summaryrefslogtreecommitdiff
path: root/setuptools
diff options
context:
space:
mode:
authorAnderson Bravalheri <andersonbravalheri@gmail.com>2022-05-19 10:48:10 +0100
committerAnderson Bravalheri <andersonbravalheri@gmail.com>2022-06-15 16:43:42 +0100
commite36951eb0afaf61a845672d060324ab3e90190d1 (patch)
treeee886414c04d6365c360c9d9f5dbda3fb6d34ecd /setuptools
parent2bddfdffbcb2fc76092d2d6029669f1bb96a742a (diff)
parent92ba2c8c4a34f40d480ee35509afc1a58f0a5f7a (diff)
downloadpython-setuptools-git-e36951eb0afaf61a845672d060324ab3e90190d1.tar.gz
Merge branch 'upstream/main' into build-editable-aggregate
Diffstat (limited to 'setuptools')
-rw-r--r--setuptools/_distutils/__init__.py2
-rw-r--r--setuptools/_distutils/_functools.py20
-rw-r--r--setuptools/_distutils/_msvccompiler.py246
-rw-r--r--setuptools/_distutils/archive_util.py74
-rw-r--r--setuptools/_distutils/bcppcompiler.py221
-rw-r--r--setuptools/_distutils/ccompiler.py442
-rw-r--r--setuptools/_distutils/cmd.py135
-rw-r--r--setuptools/_distutils/command/__init__.py53
-rw-r--r--setuptools/_distutils/command/bdist.py106
-rw-r--r--setuptools/_distutils/command/bdist_dumb.py115
-rw-r--r--setuptools/_distutils/command/bdist_msi.py929
-rw-r--r--setuptools/_distutils/command/bdist_rpm.py410
-rw-r--r--setuptools/_distutils/command/bdist_wininst.py213
-rw-r--r--setuptools/_distutils/command/build.py88
-rw-r--r--setuptools/_distutils/command/build_clib.py107
-rw-r--r--setuptools/_distutils/command/build_ext.py247
-rw-r--r--setuptools/_distutils/command/build_py.py95
-rw-r--r--setuptools/_distutils/command/build_scripts.py33
-rw-r--r--setuptools/_distutils/command/check.py111
-rw-r--r--setuptools/_distutils/command/clean.py52
-rw-r--r--setuptools/_distutils/command/config.py140
-rw-r--r--setuptools/_distutils/command/install.py343
-rw-r--r--setuptools/_distutils/command/install_data.py33
-rw-r--r--setuptools/_distutils/command/install_egg_info.py17
-rw-r--r--setuptools/_distutils/command/install_headers.py16
-rw-r--r--setuptools/_distutils/command/install_lib.py93
-rw-r--r--setuptools/_distutils/command/install_scripts.py13
-rw-r--r--setuptools/_distutils/command/py37compat.py3
-rw-r--r--setuptools/_distutils/command/register.py133
-rw-r--r--setuptools/_distutils/command/sdist.py191
-rw-r--r--setuptools/_distutils/command/upload.py39
-rw-r--r--setuptools/_distutils/config.py55
-rw-r--r--setuptools/_distutils/core.py86
-rw-r--r--setuptools/_distutils/cygwinccompiler.py161
-rw-r--r--setuptools/_distutils/dep_util.py24
-rw-r--r--setuptools/_distutils/dir_util.py63
-rw-r--r--setuptools/_distutils/dist.py331
-rw-r--r--setuptools/_distutils/errors.py66
-rw-r--r--setuptools/_distutils/extension.py74
-rw-r--r--setuptools/_distutils/fancy_getopt.py83
-rw-r--r--setuptools/_distutils/file_util.py57
-rw-r--r--setuptools/_distutils/filelist.py104
-rw-r--r--setuptools/_distutils/log.py1
-rw-r--r--setuptools/_distutils/msvc9compiler.py318
-rw-r--r--setuptools/_distutils/msvccompiler.py296
-rw-r--r--setuptools/_distutils/py35compat.py19
-rw-r--r--setuptools/_distutils/py38compat.py1
-rw-r--r--setuptools/_distutils/py39compat.py1
-rw-r--r--setuptools/_distutils/spawn.py7
-rw-r--r--setuptools/_distutils/sysconfig.py177
-rw-r--r--setuptools/_distutils/tests/py35compat.py77
-rw-r--r--setuptools/_distutils/tests/support.py13
-rw-r--r--setuptools/_distutils/tests/test_archive_util.py134
-rw-r--r--setuptools/_distutils/tests/test_bdist.py33
-rw-r--r--setuptools/_distutils/tests/test_bdist_dumb.py28
-rw-r--r--setuptools/_distutils/tests/test_bdist_msi.py9
-rw-r--r--setuptools/_distutils/tests/test_bdist_rpm.py78
-rw-r--r--setuptools/_distutils/tests/test_bdist_wininst.py20
-rw-r--r--setuptools/_distutils/tests/test_build.py9
-rw-r--r--setuptools/_distutils/tests/test_build_clib.py44
-rw-r--r--setuptools/_distutils/tests/test_build_ext.py100
-rw-r--r--setuptools/_distutils/tests/test_build_py.py37
-rw-r--r--setuptools/_distutils/tests/test_build_scripts.py60
-rw-r--r--setuptools/_distutils/tests/test_check.py96
-rw-r--r--setuptools/_distutils/tests/test_clean.py22
-rw-r--r--setuptools/_distutils/tests/test_cmd.py30
-rw-r--r--setuptools/_distutils/tests/test_config.py45
-rw-r--r--setuptools/_distutils/tests/test_config_cmd.py18
-rw-r--r--setuptools/_distutils/tests/test_core.py22
-rw-r--r--setuptools/_distutils/tests/test_cygwinccompiler.py72
-rw-r--r--setuptools/_distutils/tests/test_dep_util.py14
-rw-r--r--setuptools/_distutils/tests/test_dir_util.py33
-rw-r--r--setuptools/_distutils/tests/test_dist.py288
-rw-r--r--setuptools/_distutils/tests/test_extension.py71
-rw-r--r--setuptools/_distutils/tests/test_file_util.py13
-rw-r--r--setuptools/_distutils/tests/test_filelist.py161
-rw-r--r--setuptools/_distutils/tests/test_install.py60
-rw-r--r--setuptools/_distutils/tests/test_install_data.py16
-rw-r--r--setuptools/_distutils/tests/test_install_headers.py12
-rw-r--r--setuptools/_distutils/tests/test_install_lib.py20
-rw-r--r--setuptools/_distutils/tests/test_install_scripts.py39
-rw-r--r--setuptools/_distutils/tests/test_log.py47
-rw-r--r--setuptools/_distutils/tests/test_msvc9compiler.py22
-rw-r--r--setuptools/_distutils/tests/test_msvccompiler.py26
-rw-r--r--setuptools/_distutils/tests/test_register.py63
-rw-r--r--setuptools/_distutils/tests/test_sdist.py142
-rw-r--r--setuptools/_distutils/tests/test_spawn.py40
-rw-r--r--setuptools/_distutils/tests/test_sysconfig.py204
-rw-r--r--setuptools/_distutils/tests/test_text_file.py61
-rw-r--r--setuptools/_distutils/tests/test_unixccompiler.py70
-rw-r--r--setuptools/_distutils/tests/test_upload.py40
-rw-r--r--setuptools/_distutils/tests/test_util.py93
-rw-r--r--setuptools/_distutils/tests/test_version.py102
-rw-r--r--setuptools/_distutils/tests/test_versionpredicate.py2
-rw-r--r--setuptools/_distutils/tests/unix_compat.py3
-rw-r--r--setuptools/_distutils/text_file.py195
-rw-r--r--setuptools/_distutils/unixccompiler.py110
-rw-r--r--setuptools/_distutils/util.py174
-rw-r--r--setuptools/_distutils/version.py49
-rw-r--r--setuptools/_distutils/versionpredicate.py28
-rw-r--r--setuptools/_importlib.py11
-rw-r--r--setuptools/_vendor/pyparsing-2.2.1.dist-info/DESCRIPTION.rst3
-rw-r--r--setuptools/_vendor/pyparsing-2.2.1.dist-info/METADATA30
-rw-r--r--setuptools/_vendor/pyparsing-2.2.1.dist-info/RECORD11
-rw-r--r--setuptools/_vendor/pyparsing-2.2.1.dist-info/metadata.json1
-rw-r--r--setuptools/_vendor/pyparsing-2.2.1.dist-info/top_level.txt1
-rw-r--r--setuptools/_vendor/pyparsing-3.0.8.dist-info/INSTALLER (renamed from setuptools/_vendor/pyparsing-2.2.1.dist-info/INSTALLER)0
-rw-r--r--setuptools/_vendor/pyparsing-3.0.8.dist-info/LICENSE (renamed from setuptools/_vendor/pyparsing-2.2.1.dist-info/LICENSE.txt)36
-rw-r--r--setuptools/_vendor/pyparsing-3.0.8.dist-info/METADATA105
-rw-r--r--setuptools/_vendor/pyparsing-3.0.8.dist-info/RECORD30
-rw-r--r--setuptools/_vendor/pyparsing-3.0.8.dist-info/REQUESTED (renamed from setuptools/_vendor/pyparsing-2.2.1.dist-info/REQUESTED)0
-rw-r--r--setuptools/_vendor/pyparsing-3.0.8.dist-info/WHEEL (renamed from setuptools/_vendor/pyparsing-2.2.1.dist-info/WHEEL)4
-rw-r--r--setuptools/_vendor/pyparsing.py5742
-rw-r--r--setuptools/_vendor/pyparsing/__init__.py331
-rw-r--r--setuptools/_vendor/pyparsing/actions.py207
-rw-r--r--setuptools/_vendor/pyparsing/common.py424
-rw-r--r--setuptools/_vendor/pyparsing/core.py5812
-rw-r--r--setuptools/_vendor/pyparsing/diagram/__init__.py611
-rw-r--r--setuptools/_vendor/pyparsing/diagram/template.jinja226
-rw-r--r--setuptools/_vendor/pyparsing/exceptions.py267
-rw-r--r--setuptools/_vendor/pyparsing/helpers.py1083
-rw-r--r--setuptools/_vendor/pyparsing/py.typed0
-rw-r--r--setuptools/_vendor/pyparsing/results.py760
-rw-r--r--setuptools/_vendor/pyparsing/testing.py331
-rw-r--r--setuptools/_vendor/pyparsing/unicode.py332
-rw-r--r--setuptools/_vendor/pyparsing/util.py235
-rw-r--r--setuptools/_vendor/vendored.txt2
-rw-r--r--setuptools/command/build.py24
-rw-r--r--setuptools/command/build_py.py62
-rw-r--r--setuptools/command/dist_info.py3
-rw-r--r--setuptools/config/_apply_pyprojecttoml.py43
-rw-r--r--setuptools/config/pyprojecttoml.py5
-rw-r--r--setuptools/config/setupcfg.py12
-rw-r--r--setuptools/dist.py27
-rw-r--r--setuptools/extension.py87
-rw-r--r--setuptools/logging.py2
-rw-r--r--setuptools/tests/config/test_apply_pyprojecttoml.py49
-rw-r--r--setuptools/tests/config/test_setupcfg.py9
-rw-r--r--setuptools/tests/test_build.py63
-rw-r--r--setuptools/tests/test_build_py.py94
-rw-r--r--setuptools/tests/test_easy_install.py23
141 files changed, 16715 insertions, 9972 deletions
diff --git a/setuptools/_distutils/__init__.py b/setuptools/_distutils/__init__.py
index 8fd493b4..b3ac0146 100644
--- a/setuptools/_distutils/__init__.py
+++ b/setuptools/_distutils/__init__.py
@@ -11,7 +11,7 @@ used from a setup script as
import sys
import importlib
-__version__ = sys.version[:sys.version.index(' ')]
+__version__ = sys.version[: sys.version.index(' ')]
try:
diff --git a/setuptools/_distutils/_functools.py b/setuptools/_distutils/_functools.py
new file mode 100644
index 00000000..e7053bac
--- /dev/null
+++ b/setuptools/_distutils/_functools.py
@@ -0,0 +1,20 @@
+import functools
+
+
+# from jaraco.functools 3.5
+def pass_none(func):
+ """
+ Wrap func so it's not called if its first param is None
+
+ >>> print_text = pass_none(print)
+ >>> print_text('text')
+ text
+ >>> print_text(None)
+ """
+
+ @functools.wraps(func)
+ def wrapper(param, *args, **kwargs):
+ if param is not None:
+ return func(param, *args, **kwargs)
+
+ return wrapper
diff --git a/setuptools/_distutils/_msvccompiler.py b/setuptools/_distutils/_msvccompiler.py
index f2f801c5..3b5a8179 100644
--- a/setuptools/_distutils/_msvccompiler.py
+++ b/setuptools/_distutils/_msvccompiler.py
@@ -18,23 +18,30 @@ import subprocess
import contextlib
import warnings
import unittest.mock
+
with contextlib.suppress(ImportError):
import winreg
-from distutils.errors import DistutilsExecError, DistutilsPlatformError, \
- CompileError, LibError, LinkError
+from distutils.errors import (
+ DistutilsExecError,
+ DistutilsPlatformError,
+ CompileError,
+ LibError,
+ LinkError,
+)
from distutils.ccompiler import CCompiler, gen_lib_options
from distutils import log
from distutils.util import get_platform
from itertools import count
+
def _find_vc2015():
try:
key = winreg.OpenKeyEx(
winreg.HKEY_LOCAL_MACHINE,
r"Software\Microsoft\VisualStudio\SxS\VC7",
- access=winreg.KEY_READ | winreg.KEY_WOW64_32KEY
+ access=winreg.KEY_READ | winreg.KEY_WOW64_32KEY,
)
except OSError:
log.debug("Visual C++ is not registered")
@@ -57,6 +64,7 @@ def _find_vc2015():
best_version, best_dir = version, vc_dir
return best_version, best_dir
+
def _find_vc2017():
"""Returns "15, path" based on the result of invoking vswhere.exe
If no install is found, returns "None, None"
@@ -72,14 +80,23 @@ def _find_vc2017():
return None, None
try:
- path = subprocess.check_output([
- os.path.join(root, "Microsoft Visual Studio", "Installer", "vswhere.exe"),
- "-latest",
- "-prerelease",
- "-requires", "Microsoft.VisualStudio.Component.VC.Tools.x86.x64",
- "-property", "installationPath",
- "-products", "*",
- ], encoding="mbcs", errors="strict").strip()
+ path = subprocess.check_output(
+ [
+ os.path.join(
+ root, "Microsoft Visual Studio", "Installer", "vswhere.exe"
+ ),
+ "-latest",
+ "-prerelease",
+ "-requires",
+ "Microsoft.VisualStudio.Component.VC.Tools.x86.x64",
+ "-property",
+ "installationPath",
+ "-products",
+ "*",
+ ],
+ encoding="mbcs",
+ errors="strict",
+ ).strip()
except (subprocess.CalledProcessError, OSError, UnicodeDecodeError):
return None, None
@@ -89,13 +106,15 @@ def _find_vc2017():
return None, None
+
PLAT_SPEC_TO_RUNTIME = {
- 'x86' : 'x86',
- 'x86_amd64' : 'x64',
- 'x86_arm' : 'arm',
- 'x86_arm64' : 'arm64'
+ 'x86': 'x86',
+ 'x86_amd64': 'x64',
+ 'x86_arm': 'arm',
+ 'x86_arm64': 'arm64',
}
+
def _find_vcvarsall(plat_spec):
# bpo-38597: Removed vcruntime return value
_, best_dir = _find_vc2017()
@@ -114,12 +133,10 @@ def _find_vcvarsall(plat_spec):
return vcvarsall, None
+
def _get_vc_env(plat_spec):
if os.getenv("DISTUTILS_USE_SDK"):
- return {
- key.lower(): value
- for key, value in os.environ.items()
- }
+ return {key.lower(): value for key, value in os.environ.items()}
vcvarsall, _ = _find_vcvarsall(plat_spec)
if not vcvarsall:
@@ -132,18 +149,17 @@ def _get_vc_env(plat_spec):
).decode('utf-16le', errors='replace')
except subprocess.CalledProcessError as exc:
log.error(exc.output)
- raise DistutilsPlatformError("Error executing {}"
- .format(exc.cmd))
+ raise DistutilsPlatformError("Error executing {}".format(exc.cmd))
env = {
key.lower(): value
- for key, _, value in
- (line.partition('=') for line in out.splitlines())
+ for key, _, value in (line.partition('=') for line in out.splitlines())
if key and value
}
return env
+
def _find_exe(exe, paths=None):
"""Return path to an MSVC executable program.
@@ -161,19 +177,21 @@ def _find_exe(exe, paths=None):
return fn
return exe
+
# A map keyed by get_platform() return values to values accepted by
# 'vcvarsall.bat'. Always cross-compile from x86 to work with the
# lighter-weight MSVC installs that do not include native 64-bit tools.
PLAT_TO_VCVARS = {
- 'win32' : 'x86',
- 'win-amd64' : 'x86_amd64',
- 'win-arm32' : 'x86_arm',
- 'win-arm64' : 'x86_arm64'
+ 'win32': 'x86',
+ 'win-amd64': 'x86_amd64',
+ 'win-arm32': 'x86_arm',
+ 'win-arm64': 'x86_arm64',
}
-class MSVCCompiler(CCompiler) :
+
+class MSVCCompiler(CCompiler):
"""Concrete class that implements an interface to Microsoft Visual C++,
- as defined by the CCompiler abstract class."""
+ as defined by the CCompiler abstract class."""
compiler_type = 'msvc'
@@ -192,8 +210,7 @@ class MSVCCompiler(CCompiler) :
# Needed for the filename generation methods provided by the
# base class, CCompiler.
- src_extensions = (_c_extensions + _cpp_extensions +
- _rc_extensions + _mc_extensions)
+ src_extensions = _c_extensions + _cpp_extensions + _rc_extensions + _mc_extensions
res_extension = '.res'
obj_extension = '.obj'
static_lib_extension = '.lib'
@@ -201,7 +218,6 @@ class MSVCCompiler(CCompiler) :
static_lib_format = shared_lib_format = '%s%s'
exe_extension = '.exe'
-
def __init__(self, verbose=0, dry_run=0, force=0):
super().__init__(verbose, dry_run, force)
# target platform (.plat_name is consistent with 'bdist')
@@ -215,25 +231,27 @@ class MSVCCompiler(CCompiler) :
plat_name = get_platform()
# sanity check for platforms to prevent obscure errors later.
if plat_name not in PLAT_TO_VCVARS:
- raise DistutilsPlatformError("--plat-name must be one of {}"
- .format(tuple(PLAT_TO_VCVARS)))
+ raise DistutilsPlatformError(
+ "--plat-name must be one of {}".format(tuple(PLAT_TO_VCVARS))
+ )
# Get the vcvarsall.bat spec for the requested platform.
plat_spec = PLAT_TO_VCVARS[plat_name]
vc_env = _get_vc_env(plat_spec)
if not vc_env:
- raise DistutilsPlatformError("Unable to find a compatible "
- "Visual Studio installation.")
+ raise DistutilsPlatformError(
+ "Unable to find a compatible " "Visual Studio installation."
+ )
self._paths = vc_env.get('path', '')
paths = self._paths.split(os.pathsep)
self.cc = _find_exe("cl.exe", paths)
self.linker = _find_exe("link.exe", paths)
self.lib = _find_exe("lib.exe", paths)
- self.rc = _find_exe("rc.exe", paths) # resource compiler
- self.mc = _find_exe("mc.exe", paths) # message compiler
- self.mt = _find_exe("mt.exe", paths) # message compiler
+ self.rc = _find_exe("rc.exe", paths) # resource compiler
+ self.mc = _find_exe("mc.exe", paths) # message compiler
+ self.mt = _find_exe("mt.exe", paths) # message compiler
for dir in vc_env.get('include', '').split(os.pathsep):
if dir:
@@ -247,26 +265,35 @@ class MSVCCompiler(CCompiler) :
# bpo-38597: Always compile with dynamic linking
# Future releases of Python 3.x will include all past
# versions of vcruntime*.dll for compatibility.
- self.compile_options = [
- '/nologo', '/O2', '/W3', '/GL', '/DNDEBUG', '/MD'
- ]
+ self.compile_options = ['/nologo', '/O2', '/W3', '/GL', '/DNDEBUG', '/MD']
self.compile_options_debug = [
- '/nologo', '/Od', '/MDd', '/Zi', '/W3', '/D_DEBUG'
+ '/nologo',
+ '/Od',
+ '/MDd',
+ '/Zi',
+ '/W3',
+ '/D_DEBUG',
]
- ldflags = [
- '/nologo', '/INCREMENTAL:NO', '/LTCG'
- ]
+ ldflags = ['/nologo', '/INCREMENTAL:NO', '/LTCG']
- ldflags_debug = [
- '/nologo', '/INCREMENTAL:NO', '/LTCG', '/DEBUG:FULL'
- ]
+ ldflags_debug = ['/nologo', '/INCREMENTAL:NO', '/LTCG', '/DEBUG:FULL']
self.ldflags_exe = [*ldflags, '/MANIFEST:EMBED,ID=1']
self.ldflags_exe_debug = [*ldflags_debug, '/MANIFEST:EMBED,ID=1']
- self.ldflags_shared = [*ldflags, '/DLL', '/MANIFEST:EMBED,ID=2', '/MANIFESTUAC:NO']
- self.ldflags_shared_debug = [*ldflags_debug, '/DLL', '/MANIFEST:EMBED,ID=2', '/MANIFESTUAC:NO']
+ self.ldflags_shared = [
+ *ldflags,
+ '/DLL',
+ '/MANIFEST:EMBED,ID=2',
+ '/MANIFESTUAC:NO',
+ ]
+ self.ldflags_shared_debug = [
+ *ldflags_debug,
+ '/DLL',
+ '/MANIFEST:EMBED,ID=2',
+ '/MANIFESTUAC:NO',
+ ]
self.ldflags_static = [*ldflags]
self.ldflags_static_debug = [*ldflags_debug]
@@ -286,13 +313,13 @@ class MSVCCompiler(CCompiler) :
# -- Worker methods ------------------------------------------------
- def object_filenames(self,
- source_filenames,
- strip_dir=0,
- output_dir=''):
+ def object_filenames(self, source_filenames, strip_dir=0, output_dir=''):
ext_map = {
**{ext: self.obj_extension for ext in self.src_extensions},
- **{ext: self.res_extension for ext in self._rc_extensions + self._mc_extensions},
+ **{
+ ext: self.res_extension
+ for ext in self._rc_extensions + self._mc_extensions
+ },
}
output_dir = output_dir or ''
@@ -318,15 +345,23 @@ class MSVCCompiler(CCompiler) :
return list(map(make_out_path, source_filenames))
-
- def compile(self, sources,
- output_dir=None, macros=None, include_dirs=None, debug=0,
- extra_preargs=None, extra_postargs=None, depends=None):
+ def compile(
+ self,
+ sources,
+ output_dir=None,
+ macros=None,
+ include_dirs=None,
+ debug=0,
+ extra_preargs=None,
+ extra_postargs=None,
+ depends=None,
+ ):
if not self.initialized:
self.initialize()
- compile_info = self._setup_compile(output_dir, macros, include_dirs,
- sources, depends, extra_postargs)
+ compile_info = self._setup_compile(
+ output_dir, macros, include_dirs, sources, depends, extra_postargs
+ )
macros, objects, extra_postargs, pp_opts, build = compile_info
compile_opts = extra_preargs or []
@@ -336,7 +371,6 @@ class MSVCCompiler(CCompiler) :
else:
compile_opts.extend(self.compile_options)
-
add_cpp_opts = False
for obj in objects:
@@ -381,7 +415,7 @@ class MSVCCompiler(CCompiler) :
try:
# first compile .MC to .RC and .H file
self.spawn([self.mc, '-h', h_dir, '-r', rc_dir, src])
- base, _ = os.path.splitext(os.path.basename (src))
+ base, _ = os.path.splitext(os.path.basename(src))
rc_file = os.path.join(rc_dir, base + '.rc')
# then compile .RC to .RES file
self.spawn([self.rc, "/fo" + obj, rc_file])
@@ -391,8 +425,9 @@ class MSVCCompiler(CCompiler) :
continue
else:
# how to handle this file?
- raise CompileError("Don't know how to compile {} to {}"
- .format(src, obj))
+ raise CompileError(
+ "Don't know how to compile {} to {}".format(src, obj)
+ )
args = [self.cc] + compile_opts + pp_opts
if add_cpp_opts:
@@ -408,24 +443,19 @@ class MSVCCompiler(CCompiler) :
return objects
-
- def create_static_lib(self,
- objects,
- output_libname,
- output_dir=None,
- debug=0,
- target_lang=None):
+ def create_static_lib(
+ self, objects, output_libname, output_dir=None, debug=0, target_lang=None
+ ):
if not self.initialized:
self.initialize()
objects, output_dir = self._fix_object_args(objects, output_dir)
- output_filename = self.library_filename(output_libname,
- output_dir=output_dir)
+ output_filename = self.library_filename(output_libname, output_dir=output_dir)
if self._need_link(objects, output_filename):
lib_args = objects + ['/OUT:' + output_filename]
if debug:
- pass # XXX what goes here?
+ pass # XXX what goes here?
try:
log.debug('Executing "%s" %s', self.lib, ' '.join(lib_args))
self.spawn([self.lib] + lib_args)
@@ -434,36 +464,36 @@ class MSVCCompiler(CCompiler) :
else:
log.debug("skipping %s (up-to-date)", output_filename)
-
- def link(self,
- target_desc,
- objects,
- output_filename,
- output_dir=None,
- libraries=None,
- library_dirs=None,
- runtime_library_dirs=None,
- export_symbols=None,
- debug=0,
- extra_preargs=None,
- extra_postargs=None,
- build_temp=None,
- target_lang=None):
+ def link(
+ self,
+ target_desc,
+ objects,
+ output_filename,
+ output_dir=None,
+ libraries=None,
+ library_dirs=None,
+ runtime_library_dirs=None,
+ export_symbols=None,
+ debug=0,
+ extra_preargs=None,
+ extra_postargs=None,
+ build_temp=None,
+ target_lang=None,
+ ):
if not self.initialized:
self.initialize()
objects, output_dir = self._fix_object_args(objects, output_dir)
- fixed_args = self._fix_lib_args(libraries, library_dirs,
- runtime_library_dirs)
+ fixed_args = self._fix_lib_args(libraries, library_dirs, runtime_library_dirs)
libraries, library_dirs, runtime_library_dirs = fixed_args
if runtime_library_dirs:
- self.warn("I don't know what to do with 'runtime_library_dirs': "
- + str(runtime_library_dirs))
+ self.warn(
+ "I don't know what to do with 'runtime_library_dirs': "
+ + str(runtime_library_dirs)
+ )
- lib_opts = gen_lib_options(self,
- library_dirs, runtime_library_dirs,
- libraries)
+ lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, libraries)
if output_dir is not None:
output_filename = os.path.join(output_dir, output_filename)
@@ -472,8 +502,9 @@ class MSVCCompiler(CCompiler) :
export_opts = ["/EXPORT:" + sym for sym in (export_symbols or [])]
- ld_args = (ldflags + lib_opts + export_opts +
- objects + ['/OUT:' + output_filename])
+ ld_args = (
+ ldflags + lib_opts + export_opts + objects + ['/OUT:' + output_filename]
+ )
# The MSVC linker generates .lib and .exp files, which cannot be
# suppressed by any linker switches. The .lib files may even be
@@ -483,11 +514,10 @@ class MSVCCompiler(CCompiler) :
build_temp = os.path.dirname(objects[0])
if export_symbols is not None:
(dll_name, dll_ext) = os.path.splitext(
- os.path.basename(output_filename))
- implib_file = os.path.join(
- build_temp,
- self.library_filename(dll_name))
- ld_args.append ('/IMPLIB:' + implib_file)
+ os.path.basename(output_filename)
+ )
+ implib_file = os.path.join(build_temp, self.library_filename(dll_name))
+ ld_args.append('/IMPLIB:' + implib_file)
if extra_preargs:
ld_args[:0] = extra_preargs
@@ -525,8 +555,7 @@ class MSVCCompiler(CCompiler) :
raise
else:
return
- warnings.warn(
- "Fallback spawn triggered. Please update distutils monkeypatch.")
+ warnings.warn("Fallback spawn triggered. Please update distutils monkeypatch.")
with unittest.mock.patch.dict('os.environ', env):
bag.value = super().spawn(cmd)
@@ -539,7 +568,8 @@ class MSVCCompiler(CCompiler) :
def runtime_library_dir_option(self, dir):
raise DistutilsPlatformError(
- "don't know how to set runtime library search path for MSVC")
+ "don't know how to set runtime library search path for MSVC"
+ )
def library_option(self, lib):
return self.library_filename(lib)
diff --git a/setuptools/_distutils/archive_util.py b/setuptools/_distutils/archive_util.py
index 565a3117..5a70c32c 100644
--- a/setuptools/_distutils/archive_util.py
+++ b/setuptools/_distutils/archive_util.py
@@ -28,6 +28,7 @@ try:
except ImportError:
getgrnam = None
+
def _get_gid(name):
"""Returns a gid, given a group name."""
if getgrnam is None or name is None:
@@ -40,6 +41,7 @@ def _get_gid(name):
return result[2]
return None
+
def _get_uid(name):
"""Returns an uid, given a user name."""
if getpwnam is None or name is None:
@@ -52,8 +54,10 @@ def _get_uid(name):
return result[2]
return None
-def make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0,
- owner=None, group=None):
+
+def make_tarball(
+ base_name, base_dir, compress="gzip", verbose=0, dry_run=0, owner=None, group=None
+):
"""Create a (possibly compressed) tar file from all the files under
'base_dir'.
@@ -69,16 +73,21 @@ def make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0,
Returns the output filename.
"""
- tar_compression = {'gzip': 'gz', 'bzip2': 'bz2', 'xz': 'xz', None: '',
- 'compress': ''}
- compress_ext = {'gzip': '.gz', 'bzip2': '.bz2', 'xz': '.xz',
- 'compress': '.Z'}
+ tar_compression = {
+ 'gzip': 'gz',
+ 'bzip2': 'bz2',
+ 'xz': 'xz',
+ None: '',
+ 'compress': '',
+ }
+ compress_ext = {'gzip': '.gz', 'bzip2': '.bz2', 'xz': '.xz', 'compress': '.Z'}
# flags for compression program, each element of list will be an argument
if compress is not None and compress not in compress_ext.keys():
raise ValueError(
- "bad value for 'compress': must be None, 'gzip', 'bzip2', "
- "'xz' or 'compress'")
+ "bad value for 'compress': must be None, 'gzip', 'bzip2', "
+ "'xz' or 'compress'"
+ )
archive_name = base_name + '.tar'
if compress != 'compress':
@@ -124,6 +133,7 @@ def make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0,
return archive_name
+
def make_zipfile(base_name, base_dir, verbose=0, dry_run=0):
"""Create a zip file from all the files under 'base_dir'.
@@ -145,26 +155,29 @@ def make_zipfile(base_name, base_dir, verbose=0, dry_run=0):
zipoptions = "-rq"
try:
- spawn(["zip", zipoptions, zip_filename, base_dir],
- dry_run=dry_run)
+ spawn(["zip", zipoptions, zip_filename, base_dir], dry_run=dry_run)
except DistutilsExecError:
# XXX really should distinguish between "couldn't find
# external 'zip' command" and "zip failed".
- raise DistutilsExecError(("unable to create zip file '%s': "
- "could neither import the 'zipfile' module nor "
- "find a standalone zip utility") % zip_filename)
+ raise DistutilsExecError(
+ (
+ "unable to create zip file '%s': "
+ "could neither import the 'zipfile' module nor "
+ "find a standalone zip utility"
+ )
+ % zip_filename
+ )
else:
- log.info("creating '%s' and adding '%s' to it",
- zip_filename, base_dir)
+ log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir)
if not dry_run:
try:
- zip = zipfile.ZipFile(zip_filename, "w",
- compression=zipfile.ZIP_DEFLATED)
+ zip = zipfile.ZipFile(
+ zip_filename, "w", compression=zipfile.ZIP_DEFLATED
+ )
except RuntimeError:
- zip = zipfile.ZipFile(zip_filename, "w",
- compression=zipfile.ZIP_STORED)
+ zip = zipfile.ZipFile(zip_filename, "w", compression=zipfile.ZIP_STORED)
with zip:
if base_dir != os.curdir:
@@ -184,14 +197,16 @@ def make_zipfile(base_name, base_dir, verbose=0, dry_run=0):
return zip_filename
+
ARCHIVE_FORMATS = {
'gztar': (make_tarball, [('compress', 'gzip')], "gzip'ed tar-file"),
'bztar': (make_tarball, [('compress', 'bzip2')], "bzip2'ed tar-file"),
'xztar': (make_tarball, [('compress', 'xz')], "xz'ed tar-file"),
- 'ztar': (make_tarball, [('compress', 'compress')], "compressed tar file"),
- 'tar': (make_tarball, [('compress', None)], "uncompressed tar file"),
- 'zip': (make_zipfile, [],"ZIP file")
- }
+ 'ztar': (make_tarball, [('compress', 'compress')], "compressed tar file"),
+ 'tar': (make_tarball, [('compress', None)], "uncompressed tar file"),
+ 'zip': (make_zipfile, [], "ZIP file"),
+}
+
def check_archive_formats(formats):
"""Returns the first format from the 'format' list that is unknown.
@@ -203,8 +218,17 @@ def check_archive_formats(formats):
return format
return None
-def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0,
- dry_run=0, owner=None, group=None):
+
+def make_archive(
+ base_name,
+ format,
+ root_dir=None,
+ base_dir=None,
+ verbose=0,
+ dry_run=0,
+ owner=None,
+ group=None,
+):
"""Create an archive file (eg. zip or tar).
'base_name' is the name of the file to create, minus any format-specific
diff --git a/setuptools/_distutils/bcppcompiler.py b/setuptools/_distutils/bcppcompiler.py
index 2eb6d2e9..056b2d98 100644
--- a/setuptools/_distutils/bcppcompiler.py
+++ b/setuptools/_distutils/bcppcompiler.py
@@ -13,16 +13,20 @@ for the Borland C++ compiler.
import os
-from distutils.errors import \
- DistutilsExecError, \
- CompileError, LibError, LinkError, UnknownFileError
-from distutils.ccompiler import \
- CCompiler, gen_preprocess_options
+from distutils.errors import (
+ DistutilsExecError,
+ CompileError,
+ LibError,
+ LinkError,
+ UnknownFileError,
+)
+from distutils.ccompiler import CCompiler, gen_preprocess_options
from distutils.file_util import write_file
from distutils.dep_util import newer
from distutils import log
-class BCPPCompiler(CCompiler) :
+
+class BCPPCompiler(CCompiler):
"""Concrete class that implements an interface to the Borland C/C++
compiler, as defined by the CCompiler abstract class.
"""
@@ -49,11 +53,7 @@ class BCPPCompiler(CCompiler) :
static_lib_format = shared_lib_format = '%s%s'
exe_extension = '.exe'
-
- def __init__ (self,
- verbose=0,
- dry_run=0,
- force=0):
+ def __init__(self, verbose=0, dry_run=0, force=0):
super().__init__(verbose, dry_run, force)
@@ -73,24 +73,31 @@ class BCPPCompiler(CCompiler) :
self.ldflags_shared_debug = ['/Tpd', '/Gn', '/q', '/x']
self.ldflags_static = []
self.ldflags_exe = ['/Gn', '/q', '/x']
- self.ldflags_exe_debug = ['/Gn', '/q', '/x','/r']
-
+ self.ldflags_exe_debug = ['/Gn', '/q', '/x', '/r']
# -- Worker methods ------------------------------------------------
- def compile(self, sources,
- output_dir=None, macros=None, include_dirs=None, debug=0,
- extra_preargs=None, extra_postargs=None, depends=None):
-
- macros, objects, extra_postargs, pp_opts, build = \
- self._setup_compile(output_dir, macros, include_dirs, sources,
- depends, extra_postargs)
+ def compile(
+ self,
+ sources,
+ output_dir=None,
+ macros=None,
+ include_dirs=None,
+ debug=0,
+ extra_preargs=None,
+ extra_postargs=None,
+ depends=None,
+ ):
+
+ macros, objects, extra_postargs, pp_opts, build = self._setup_compile(
+ output_dir, macros, include_dirs, sources, depends, extra_postargs
+ )
compile_opts = extra_preargs or []
- compile_opts.append ('-c')
+ compile_opts.append('-c')
if debug:
- compile_opts.extend (self.compile_options_debug)
+ compile_opts.extend(self.compile_options_debug)
else:
- compile_opts.extend (self.compile_options)
+ compile_opts.extend(self.compile_options)
for obj in objects:
try:
@@ -106,14 +113,14 @@ class BCPPCompiler(CCompiler) :
if ext == '.res':
# This is already a binary file -- skip it.
- continue # the 'for' loop
+ continue # the 'for' loop
if ext == '.rc':
# This needs to be compiled to a .res file -- do it now.
try:
- self.spawn (["brcc32", "-fo", obj, src])
+ self.spawn(["brcc32", "-fo", obj, src])
except DistutilsExecError as msg:
raise CompileError(msg)
- continue # the 'for' loop
+ continue # the 'for' loop
# The next two are both for the real compiler.
if ext in self._c_extensions:
@@ -132,9 +139,14 @@ class BCPPCompiler(CCompiler) :
# Note that the source file names must appear at the end of
# the command line.
try:
- self.spawn ([self.cc] + compile_opts + pp_opts +
- [input_opt, output_opt] +
- extra_postargs + [src])
+ self.spawn(
+ [self.cc]
+ + compile_opts
+ + pp_opts
+ + [input_opt, output_opt]
+ + extra_postargs
+ + [src]
+ )
except DistutilsExecError as msg:
raise CompileError(msg)
@@ -142,24 +154,19 @@ class BCPPCompiler(CCompiler) :
# compile ()
+ def create_static_lib(
+ self, objects, output_libname, output_dir=None, debug=0, target_lang=None
+ ):
- def create_static_lib (self,
- objects,
- output_libname,
- output_dir=None,
- debug=0,
- target_lang=None):
-
- (objects, output_dir) = self._fix_object_args (objects, output_dir)
- output_filename = \
- self.library_filename (output_libname, output_dir=output_dir)
+ (objects, output_dir) = self._fix_object_args(objects, output_dir)
+ output_filename = self.library_filename(output_libname, output_dir=output_dir)
- if self._need_link (objects, output_filename):
+ if self._need_link(objects, output_filename):
lib_args = [output_filename, '/u'] + objects
if debug:
- pass # XXX what goes here?
+ pass # XXX what goes here?
try:
- self.spawn ([self.lib] + lib_args)
+ self.spawn([self.lib] + lib_args)
except DistutilsExecError as msg:
raise LibError(msg)
else:
@@ -167,37 +174,41 @@ class BCPPCompiler(CCompiler) :
# create_static_lib ()
-
- def link (self,
- target_desc,
- objects,
- output_filename,
- output_dir=None,
- libraries=None,
- library_dirs=None,
- runtime_library_dirs=None,
- export_symbols=None,
- debug=0,
- extra_preargs=None,
- extra_postargs=None,
- build_temp=None,
- target_lang=None):
+ def link(
+ self,
+ target_desc,
+ objects,
+ output_filename,
+ output_dir=None,
+ libraries=None,
+ library_dirs=None,
+ runtime_library_dirs=None,
+ export_symbols=None,
+ debug=0,
+ extra_preargs=None,
+ extra_postargs=None,
+ build_temp=None,
+ target_lang=None,
+ ):
# XXX this ignores 'build_temp'! should follow the lead of
# msvccompiler.py
- (objects, output_dir) = self._fix_object_args (objects, output_dir)
- (libraries, library_dirs, runtime_library_dirs) = \
- self._fix_lib_args (libraries, library_dirs, runtime_library_dirs)
+ (objects, output_dir) = self._fix_object_args(objects, output_dir)
+ (libraries, library_dirs, runtime_library_dirs) = self._fix_lib_args(
+ libraries, library_dirs, runtime_library_dirs
+ )
if runtime_library_dirs:
- log.warn("I don't know what to do with 'runtime_library_dirs': %s",
- str(runtime_library_dirs))
+ log.warn(
+ "I don't know what to do with 'runtime_library_dirs': %s",
+ str(runtime_library_dirs),
+ )
if output_dir is not None:
- output_filename = os.path.join (output_dir, output_filename)
+ output_filename = os.path.join(output_dir, output_filename)
- if self._need_link (objects, output_filename):
+ if self._need_link(objects, output_filename):
# Figure out linker args based on type of target.
if target_desc == CCompiler.EXECUTABLE:
@@ -213,20 +224,18 @@ class BCPPCompiler(CCompiler) :
else:
ld_args = self.ldflags_shared[:]
-
# Create a temporary exports file for use by the linker
if export_symbols is None:
def_file = ''
else:
- head, tail = os.path.split (output_filename)
- modname, ext = os.path.splitext (tail)
- temp_dir = os.path.dirname(objects[0]) # preserve tree structure
- def_file = os.path.join (temp_dir, '%s.def' % modname)
+ head, tail = os.path.split(output_filename)
+ modname, ext = os.path.splitext(tail)
+ temp_dir = os.path.dirname(objects[0]) # preserve tree structure
+ def_file = os.path.join(temp_dir, '%s.def' % modname)
contents = ['EXPORTS']
- for sym in (export_symbols or []):
+ for sym in export_symbols or []:
contents.append(' %s=_%s' % (sym, sym))
- self.execute(write_file, (def_file, contents),
- "writing %s" % def_file)
+ self.execute(write_file, (def_file, contents), "writing %s" % def_file)
# Borland C++ has problems with '/' in paths
objects2 = map(os.path.normpath, objects)
@@ -241,10 +250,9 @@ class BCPPCompiler(CCompiler) :
else:
objects.append(file)
-
for l in library_dirs:
ld_args.append("/L%s" % os.path.normpath(l))
- ld_args.append("/L.") # we sometimes use relative paths
+ ld_args.append("/L.") # we sometimes use relative paths
# list of object files
ld_args.extend(objects)
@@ -260,7 +268,7 @@ class BCPPCompiler(CCompiler) :
# them. Arghghh!. Apparently it works fine as coded...
# name of dll/exe file
- ld_args.extend([',',output_filename])
+ ld_args.extend([',', output_filename])
# no map file and start libraries
ld_args.append(',,')
@@ -276,24 +284,23 @@ class BCPPCompiler(CCompiler) :
ld_args.append(libfile)
# some default libraries
- ld_args.append ('import32')
- ld_args.append ('cw32mt')
+ ld_args.append('import32')
+ ld_args.append('cw32mt')
# def file for export symbols
- ld_args.extend([',',def_file])
+ ld_args.extend([',', def_file])
# add resource files
ld_args.append(',')
ld_args.extend(resources)
-
if extra_preargs:
ld_args[:0] = extra_preargs
if extra_postargs:
ld_args.extend(extra_postargs)
- self.mkpath (os.path.dirname (output_filename))
+ self.mkpath(os.path.dirname(output_filename))
try:
- self.spawn ([self.linker] + ld_args)
+ self.spawn([self.linker] + ld_args)
except DistutilsExecError as msg:
raise LinkError(msg)
@@ -304,8 +311,7 @@ class BCPPCompiler(CCompiler) :
# -- Miscellaneous methods -----------------------------------------
-
- def find_library_file (self, dirs, lib, debug=0):
+ def find_library_file(self, dirs, lib, debug=0):
# List of effective library names to try, in order of preference:
# xxx_bcpp.lib is better than xxx.lib
# and xxx_d.lib is better than xxx.lib if debug is set
@@ -316,7 +322,7 @@ class BCPPCompiler(CCompiler) :
# compiler they care about, since (almost?) every Windows compiler
# seems to have a different format for static libraries.
if debug:
- dlib = (lib + "_d")
+ dlib = lib + "_d"
try_names = (dlib + "_bcpp", lib + "_bcpp", dlib, lib)
else:
try_names = (lib + "_bcpp", lib)
@@ -331,43 +337,42 @@ class BCPPCompiler(CCompiler) :
return None
# overwrite the one from CCompiler to support rc and res-files
- def object_filenames (self,
- source_filenames,
- strip_dir=0,
- output_dir=''):
- if output_dir is None: output_dir = ''
+ def object_filenames(self, source_filenames, strip_dir=0, output_dir=''):
+ if output_dir is None:
+ output_dir = ''
obj_names = []
for src_name in source_filenames:
# use normcase to make sure '.rc' is really '.rc' and not '.RC'
- (base, ext) = os.path.splitext (os.path.normcase(src_name))
- if ext not in (self.src_extensions + ['.rc','.res']):
- raise UnknownFileError("unknown file type '%s' (from '%s')" % \
- (ext, src_name))
+ (base, ext) = os.path.splitext(os.path.normcase(src_name))
+ if ext not in (self.src_extensions + ['.rc', '.res']):
+ raise UnknownFileError(
+ "unknown file type '%s' (from '%s')" % (ext, src_name)
+ )
if strip_dir:
- base = os.path.basename (base)
+ base = os.path.basename(base)
if ext == '.res':
# these can go unchanged
- obj_names.append (os.path.join (output_dir, base + ext))
+ obj_names.append(os.path.join(output_dir, base + ext))
elif ext == '.rc':
# these need to be compiled to .res-files
- obj_names.append (os.path.join (output_dir, base + '.res'))
+ obj_names.append(os.path.join(output_dir, base + '.res'))
else:
- obj_names.append (os.path.join (output_dir,
- base + self.obj_extension))
+ obj_names.append(os.path.join(output_dir, base + self.obj_extension))
return obj_names
# object_filenames ()
- def preprocess (self,
- source,
- output_file=None,
- macros=None,
- include_dirs=None,
- extra_preargs=None,
- extra_postargs=None):
-
- (_, macros, include_dirs) = \
- self._fix_compile_args(None, macros, include_dirs)
+ def preprocess(
+ self,
+ source,
+ output_file=None,
+ macros=None,
+ include_dirs=None,
+ extra_preargs=None,
+ extra_postargs=None,
+ ):
+
+ (_, macros, include_dirs) = self._fix_compile_args(None, macros, include_dirs)
pp_opts = gen_preprocess_options(macros, include_dirs)
pp_args = ['cpp32.exe'] + pp_opts
if output_file is not None:
diff --git a/setuptools/_distutils/ccompiler.py b/setuptools/_distutils/ccompiler.py
index 777fc661..005b64ac 100644
--- a/setuptools/_distutils/ccompiler.py
+++ b/setuptools/_distutils/ccompiler.py
@@ -12,6 +12,7 @@ from distutils.dep_util import newer_group
from distutils.util import split_quoted, execute
from distutils import log
+
class CCompiler:
"""Abstract base class to define the interface that must be implemented
by real compiler classes. Also has some utility methods used by
@@ -56,17 +57,16 @@ class CCompiler:
# think this is useless without the ability to null out the
# library search path anyways.
-
# Subclasses that rely on the standard filename generation methods
# implemented below should override these; see the comment near
# those methods ('object_filenames()' et. al.) for details:
- src_extensions = None # list of strings
- obj_extension = None # string
+ src_extensions = None # list of strings
+ obj_extension = None # string
static_lib_extension = None
- shared_lib_extension = None # string
- static_lib_format = None # format string
- shared_lib_format = None # prob. same as static_lib_format
- exe_extension = None # string
+ shared_lib_extension = None # string
+ static_lib_format = None # format string
+ shared_lib_format = None # prob. same as static_lib_format
+ exe_extension = None # string
# Default language settings. language_map is used to detect a source
# file or Extension target language, checking source filenames.
@@ -74,12 +74,13 @@ class CCompiler:
# what language to use when mixing source types. For example, if some
# extension has two files with ".c" extension, and one with ".cpp", it
# is still linked as c++.
- language_map = {".c" : "c",
- ".cc" : "c++",
- ".cpp" : "c++",
- ".cxx" : "c++",
- ".m" : "objc",
- }
+ language_map = {
+ ".c": "c",
+ ".cc": "c++",
+ ".cpp": "c++",
+ ".cxx": "c++",
+ ".m": "objc",
+ }
language_order = ["c++", "objc", "c"]
def __init__(self, verbose=0, dry_run=0, force=0):
@@ -146,8 +147,10 @@ class CCompiler:
for key in kwargs:
if key not in self.executables:
- raise ValueError("unknown executable '%s' for class %s" %
- (key, self.__class__.__name__))
+ raise ValueError(
+ "unknown executable '%s' for class %s"
+ % (key, self.__class__.__name__)
+ )
self.set_executable(key, kwargs[key])
def set_executable(self, key, value):
@@ -170,14 +173,19 @@ class CCompiler:
nothing if all definitions are OK, raise TypeError otherwise.
"""
for defn in definitions:
- if not (isinstance(defn, tuple) and
- (len(defn) in (1, 2) and
- (isinstance (defn[1], str) or defn[1] is None)) and
- isinstance (defn[0], str)):
- raise TypeError(("invalid macro definition '%s': " % defn) + \
- "must be tuple (string,), (string, string), or " + \
- "(string, None)")
-
+ if not (
+ isinstance(defn, tuple)
+ and (
+ len(defn) in (1, 2)
+ and (isinstance(defn[1], str) or defn[1] is None)
+ )
+ and isinstance(defn[0], str)
+ ):
+ raise TypeError(
+ ("invalid macro definition '%s': " % defn)
+ + "must be tuple (string,), (string, string), or "
+ + "(string, None)"
+ )
# -- Bookkeeping methods -------------------------------------------
@@ -190,7 +198,7 @@ class CCompiler:
"""
# Delete from the list of macro definitions/undefinitions if
# already there (so that this one will take precedence).
- i = self._find_macro (name)
+ i = self._find_macro(name)
if i is not None:
del self.macros[i]
@@ -207,7 +215,7 @@ class CCompiler:
"""
# Delete from the list of macro definitions/undefinitions if
# already there (so that this one will take precedence).
- i = self._find_macro (name)
+ i = self._find_macro(name)
if i is not None:
del self.macros[i]
@@ -301,14 +309,12 @@ class CCompiler:
"""
self.objects = objects[:]
-
# -- Private utility methods --------------------------------------
# (here for the convenience of subclasses)
# Helper method to prep compiler in subclass compile() methods
- def _setup_compile(self, outdir, macros, incdirs, sources, depends,
- extra):
+ def _setup_compile(self, outdir, macros, incdirs, sources, depends, extra):
"""Process arguments and decide which source files to compile."""
if outdir is None:
outdir = self.output_dir
@@ -327,15 +333,13 @@ class CCompiler:
elif isinstance(incdirs, (list, tuple)):
incdirs = list(incdirs) + (self.include_dirs or [])
else:
- raise TypeError(
- "'include_dirs' (if supplied) must be a list of strings")
+ raise TypeError("'include_dirs' (if supplied) must be a list of strings")
if extra is None:
extra = []
# Get the list of expected output (object) files
- objects = self.object_filenames(sources, strip_dir=0,
- output_dir=outdir)
+ objects = self.object_filenames(sources, strip_dir=0, output_dir=outdir)
assert len(objects) == len(sources)
pp_opts = gen_preprocess_options(macros, incdirs)
@@ -386,8 +390,7 @@ class CCompiler:
elif isinstance(include_dirs, (list, tuple)):
include_dirs = list(include_dirs) + (self.include_dirs or [])
else:
- raise TypeError(
- "'include_dirs' (if supplied) must be a list of strings")
+ raise TypeError("'include_dirs' (if supplied) must be a list of strings")
return output_dir, macros, include_dirs
@@ -434,27 +437,27 @@ class CCompiler:
if libraries is None:
libraries = self.libraries
elif isinstance(libraries, (list, tuple)):
- libraries = list (libraries) + (self.libraries or [])
+ libraries = list(libraries) + (self.libraries or [])
else:
- raise TypeError(
- "'libraries' (if supplied) must be a list of strings")
+ raise TypeError("'libraries' (if supplied) must be a list of strings")
if library_dirs is None:
library_dirs = self.library_dirs
elif isinstance(library_dirs, (list, tuple)):
- library_dirs = list (library_dirs) + (self.library_dirs or [])
+ library_dirs = list(library_dirs) + (self.library_dirs or [])
else:
- raise TypeError(
- "'library_dirs' (if supplied) must be a list of strings")
+ raise TypeError("'library_dirs' (if supplied) must be a list of strings")
if runtime_library_dirs is None:
runtime_library_dirs = self.runtime_library_dirs
elif isinstance(runtime_library_dirs, (list, tuple)):
- runtime_library_dirs = (list(runtime_library_dirs) +
- (self.runtime_library_dirs or []))
+ runtime_library_dirs = list(runtime_library_dirs) + (
+ self.runtime_library_dirs or []
+ )
else:
- raise TypeError("'runtime_library_dirs' (if supplied) "
- "must be a list of strings")
+ raise TypeError(
+ "'runtime_library_dirs' (if supplied) " "must be a list of strings"
+ )
return (libraries, library_dirs, runtime_library_dirs)
@@ -466,9 +469,9 @@ class CCompiler:
return True
else:
if self.dry_run:
- newer = newer_group (objects, output_file, missing='newer')
+ newer = newer_group(objects, output_file, missing='newer')
else:
- newer = newer_group (objects, output_file)
+ newer = newer_group(objects, output_file)
return newer
def detect_language(self, sources):
@@ -491,12 +494,18 @@ class CCompiler:
pass
return lang
-
# -- Worker methods ------------------------------------------------
# (must be implemented by subclasses)
- def preprocess(self, source, output_file=None, macros=None,
- include_dirs=None, extra_preargs=None, extra_postargs=None):
+ def preprocess(
+ self,
+ source,
+ output_file=None,
+ macros=None,
+ include_dirs=None,
+ extra_preargs=None,
+ extra_postargs=None,
+ ):
"""Preprocess a single C/C++ source file, named in 'source'.
Output will be written to file named 'output_file', or stdout if
'output_file' not supplied. 'macros' is a list of macro
@@ -508,9 +517,17 @@ class CCompiler:
"""
pass
- def compile(self, sources, output_dir=None, macros=None,
- include_dirs=None, debug=0, extra_preargs=None,
- extra_postargs=None, depends=None):
+ def compile(
+ self,
+ sources,
+ output_dir=None,
+ macros=None,
+ include_dirs=None,
+ debug=0,
+ extra_preargs=None,
+ extra_postargs=None,
+ depends=None,
+ ):
"""Compile one or more source files.
'sources' must be a list of filenames, most likely C/C++
@@ -561,9 +578,9 @@ class CCompiler:
"""
# A concrete compiler class can either override this method
# entirely or implement _compile().
- macros, objects, extra_postargs, pp_opts, build = \
- self._setup_compile(output_dir, macros, include_dirs, sources,
- depends, extra_postargs)
+ macros, objects, extra_postargs, pp_opts, build = self._setup_compile(
+ output_dir, macros, include_dirs, sources, depends, extra_postargs
+ )
cc_args = self._get_cc_args(pp_opts, debug, extra_preargs)
for obj in objects:
@@ -582,8 +599,9 @@ class CCompiler:
# should implement _compile().
pass
- def create_static_lib(self, objects, output_libname, output_dir=None,
- debug=0, target_lang=None):
+ def create_static_lib(
+ self, objects, output_libname, output_dir=None, debug=0, target_lang=None
+ ):
"""Link a bunch of stuff together to create a static library file.
The "bunch of stuff" consists of the list of object files supplied
as 'objects', the extra object files supplied to
@@ -608,26 +626,27 @@ class CCompiler:
"""
pass
-
# values for target_desc parameter in link()
SHARED_OBJECT = "shared_object"
SHARED_LIBRARY = "shared_library"
EXECUTABLE = "executable"
- def link(self,
- target_desc,
- objects,
- output_filename,
- output_dir=None,
- libraries=None,
- library_dirs=None,
- runtime_library_dirs=None,
- export_symbols=None,
- debug=0,
- extra_preargs=None,
- extra_postargs=None,
- build_temp=None,
- target_lang=None):
+ def link(
+ self,
+ target_desc,
+ objects,
+ output_filename,
+ output_dir=None,
+ libraries=None,
+ library_dirs=None,
+ runtime_library_dirs=None,
+ export_symbols=None,
+ debug=0,
+ extra_preargs=None,
+ extra_postargs=None,
+ build_temp=None,
+ target_lang=None,
+ ):
"""Link a bunch of stuff together to create an executable or
shared library file.
@@ -673,66 +692,98 @@ class CCompiler:
"""
raise NotImplementedError
-
# Old 'link_*()' methods, rewritten to use the new 'link()' method.
- def link_shared_lib(self,
- objects,
- output_libname,
- output_dir=None,
- libraries=None,
- library_dirs=None,
- runtime_library_dirs=None,
- export_symbols=None,
- debug=0,
- extra_preargs=None,
- extra_postargs=None,
- build_temp=None,
- target_lang=None):
- self.link(CCompiler.SHARED_LIBRARY, objects,
- self.library_filename(output_libname, lib_type='shared'),
- output_dir,
- libraries, library_dirs, runtime_library_dirs,
- export_symbols, debug,
- extra_preargs, extra_postargs, build_temp, target_lang)
-
-
- def link_shared_object(self,
- objects,
- output_filename,
- output_dir=None,
- libraries=None,
- library_dirs=None,
- runtime_library_dirs=None,
- export_symbols=None,
- debug=0,
- extra_preargs=None,
- extra_postargs=None,
- build_temp=None,
- target_lang=None):
- self.link(CCompiler.SHARED_OBJECT, objects,
- output_filename, output_dir,
- libraries, library_dirs, runtime_library_dirs,
- export_symbols, debug,
- extra_preargs, extra_postargs, build_temp, target_lang)
-
-
- def link_executable(self,
- objects,
- output_progname,
- output_dir=None,
- libraries=None,
- library_dirs=None,
- runtime_library_dirs=None,
- debug=0,
- extra_preargs=None,
- extra_postargs=None,
- target_lang=None):
- self.link(CCompiler.EXECUTABLE, objects,
- self.executable_filename(output_progname), output_dir,
- libraries, library_dirs, runtime_library_dirs, None,
- debug, extra_preargs, extra_postargs, None, target_lang)
-
+ def link_shared_lib(
+ self,
+ objects,
+ output_libname,
+ output_dir=None,
+ libraries=None,
+ library_dirs=None,
+ runtime_library_dirs=None,
+ export_symbols=None,
+ debug=0,
+ extra_preargs=None,
+ extra_postargs=None,
+ build_temp=None,
+ target_lang=None,
+ ):
+ self.link(
+ CCompiler.SHARED_LIBRARY,
+ objects,
+ self.library_filename(output_libname, lib_type='shared'),
+ output_dir,
+ libraries,
+ library_dirs,
+ runtime_library_dirs,
+ export_symbols,
+ debug,
+ extra_preargs,
+ extra_postargs,
+ build_temp,
+ target_lang,
+ )
+
+ def link_shared_object(
+ self,
+ objects,
+ output_filename,
+ output_dir=None,
+ libraries=None,
+ library_dirs=None,
+ runtime_library_dirs=None,
+ export_symbols=None,
+ debug=0,
+ extra_preargs=None,
+ extra_postargs=None,
+ build_temp=None,
+ target_lang=None,
+ ):
+ self.link(
+ CCompiler.SHARED_OBJECT,
+ objects,
+ output_filename,
+ output_dir,
+ libraries,
+ library_dirs,
+ runtime_library_dirs,
+ export_symbols,
+ debug,
+ extra_preargs,
+ extra_postargs,
+ build_temp,
+ target_lang,
+ )
+
+ def link_executable(
+ self,
+ objects,
+ output_progname,
+ output_dir=None,
+ libraries=None,
+ library_dirs=None,
+ runtime_library_dirs=None,
+ debug=0,
+ extra_preargs=None,
+ extra_postargs=None,
+ target_lang=None,
+ ):
+ self.link(
+ CCompiler.EXECUTABLE,
+ objects,
+ self.executable_filename(output_progname),
+ output_dir,
+ libraries,
+ library_dirs,
+ runtime_library_dirs,
+ None,
+ debug,
+ extra_preargs,
+ extra_postargs,
+ None,
+ target_lang,
+ )
# -- Miscellaneous methods -----------------------------------------
# These are all used by the 'gen_lib_options() function; there is
@@ -757,8 +808,14 @@ class CCompiler:
"""
raise NotImplementedError
- def has_function(self, funcname, includes=None, include_dirs=None,
- libraries=None, library_dirs=None):
+ def has_function(
+ self,
+ funcname,
+ includes=None,
+ include_dirs=None,
+ libraries=None,
+ library_dirs=None,
+ ):
"""Return a boolean indicating whether funcname is supported on
the current platform. The optional arguments can be used to
augment the compilation environment.
@@ -767,6 +824,7 @@ class CCompiler:
# import math which might not be available at that point - maybe
# the necessary logic should just be inlined?
import tempfile
+
if includes is None:
includes = []
if include_dirs is None:
@@ -780,12 +838,15 @@ class CCompiler:
try:
for incl in includes:
f.write("""#include "%s"\n""" % incl)
- f.write("""\
+ f.write(
+ """\
int main (int argc, char **argv) {
%s();
return 0;
}
-""" % funcname)
+"""
+ % funcname
+ )
finally:
f.close()
try:
@@ -796,9 +857,9 @@ int main (int argc, char **argv) {
os.remove(fname)
try:
- self.link_executable(objects, "a.out",
- libraries=libraries,
- library_dirs=library_dirs)
+ self.link_executable(
+ objects, "a.out", libraries=libraries, library_dirs=library_dirs
+ )
except (LinkError, TypeError):
return False
else:
@@ -808,7 +869,7 @@ int main (int argc, char **argv) {
os.remove(fn)
return True
- def find_library_file (self, dirs, lib, debug=0):
+ def find_library_file(self, dirs, lib, debug=0):
"""Search the specified list of directories for a static or shared
library file 'lib' and return the full path to that file. If
'debug' true, look for a debugging version (if that makes sense on
@@ -857,15 +918,15 @@ int main (int argc, char **argv) {
obj_names = []
for src_name in source_filenames:
base, ext = os.path.splitext(src_name)
- base = os.path.splitdrive(base)[1] # Chop off the drive
- base = base[os.path.isabs(base):] # If abs, chop off leading /
+ base = os.path.splitdrive(base)[1] # Chop off the drive
+ base = base[os.path.isabs(base) :] # If abs, chop off leading /
if ext not in self.src_extensions:
raise UnknownFileError(
- "unknown file type '%s' (from '%s')" % (ext, src_name))
+ "unknown file type '%s' (from '%s')" % (ext, src_name)
+ )
if strip_dir:
base = os.path.basename(base)
- obj_names.append(os.path.join(output_dir,
- base + self.obj_extension))
+ obj_names.append(os.path.join(output_dir, base + self.obj_extension))
return obj_names
def shared_object_filename(self, basename, strip_dir=0, output_dir=''):
@@ -880,12 +941,14 @@ int main (int argc, char **argv) {
basename = os.path.basename(basename)
return os.path.join(output_dir, basename + (self.exe_extension or ''))
- def library_filename(self, libname, lib_type='static', # or 'shared'
- strip_dir=0, output_dir=''):
+ def library_filename(
+ self, libname, lib_type='static', strip_dir=0, output_dir='' # or 'shared'
+ ):
assert output_dir is not None
if lib_type not in ("static", "shared", "dylib", "xcode_stub"):
raise ValueError(
- "'lib_type' must be \"static\", \"shared\", \"dylib\", or \"xcode_stub\"")
+ "'lib_type' must be \"static\", \"shared\", \"dylib\", or \"xcode_stub\""
+ )
fmt = getattr(self, lib_type + "_lib_format")
ext = getattr(self, lib_type + "_lib_extension")
@@ -896,7 +959,6 @@ int main (int argc, char **argv) {
return os.path.join(output_dir, dir, filename)
-
# -- Utility methods -----------------------------------------------
def announce(self, msg, level=1):
@@ -904,6 +966,7 @@ int main (int argc, char **argv) {
def debug_print(self, msg):
from distutils.debug import DEBUG
+
if DEBUG:
print(msg)
@@ -919,7 +982,7 @@ int main (int argc, char **argv) {
def move_file(self, src, dst):
return move_file(src, dst, dry_run=self.dry_run)
- def mkpath (self, name, mode=0o777):
+ def mkpath(self, name, mode=0o777):
mkpath(name, mode, dry_run=self.dry_run)
@@ -928,54 +991,59 @@ int main (int argc, char **argv) {
# patterns. Order is important; platform mappings are preferred over
# OS names.
_default_compilers = (
-
# Platform string mappings
-
# on a cygwin built python we can use gcc like an ordinary UNIXish
# compiler
('cygwin.*', 'unix'),
-
# OS name mappings
('posix', 'unix'),
('nt', 'msvc'),
+)
- )
def get_default_compiler(osname=None, platform=None):
"""Determine the default compiler to use for the given platform.
- osname should be one of the standard Python OS names (i.e. the
- ones returned by os.name) and platform the common value
- returned by sys.platform for the platform in question.
+ osname should be one of the standard Python OS names (i.e. the
+ ones returned by os.name) and platform the common value
+ returned by sys.platform for the platform in question.
- The default values are os.name and sys.platform in case the
- parameters are not given.
+ The default values are os.name and sys.platform in case the
+ parameters are not given.
"""
if osname is None:
osname = os.name
if platform is None:
platform = sys.platform
for pattern, compiler in _default_compilers:
- if re.match(pattern, platform) is not None or \
- re.match(pattern, osname) is not None:
+ if (
+ re.match(pattern, platform) is not None
+ or re.match(pattern, osname) is not None
+ ):
return compiler
# Default to Unix compiler
return 'unix'
+
# Map compiler types to (module_name, class_name) pairs -- ie. where to
# find the code that implements an interface to this compiler. (The module
# is assumed to be in the 'distutils' package.)
-compiler_class = { 'unix': ('unixccompiler', 'UnixCCompiler',
- "standard UNIX-style compiler"),
- 'msvc': ('_msvccompiler', 'MSVCCompiler',
- "Microsoft Visual C++"),
- 'cygwin': ('cygwinccompiler', 'CygwinCCompiler',
- "Cygwin port of GNU C Compiler for Win32"),
- 'mingw32': ('cygwinccompiler', 'Mingw32CCompiler',
- "Mingw32 port of GNU C Compiler for Win32"),
- 'bcpp': ('bcppcompiler', 'BCPPCompiler',
- "Borland C++ Compiler"),
- }
+compiler_class = {
+ 'unix': ('unixccompiler', 'UnixCCompiler', "standard UNIX-style compiler"),
+ 'msvc': ('_msvccompiler', 'MSVCCompiler', "Microsoft Visual C++"),
+ 'cygwin': (
+ 'cygwinccompiler',
+ 'CygwinCCompiler',
+ "Cygwin port of GNU C Compiler for Win32",
+ ),
+ 'mingw32': (
+ 'cygwinccompiler',
+ 'Mingw32CCompiler',
+ "Mingw32 port of GNU C Compiler for Win32",
+ ),
+ 'bcpp': ('bcppcompiler', 'BCPPCompiler', "Borland C++ Compiler"),
+}
+
def show_compilers():
"""Print list of available compilers (used by the "--help-compiler"
@@ -985,10 +1053,10 @@ def show_compilers():
# "--compiler", which just happens to be the case for the three
# commands that use it.
from distutils.fancy_getopt import FancyGetopt
+
compilers = []
for compiler in compiler_class.keys():
- compilers.append(("compiler="+compiler, None,
- compiler_class[compiler][2]))
+ compilers.append(("compiler=" + compiler, None, compiler_class[compiler][2]))
compilers.sort()
pretty_printer = FancyGetopt(compilers)
pretty_printer.print_help("List of available compilers:")
@@ -1021,17 +1089,18 @@ def new_compiler(plat=None, compiler=None, verbose=0, dry_run=0, force=0):
try:
module_name = "distutils." + module_name
- __import__ (module_name)
+ __import__(module_name)
module = sys.modules[module_name]
klass = vars(module)[class_name]
except ImportError:
raise DistutilsModuleError(
- "can't compile C/C++ code: unable to load module '%s'" % \
- module_name)
+ "can't compile C/C++ code: unable to load module '%s'" % module_name
+ )
except KeyError:
raise DistutilsModuleError(
- "can't compile C/C++ code: unable to find class '%s' "
- "in module '%s'" % (class_name, module_name))
+ "can't compile C/C++ code: unable to find class '%s' "
+ "in module '%s'" % (class_name, module_name)
+ )
# XXX The None is necessary to preserve backwards compatibility
# with classes that expect verbose to be the first positional
@@ -1064,14 +1133,14 @@ def gen_preprocess_options(macros, include_dirs):
for macro in macros:
if not (isinstance(macro, tuple) and 1 <= len(macro) <= 2):
raise TypeError(
- "bad macro definition '%s': "
- "each element of 'macros' list must be a 1- or 2-tuple"
- % macro)
+ "bad macro definition '%s': "
+ "each element of 'macros' list must be a 1- or 2-tuple" % macro
+ )
- if len(macro) == 1: # undefine this macro
+ if len(macro) == 1: # undefine this macro
pp_opts.append("-U%s" % macro[0])
elif len(macro) == 2:
- if macro[1] is None: # define with no explicit value
+ if macro[1] is None: # define with no explicit value
pp_opts.append("-D%s" % macro[0])
else:
# XXX *don't* need to be clever about quoting the
@@ -1084,7 +1153,7 @@ def gen_preprocess_options(macros, include_dirs):
return pp_opts
-def gen_lib_options (compiler, library_dirs, runtime_library_dirs, libraries):
+def gen_lib_options(compiler, library_dirs, runtime_library_dirs, libraries):
"""Generate linker options for searching library directories and
linking with specific libraries. 'libraries' and 'library_dirs' are,
respectively, lists of library names (not filenames!) and search
@@ -1116,8 +1185,9 @@ def gen_lib_options (compiler, library_dirs, runtime_library_dirs, libraries):
if lib_file:
lib_opts.append(lib_file)
else:
- compiler.warn("no library file corresponding to "
- "'%s' found (skipping)" % lib)
+ compiler.warn(
+ "no library file corresponding to " "'%s' found (skipping)" % lib
+ )
else:
- lib_opts.append(compiler.library_option (lib))
+ lib_opts.append(compiler.library_option(lib))
return lib_opts
diff --git a/setuptools/_distutils/cmd.py b/setuptools/_distutils/cmd.py
index dba3191e..4a9bcc2a 100644
--- a/setuptools/_distutils/cmd.py
+++ b/setuptools/_distutils/cmd.py
@@ -9,6 +9,7 @@ from distutils.errors import DistutilsOptionError
from distutils import util, dir_util, file_util, archive_util, dep_util
from distutils import log
+
class Command:
"""Abstract base class for defining command classes, the "worker bees"
of the Distutils. A useful analogy for command classes is to think of
@@ -41,7 +42,6 @@ class Command:
# defined. The canonical example is the "install" command.
sub_commands = []
-
# -- Creation/initialization methods -------------------------------
def __init__(self, dist):
@@ -130,8 +130,9 @@ class Command:
This method must be implemented by all command classes.
"""
- raise RuntimeError("abstract method -- subclass %s must override"
- % self.__class__)
+ raise RuntimeError(
+ "abstract method -- subclass %s must override" % self.__class__
+ )
def finalize_options(self):
"""Set final values for all the options that this command supports.
@@ -144,12 +145,13 @@ class Command:
This method must be implemented by all command classes.
"""
- raise RuntimeError("abstract method -- subclass %s must override"
- % self.__class__)
-
+ raise RuntimeError(
+ "abstract method -- subclass %s must override" % self.__class__
+ )
def dump_options(self, header=None, indent=""):
from distutils.fancy_getopt import longopt_xlate
+
if header is None:
header = "command options for '%s':" % self.get_command_name()
self.announce(indent + header, level=log.INFO)
@@ -159,8 +161,7 @@ class Command:
if option[-1] == "=":
option = option[:-1]
value = getattr(self, option)
- self.announce(indent + "%s = %s" % (option, value),
- level=log.INFO)
+ self.announce(indent + "%s = %s" % (option, value), level=log.INFO)
def run(self):
"""A command's raison d'etre: carry out the action it exists to
@@ -172,8 +173,9 @@ class Command:
This method must be implemented by all command classes.
"""
- raise RuntimeError("abstract method -- subclass %s must override"
- % self.__class__)
+ raise RuntimeError(
+ "abstract method -- subclass %s must override" % self.__class__
+ )
def announce(self, msg, level=1):
"""If the current verbosity level is of greater than or equal to
@@ -186,11 +188,11 @@ class Command:
DISTUTILS_DEBUG environment variable) flag is true.
"""
from distutils.debug import DEBUG
+
if DEBUG:
print(msg)
sys.stdout.flush()
-
# -- Option validation methods -------------------------------------
# (these are very handy in writing the 'finalize_options()' method)
#
@@ -210,8 +212,9 @@ class Command:
setattr(self, option, default)
return default
elif not isinstance(val, str):
- raise DistutilsOptionError("'%s' must be a %s (got `%s`)"
- % (option, what, val))
+ raise DistutilsOptionError(
+ "'%s' must be a %s (got `%s`)" % (option, what, val)
+ )
return val
def ensure_string(self, option, default=None):
@@ -238,27 +241,29 @@ class Command:
ok = False
if not ok:
raise DistutilsOptionError(
- "'%s' must be a list of strings (got %r)"
- % (option, val))
+ "'%s' must be a list of strings (got %r)" % (option, val)
+ )
- def _ensure_tested_string(self, option, tester, what, error_fmt,
- default=None):
+ def _ensure_tested_string(self, option, tester, what, error_fmt, default=None):
val = self._ensure_stringlike(option, what, default)
if val is not None and not tester(val):
- raise DistutilsOptionError(("error in '%s' option: " + error_fmt)
- % (option, val))
+ raise DistutilsOptionError(
+ ("error in '%s' option: " + error_fmt) % (option, val)
+ )
def ensure_filename(self, option):
"""Ensure that 'option' is the name of an existing file."""
- self._ensure_tested_string(option, os.path.isfile,
- "filename",
- "'%s' does not exist or is not a file")
+ self._ensure_tested_string(
+ option, os.path.isfile, "filename", "'%s' does not exist or is not a file"
+ )
def ensure_dirname(self, option):
- self._ensure_tested_string(option, os.path.isdir,
- "directory name",
- "'%s' does not exist or is not a directory")
-
+ self._ensure_tested_string(
+ option,
+ os.path.isdir,
+ "directory name",
+ "'%s' does not exist or is not a directory",
+ )
# -- Convenience methods for commands ------------------------------
@@ -302,8 +307,7 @@ class Command:
# XXX rename to 'get_reinitialized_command()'? (should do the
# same in dist.py, if so)
def reinitialize_command(self, command, reinit_subcommands=0):
- return self.distribution.reinitialize_command(command,
- reinit_subcommands)
+ return self.distribution.reinitialize_command(command, reinit_subcommands)
def run_command(self, command):
"""Run some other command: uses the 'run_command()' method of
@@ -325,7 +329,6 @@ class Command:
commands.append(cmd_name)
return commands
-
# -- External world manipulation -----------------------------------
def warn(self, msg):
@@ -337,41 +340,70 @@ class Command:
def mkpath(self, name, mode=0o777):
dir_util.mkpath(name, mode, dry_run=self.dry_run)
- def copy_file(self, infile, outfile, preserve_mode=1, preserve_times=1,
- link=None, level=1):
+ def copy_file(
+ self, infile, outfile, preserve_mode=1, preserve_times=1, link=None, level=1
+ ):
"""Copy a file respecting verbose, dry-run and force flags. (The
former two default to whatever is in the Distribution object, and
the latter defaults to false for commands that don't define it.)"""
- return file_util.copy_file(infile, outfile, preserve_mode,
- preserve_times, not self.force, link,
- dry_run=self.dry_run)
-
- def copy_tree(self, infile, outfile, preserve_mode=1, preserve_times=1,
- preserve_symlinks=0, level=1):
+ return file_util.copy_file(
+ infile,
+ outfile,
+ preserve_mode,
+ preserve_times,
+ not self.force,
+ link,
+ dry_run=self.dry_run,
+ )
+
+ def copy_tree(
+ self,
+ infile,
+ outfile,
+ preserve_mode=1,
+ preserve_times=1,
+ preserve_symlinks=0,
+ level=1,
+ ):
"""Copy an entire directory tree respecting verbose, dry-run,
and force flags.
"""
- return dir_util.copy_tree(infile, outfile, preserve_mode,
- preserve_times, preserve_symlinks,
- not self.force, dry_run=self.dry_run)
-
- def move_file (self, src, dst, level=1):
+ return dir_util.copy_tree(
+ infile,
+ outfile,
+ preserve_mode,
+ preserve_times,
+ preserve_symlinks,
+ not self.force,
+ dry_run=self.dry_run,
+ )
+
+ def move_file(self, src, dst, level=1):
"""Move a file respecting dry-run flag."""
return file_util.move_file(src, dst, dry_run=self.dry_run)
def spawn(self, cmd, search_path=1, level=1):
"""Spawn an external command respecting dry-run flag."""
from distutils.spawn import spawn
- spawn(cmd, search_path, dry_run=self.dry_run)
- def make_archive(self, base_name, format, root_dir=None, base_dir=None,
- owner=None, group=None):
- return archive_util.make_archive(base_name, format, root_dir, base_dir,
- dry_run=self.dry_run,
- owner=owner, group=group)
+ spawn(cmd, search_path, dry_run=self.dry_run)
- def make_file(self, infiles, outfile, func, args,
- exec_msg=None, skip_msg=None, level=1):
+ def make_archive(
+ self, base_name, format, root_dir=None, base_dir=None, owner=None, group=None
+ ):
+ return archive_util.make_archive(
+ base_name,
+ format,
+ root_dir,
+ base_dir,
+ dry_run=self.dry_run,
+ owner=owner,
+ group=group,
+ )
+
+ def make_file(
+ self, infiles, outfile, func, args, exec_msg=None, skip_msg=None, level=1
+ ):
"""Special case of 'execute()' for operations that process one or
more input files and generate one output file. Works just like
'execute()', except the operation is skipped and a different
@@ -387,8 +419,7 @@ class Command:
if isinstance(infiles, str):
infiles = (infiles,)
elif not isinstance(infiles, (list, tuple)):
- raise TypeError(
- "'infiles' must be a string, or a list or tuple of strings")
+ raise TypeError("'infiles' must be a string, or a list or tuple of strings")
if exec_msg is None:
exec_msg = "generating %s from %s" % (outfile, ', '.join(infiles))
diff --git a/setuptools/_distutils/command/__init__.py b/setuptools/_distutils/command/__init__.py
index 481eea9f..d199c242 100644
--- a/setuptools/_distutils/command/__init__.py
+++ b/setuptools/_distutils/command/__init__.py
@@ -3,29 +3,30 @@
Package containing implementation of all the standard Distutils
commands."""
-__all__ = ['build',
- 'build_py',
- 'build_ext',
- 'build_clib',
- 'build_scripts',
- 'clean',
- 'install',
- 'install_lib',
- 'install_headers',
- 'install_scripts',
- 'install_data',
- 'sdist',
- 'register',
- 'bdist',
- 'bdist_dumb',
- 'bdist_rpm',
- 'bdist_wininst',
- 'check',
- 'upload',
- # These two are reserved for future use:
- #'bdist_sdux',
- #'bdist_pkgtool',
- # Note:
- # bdist_packager is not included because it only provides
- # an abstract base class
- ]
+__all__ = [
+ 'build',
+ 'build_py',
+ 'build_ext',
+ 'build_clib',
+ 'build_scripts',
+ 'clean',
+ 'install',
+ 'install_lib',
+ 'install_headers',
+ 'install_scripts',
+ 'install_data',
+ 'sdist',
+ 'register',
+ 'bdist',
+ 'bdist_dumb',
+ 'bdist_rpm',
+ 'bdist_wininst',
+ 'check',
+ 'upload',
+ # These two are reserved for future use:
+ #'bdist_sdux',
+ #'bdist_pkgtool',
+ # Note:
+ # bdist_packager is not included because it only provides
+ # an abstract base class
+]
diff --git a/setuptools/_distutils/command/bdist.py b/setuptools/_distutils/command/bdist.py
index 014871d2..2a639761 100644
--- a/setuptools/_distutils/command/bdist.py
+++ b/setuptools/_distutils/command/bdist.py
@@ -10,13 +10,12 @@ from distutils.util import get_platform
def show_formats():
- """Print list of available formats (arguments to "--format" option).
- """
+ """Print list of available formats (arguments to "--format" option)."""
from distutils.fancy_getopt import FancyGetopt
+
formats = []
for format in bdist.format_commands:
- formats.append(("formats=" + format, None,
- bdist.format_command[format][1]))
+ formats.append(("formats=" + format, None, bdist.format_command[format][1]))
pretty_printer = FancyGetopt(formats)
pretty_printer.print_help("List of available distribution formats:")
@@ -25,58 +24,71 @@ class bdist(Command):
description = "create a built (binary) distribution"
- user_options = [('bdist-base=', 'b',
- "temporary directory for creating built distributions"),
- ('plat-name=', 'p',
- "platform name to embed in generated filenames "
- "(default: %s)" % get_platform()),
- ('formats=', None,
- "formats for distribution (comma-separated list)"),
- ('dist-dir=', 'd',
- "directory to put final built distributions in "
- "[default: dist]"),
- ('skip-build', None,
- "skip rebuilding everything (for testing/debugging)"),
- ('owner=', 'u',
- "Owner name used when creating a tar file"
- " [default: current user]"),
- ('group=', 'g',
- "Group name used when creating a tar file"
- " [default: current group]"),
- ]
+ user_options = [
+ ('bdist-base=', 'b', "temporary directory for creating built distributions"),
+ (
+ 'plat-name=',
+ 'p',
+ "platform name to embed in generated filenames "
+ "(default: %s)" % get_platform(),
+ ),
+ ('formats=', None, "formats for distribution (comma-separated list)"),
+ (
+ 'dist-dir=',
+ 'd',
+ "directory to put final built distributions in " "[default: dist]",
+ ),
+ ('skip-build', None, "skip rebuilding everything (for testing/debugging)"),
+ (
+ 'owner=',
+ 'u',
+ "Owner name used when creating a tar file" " [default: current user]",
+ ),
+ (
+ 'group=',
+ 'g',
+ "Group name used when creating a tar file" " [default: current group]",
+ ),
+ ]
boolean_options = ['skip-build']
help_options = [
- ('help-formats', None,
- "lists available distribution formats", show_formats),
- ]
+ ('help-formats', None, "lists available distribution formats", show_formats),
+ ]
# The following commands do not take a format option from bdist
no_format_option = ('bdist_rpm',)
# This won't do in reality: will need to distinguish RPM-ish Linux,
# Debian-ish Linux, Solaris, FreeBSD, ..., Windows, Mac OS.
- default_format = {'posix': 'gztar',
- 'nt': 'zip'}
+ default_format = {'posix': 'gztar', 'nt': 'zip'}
# Establish the preferred order (for the --help-formats option).
- format_commands = ['rpm', 'gztar', 'bztar', 'xztar', 'ztar', 'tar',
- 'wininst', 'zip', 'msi']
+ format_commands = [
+ 'rpm',
+ 'gztar',
+ 'bztar',
+ 'xztar',
+ 'ztar',
+ 'tar',
+ 'wininst',
+ 'zip',
+ 'msi',
+ ]
# And the real information.
- format_command = {'rpm': ('bdist_rpm', "RPM distribution"),
- 'gztar': ('bdist_dumb', "gzip'ed tar file"),
- 'bztar': ('bdist_dumb', "bzip2'ed tar file"),
- 'xztar': ('bdist_dumb', "xz'ed tar file"),
- 'ztar': ('bdist_dumb', "compressed tar file"),
- 'tar': ('bdist_dumb', "tar file"),
- 'wininst': ('bdist_wininst',
- "Windows executable installer"),
- 'zip': ('bdist_dumb', "ZIP file"),
- 'msi': ('bdist_msi', "Microsoft Installer")
- }
-
+ format_command = {
+ 'rpm': ('bdist_rpm', "RPM distribution"),
+ 'gztar': ('bdist_dumb', "gzip'ed tar file"),
+ 'bztar': ('bdist_dumb', "bzip2'ed tar file"),
+ 'xztar': ('bdist_dumb', "xz'ed tar file"),
+ 'ztar': ('bdist_dumb', "compressed tar file"),
+ 'tar': ('bdist_dumb', "tar file"),
+ 'wininst': ('bdist_wininst', "Windows executable installer"),
+ 'zip': ('bdist_dumb', "ZIP file"),
+ 'msi': ('bdist_msi', "Microsoft Installer"),
+ }
def initialize_options(self):
self.bdist_base = None
@@ -100,8 +112,7 @@ class bdist(Command):
# "build/bdist.<plat>/dumb", "build/bdist.<plat>/rpm", etc.)
if self.bdist_base is None:
build_base = self.get_finalized_command('build').build_base
- self.bdist_base = os.path.join(build_base,
- 'bdist.' + self.plat_name)
+ self.bdist_base = os.path.join(build_base, 'bdist.' + self.plat_name)
self.ensure_string_list('formats')
if self.formats is None:
@@ -109,8 +120,9 @@ class bdist(Command):
self.formats = [self.default_format[os.name]]
except KeyError:
raise DistutilsPlatformError(
- "don't know how to create built distributions "
- "on platform %s" % os.name)
+ "don't know how to create built distributions "
+ "on platform %s" % os.name
+ )
if self.dist_dir is None:
self.dist_dir = "dist"
@@ -138,6 +150,6 @@ class bdist(Command):
# If we're going to need to run this command again, tell it to
# keep its temporary files around so subsequent runs go faster.
- if cmd_name in commands[i+1:]:
+ if cmd_name in commands[i + 1 :]:
sub_cmd.keep_temp = 1
self.run_command(cmd_name)
diff --git a/setuptools/_distutils/command/bdist_dumb.py b/setuptools/_distutils/command/bdist_dumb.py
index f0d6b5b8..3c387828 100644
--- a/setuptools/_distutils/command/bdist_dumb.py
+++ b/setuptools/_distutils/command/bdist_dumb.py
@@ -12,40 +12,52 @@ from distutils.errors import *
from distutils.sysconfig import get_python_version
from distutils import log
+
class bdist_dumb(Command):
description = "create a \"dumb\" built distribution"
- user_options = [('bdist-dir=', 'd',
- "temporary directory for creating the distribution"),
- ('plat-name=', 'p',
- "platform name to embed in generated filenames "
- "(default: %s)" % get_platform()),
- ('format=', 'f',
- "archive format to create (tar, gztar, bztar, xztar, "
- "ztar, zip)"),
- ('keep-temp', 'k',
- "keep the pseudo-installation tree around after " +
- "creating the distribution archive"),
- ('dist-dir=', 'd',
- "directory to put final built distributions in"),
- ('skip-build', None,
- "skip rebuilding everything (for testing/debugging)"),
- ('relative', None,
- "build the archive using relative paths "
- "(default: false)"),
- ('owner=', 'u',
- "Owner name used when creating a tar file"
- " [default: current user]"),
- ('group=', 'g',
- "Group name used when creating a tar file"
- " [default: current group]"),
- ]
+ user_options = [
+ ('bdist-dir=', 'd', "temporary directory for creating the distribution"),
+ (
+ 'plat-name=',
+ 'p',
+ "platform name to embed in generated filenames "
+ "(default: %s)" % get_platform(),
+ ),
+ (
+ 'format=',
+ 'f',
+ "archive format to create (tar, gztar, bztar, xztar, " "ztar, zip)",
+ ),
+ (
+ 'keep-temp',
+ 'k',
+ "keep the pseudo-installation tree around after "
+ + "creating the distribution archive",
+ ),
+ ('dist-dir=', 'd', "directory to put final built distributions in"),
+ ('skip-build', None, "skip rebuilding everything (for testing/debugging)"),
+ (
+ 'relative',
+ None,
+ "build the archive using relative paths " "(default: false)",
+ ),
+ (
+ 'owner=',
+ 'u',
+ "Owner name used when creating a tar file" " [default: current user]",
+ ),
+ (
+ 'group=',
+ 'g',
+ "Group name used when creating a tar file" " [default: current group]",
+ ),
+ ]
boolean_options = ['keep-temp', 'skip-build', 'relative']
- default_format = { 'posix': 'gztar',
- 'nt': 'zip' }
+ default_format = {'posix': 'gztar', 'nt': 'zip'}
def initialize_options(self):
self.bdist_dir = None
@@ -68,13 +80,16 @@ class bdist_dumb(Command):
self.format = self.default_format[os.name]
except KeyError:
raise DistutilsPlatformError(
- "don't know how to create dumb built distributions "
- "on platform %s" % os.name)
+ "don't know how to create dumb built distributions "
+ "on platform %s" % os.name
+ )
- self.set_undefined_options('bdist',
- ('dist_dir', 'dist_dir'),
- ('plat_name', 'plat_name'),
- ('skip_build', 'skip_build'))
+ self.set_undefined_options(
+ 'bdist',
+ ('dist_dir', 'dist_dir'),
+ ('plat_name', 'plat_name'),
+ ('skip_build', 'skip_build'),
+ )
def run(self):
if not self.skip_build:
@@ -90,34 +105,38 @@ class bdist_dumb(Command):
# And make an archive relative to the root of the
# pseudo-installation tree.
- archive_basename = "%s.%s" % (self.distribution.get_fullname(),
- self.plat_name)
+ archive_basename = "%s.%s" % (self.distribution.get_fullname(), self.plat_name)
pseudoinstall_root = os.path.join(self.dist_dir, archive_basename)
if not self.relative:
archive_root = self.bdist_dir
else:
- if (self.distribution.has_ext_modules() and
- (install.install_base != install.install_platbase)):
+ if self.distribution.has_ext_modules() and (
+ install.install_base != install.install_platbase
+ ):
raise DistutilsPlatformError(
- "can't make a dumb built distribution where "
- "base and platbase are different (%s, %s)"
- % (repr(install.install_base),
- repr(install.install_platbase)))
+ "can't make a dumb built distribution where "
+ "base and platbase are different (%s, %s)"
+ % (repr(install.install_base), repr(install.install_platbase))
+ )
else:
- archive_root = os.path.join(self.bdist_dir,
- ensure_relative(install.install_base))
+ archive_root = os.path.join(
+ self.bdist_dir, ensure_relative(install.install_base)
+ )
# Make the archive
- filename = self.make_archive(pseudoinstall_root,
- self.format, root_dir=archive_root,
- owner=self.owner, group=self.group)
+ filename = self.make_archive(
+ pseudoinstall_root,
+ self.format,
+ root_dir=archive_root,
+ owner=self.owner,
+ group=self.group,
+ )
if self.distribution.has_ext_modules():
pyversion = get_python_version()
else:
pyversion = 'any'
- self.distribution.dist_files.append(('bdist_dumb', pyversion,
- filename))
+ self.distribution.dist_files.append(('bdist_dumb', pyversion, filename))
if not self.keep_temp:
remove_tree(self.bdist_dir, dry_run=self.dry_run)
diff --git a/setuptools/_distutils/command/bdist_msi.py b/setuptools/_distutils/command/bdist_msi.py
index 15259532..2f292c96 100644
--- a/setuptools/_distutils/command/bdist_msi.py
+++ b/setuptools/_distutils/command/bdist_msi.py
@@ -20,17 +20,19 @@ import msilib
from msilib import schema, sequence, text
from msilib import Directory, Feature, Dialog, add_data
+
class PyDialog(Dialog):
"""Dialog class with a fixed layout: controls at the top, then a ruler,
then a list of buttons: back, next, cancel. Optionally a bitmap at the
left."""
+
def __init__(self, *args, **kw):
"""Dialog(database, name, x, y, w, h, attributes, title, first,
default, cancel, bitmap=true)"""
super().__init__(*args)
ruler = self.h - 36
- bmwidth = 152*ruler/328
- #if kw.get("bitmap", True):
+ bmwidth = 152 * ruler / 328
+ # if kw.get("bitmap", True):
# self.bitmap("Bitmap", 0, 0, bmwidth, ruler, "PythonWin")
self.line("BottomLine", 0, ruler, self.w, 0)
@@ -38,41 +40,40 @@ class PyDialog(Dialog):
"Set the title text of the dialog at the top."
# name, x, y, w, h, flags=Visible|Enabled|Transparent|NoPrefix,
# text, in VerdanaBold10
- self.text("Title", 15, 10, 320, 60, 0x30003,
- r"{\VerdanaBold10}%s" % title)
+ self.text("Title", 15, 10, 320, 60, 0x30003, r"{\VerdanaBold10}%s" % title)
- def back(self, title, next, name = "Back", active = 1):
+ def back(self, title, next, name="Back", active=1):
"""Add a back button with a given title, the tab-next button,
its name in the Control table, possibly initially disabled.
Return the button, so that events can be associated"""
if active:
- flags = 3 # Visible|Enabled
+ flags = 3 # Visible|Enabled
else:
- flags = 1 # Visible
- return self.pushbutton(name, 180, self.h-27 , 56, 17, flags, title, next)
+ flags = 1 # Visible
+ return self.pushbutton(name, 180, self.h - 27, 56, 17, flags, title, next)
- def cancel(self, title, next, name = "Cancel", active = 1):
+ def cancel(self, title, next, name="Cancel", active=1):
"""Add a cancel button with a given title, the tab-next button,
its name in the Control table, possibly initially disabled.
Return the button, so that events can be associated"""
if active:
- flags = 3 # Visible|Enabled
+ flags = 3 # Visible|Enabled
else:
- flags = 1 # Visible
- return self.pushbutton(name, 304, self.h-27, 56, 17, flags, title, next)
+ flags = 1 # Visible
+ return self.pushbutton(name, 304, self.h - 27, 56, 17, flags, title, next)
- def next(self, title, next, name = "Next", active = 1):
+ def next(self, title, next, name="Next", active=1):
"""Add a Next button with a given title, the tab-next button,
its name in the Control table, possibly initially disabled.
Return the button, so that events can be associated"""
if active:
- flags = 3 # Visible|Enabled
+ flags = 3 # Visible|Enabled
else:
- flags = 1 # Visible
- return self.pushbutton(name, 236, self.h-27, 56, 17, flags, title, next)
+ flags = 1 # Visible
+ return self.pushbutton(name, 236, self.h - 27, 56, 17, flags, title, next)
def xbutton(self, name, title, next, xpos):
"""Add a button with a given title, the tab-next button,
@@ -80,55 +81,96 @@ class PyDialog(Dialog):
y-position is aligned with the other buttons.
Return the button, so that events can be associated"""
- return self.pushbutton(name, int(self.w*xpos - 28), self.h-27, 56, 17, 3, title, next)
+ return self.pushbutton(
+ name, int(self.w * xpos - 28), self.h - 27, 56, 17, 3, title, next
+ )
+
class bdist_msi(Command):
description = "create a Microsoft Installer (.msi) binary distribution"
- user_options = [('bdist-dir=', None,
- "temporary directory for creating the distribution"),
- ('plat-name=', 'p',
- "platform name to embed in generated filenames "
- "(default: %s)" % get_platform()),
- ('keep-temp', 'k',
- "keep the pseudo-installation tree around after " +
- "creating the distribution archive"),
- ('target-version=', None,
- "require a specific python version" +
- " on the target system"),
- ('no-target-compile', 'c',
- "do not compile .py to .pyc on the target system"),
- ('no-target-optimize', 'o',
- "do not compile .py to .pyo (optimized) "
- "on the target system"),
- ('dist-dir=', 'd',
- "directory to put final built distributions in"),
- ('skip-build', None,
- "skip rebuilding everything (for testing/debugging)"),
- ('install-script=', None,
- "basename of installation script to be run after "
- "installation or before deinstallation"),
- ('pre-install-script=', None,
- "Fully qualified filename of a script to be run before "
- "any files are installed. This script need not be in the "
- "distribution"),
- ]
-
- boolean_options = ['keep-temp', 'no-target-compile', 'no-target-optimize',
- 'skip-build']
-
- all_versions = ['2.0', '2.1', '2.2', '2.3', '2.4',
- '2.5', '2.6', '2.7', '2.8', '2.9',
- '3.0', '3.1', '3.2', '3.3', '3.4',
- '3.5', '3.6', '3.7', '3.8', '3.9']
+ user_options = [
+ ('bdist-dir=', None, "temporary directory for creating the distribution"),
+ (
+ 'plat-name=',
+ 'p',
+ "platform name to embed in generated filenames "
+ "(default: %s)" % get_platform(),
+ ),
+ (
+ 'keep-temp',
+ 'k',
+ "keep the pseudo-installation tree around after "
+ + "creating the distribution archive",
+ ),
+ (
+ 'target-version=',
+ None,
+ "require a specific python version" + " on the target system",
+ ),
+ ('no-target-compile', 'c', "do not compile .py to .pyc on the target system"),
+ (
+ 'no-target-optimize',
+ 'o',
+ "do not compile .py to .pyo (optimized) " "on the target system",
+ ),
+ ('dist-dir=', 'd', "directory to put final built distributions in"),
+ ('skip-build', None, "skip rebuilding everything (for testing/debugging)"),
+ (
+ 'install-script=',
+ None,
+ "basename of installation script to be run after "
+ "installation or before deinstallation",
+ ),
+ (
+ 'pre-install-script=',
+ None,
+ "Fully qualified filename of a script to be run before "
+ "any files are installed. This script need not be in the "
+ "distribution",
+ ),
+ ]
+
+ boolean_options = [
+ 'keep-temp',
+ 'no-target-compile',
+ 'no-target-optimize',
+ 'skip-build',
+ ]
+
+ all_versions = [
+ '2.0',
+ '2.1',
+ '2.2',
+ '2.3',
+ '2.4',
+ '2.5',
+ '2.6',
+ '2.7',
+ '2.8',
+ '2.9',
+ '3.0',
+ '3.1',
+ '3.2',
+ '3.3',
+ '3.4',
+ '3.5',
+ '3.6',
+ '3.7',
+ '3.8',
+ '3.9',
+ ]
other_version = 'X'
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
- warnings.warn("bdist_msi command is deprecated since Python 3.9, "
- "use bdist_wheel (wheel packages) instead",
- DeprecationWarning, 2)
+ warnings.warn(
+ "bdist_msi command is deprecated since Python 3.9, "
+ "use bdist_wheel (wheel packages) instead",
+ DeprecationWarning,
+ 2,
+ )
def initialize_options(self):
self.bdist_dir = None
@@ -156,22 +198,28 @@ class bdist_msi(Command):
if self.target_version:
self.versions = [self.target_version]
- if not self.skip_build and self.distribution.has_ext_modules()\
- and self.target_version != short_version:
+ if (
+ not self.skip_build
+ and self.distribution.has_ext_modules()
+ and self.target_version != short_version
+ ):
raise DistutilsOptionError(
- "target version can only be %s, or the '--skip-build'"
- " option must be specified" % (short_version,))
+ "target version can only be %s, or the '--skip-build'"
+ " option must be specified" % (short_version,)
+ )
else:
self.versions = list(self.all_versions)
- self.set_undefined_options('bdist',
- ('dist_dir', 'dist_dir'),
- ('plat_name', 'plat_name'),
- )
+ self.set_undefined_options(
+ 'bdist',
+ ('dist_dir', 'dist_dir'),
+ ('plat_name', 'plat_name'),
+ )
if self.pre_install_script:
raise DistutilsOptionError(
- "the pre-install-script feature is not yet implemented")
+ "the pre-install-script feature is not yet implemented"
+ )
if self.install_script:
for script in self.distribution.scripts:
@@ -179,8 +227,8 @@ class bdist_msi(Command):
break
else:
raise DistutilsOptionError(
- "install_script '%s' not found in scripts"
- % self.install_script)
+ "install_script '%s' not found in scripts" % self.install_script
+ )
self.install_script_key = None
def run(self):
@@ -210,8 +258,7 @@ class bdist_msi(Command):
target_version = '%d.%d' % sys.version_info[:2]
plat_specifier = ".%s-%s" % (self.plat_name, target_version)
build = self.get_finalized_command('build')
- build.build_lib = os.path.join(build.build_base,
- 'lib' + plat_specifier)
+ build.build_lib = os.path.join(build.build_base, 'lib' + plat_specifier)
log.info("installing to %s", self.bdist_dir)
install.ensure_finalized()
@@ -228,14 +275,11 @@ class bdist_msi(Command):
fullname = self.distribution.get_fullname()
installer_name = self.get_installer_filename(fullname)
installer_name = os.path.abspath(installer_name)
- if os.path.exists(installer_name): os.unlink(installer_name)
+ if os.path.exists(installer_name):
+ os.unlink(installer_name)
metadata = self.distribution.metadata
- author = metadata.author
- if not author:
- author = metadata.maintainer
- if not author:
- author = "UNKNOWN"
+ author = metadata.author or metadata.maintainer
version = metadata.get_version()
# ProductVersion must be strictly numeric
# XXX need to deal with prerelease versions
@@ -248,9 +292,9 @@ class bdist_msi(Command):
product_name = "Python %s %s" % (self.target_version, fullname)
else:
product_name = "Python %s" % (fullname)
- self.db = msilib.init_database(installer_name, schema,
- product_name, msilib.gen_uuid(),
- sversion, author)
+ self.db = msilib.init_database(
+ installer_name, schema, product_name, msilib.gen_uuid(), sversion, author
+ )
msilib.add_tables(self.db, sequence)
props = [('DistVersion', version)]
email = metadata.author_email or metadata.maintainer_email
@@ -280,8 +324,7 @@ class bdist_msi(Command):
rootdir = os.path.abspath(self.bdist_dir)
root = Directory(db, cab, None, rootdir, "TARGETDIR", "SourceDir")
- f = Feature(db, "Python", "Python", "Everything",
- 0, 1, directory="TARGETDIR")
+ f = Feature(db, "Python", "Python", "Everything", 0, 1, directory="TARGETDIR")
items = [(f, root, '')]
for version in self.versions + [self.other_version]:
@@ -316,15 +359,27 @@ class bdist_msi(Command):
dir.start_component(dir.logical, feature, 0)
if afile not in seen:
key = seen[afile] = dir.add_file(file)
- if file==self.install_script:
+ if file == self.install_script:
if self.install_script_key:
raise DistutilsOptionError(
- "Multiple files with name %s" % file)
+ "Multiple files with name %s" % file
+ )
self.install_script_key = '[#%s]' % key
else:
key = seen[afile]
- add_data(self.db, "DuplicateFile",
- [(key + version, dir.component, key, None, dir.logical)])
+ add_data(
+ self.db,
+ "DuplicateFile",
+ [
+ (
+ key + version,
+ dir.component,
+ key,
+ None,
+ dir.logical,
+ )
+ ],
+ )
db.Commit()
cab.commit(db)
@@ -353,32 +408,60 @@ class bdist_msi(Command):
exe_prop = "PYTHON" + ver
if msilib.Win64:
# type: msidbLocatorTypeRawValue + msidbLocatorType64bit
- Type = 2+16
+ Type = 2 + 16
else:
Type = 2
- add_data(self.db, "RegLocator",
- [(machine_reg, 2, install_path, None, Type),
- (user_reg, 1, install_path, None, Type)])
- add_data(self.db, "AppSearch",
- [(machine_prop, machine_reg),
- (user_prop, user_reg)])
- add_data(self.db, "CustomAction",
- [(machine_action, 51+256, target_dir_prop, "[" + machine_prop + "]"),
- (user_action, 51+256, target_dir_prop, "[" + user_prop + "]"),
- (exe_action, 51+256, exe_prop, "[" + target_dir_prop + "]\\python.exe"),
- ])
- add_data(self.db, "InstallExecuteSequence",
- [(machine_action, machine_prop, start),
- (user_action, user_prop, start + 1),
- (exe_action, None, start + 2),
- ])
- add_data(self.db, "InstallUISequence",
- [(machine_action, machine_prop, start),
- (user_action, user_prop, start + 1),
- (exe_action, None, start + 2),
- ])
- add_data(self.db, "Condition",
- [("Python" + ver, 0, "NOT TARGETDIR" + ver)])
+ add_data(
+ self.db,
+ "RegLocator",
+ [
+ (machine_reg, 2, install_path, None, Type),
+ (user_reg, 1, install_path, None, Type),
+ ],
+ )
+ add_data(
+ self.db,
+ "AppSearch",
+ [(machine_prop, machine_reg), (user_prop, user_reg)],
+ )
+ add_data(
+ self.db,
+ "CustomAction",
+ [
+ (
+ machine_action,
+ 51 + 256,
+ target_dir_prop,
+ "[" + machine_prop + "]",
+ ),
+ (user_action, 51 + 256, target_dir_prop, "[" + user_prop + "]"),
+ (
+ exe_action,
+ 51 + 256,
+ exe_prop,
+ "[" + target_dir_prop + "]\\python.exe",
+ ),
+ ],
+ )
+ add_data(
+ self.db,
+ "InstallExecuteSequence",
+ [
+ (machine_action, machine_prop, start),
+ (user_action, user_prop, start + 1),
+ (exe_action, None, start + 2),
+ ],
+ )
+ add_data(
+ self.db,
+ "InstallUISequence",
+ [
+ (machine_action, machine_prop, start),
+ (user_action, user_prop, start + 1),
+ (exe_action, None, start + 2),
+ ],
+ )
+ add_data(self.db, "Condition", [("Python" + ver, 0, "NOT TARGETDIR" + ver)])
start += 4
assert start < 500
@@ -388,10 +471,16 @@ class bdist_msi(Command):
for ver in self.versions + [self.other_version]:
install_action = "install_script." + ver
exe_prop = "PYTHON" + ver
- add_data(self.db, "CustomAction",
- [(install_action, 50, exe_prop, self.install_script_key)])
- add_data(self.db, "InstallExecuteSequence",
- [(install_action, "&Python%s=3" % ver, start)])
+ add_data(
+ self.db,
+ "CustomAction",
+ [(install_action, 50, exe_prop, self.install_script_key)],
+ )
+ add_data(
+ self.db,
+ "InstallExecuteSequence",
+ [(install_action, "&Python%s=3" % ver, start)],
+ )
start += 1
# XXX pre-install scripts are currently refused in finalize_options()
# but if this feature is completed, it will also need to add
@@ -410,15 +499,13 @@ class bdist_msi(Command):
f.write('rem ="""\n%1 %0\nexit\n"""\n')
with open(self.pre_install_script) as fin:
f.write(fin.read())
- add_data(self.db, "Binary",
- [("PreInstall", msilib.Binary(scriptfn))
- ])
- add_data(self.db, "CustomAction",
- [("PreInstall", 2, "PreInstall", None)
- ])
- add_data(self.db, "InstallExecuteSequence",
- [("PreInstall", "NOT Installed", 450)])
-
+ add_data(self.db, "Binary", [("PreInstall", msilib.Binary(scriptfn))])
+ add_data(self.db, "CustomAction", [("PreInstall", 2, "PreInstall", None)])
+ add_data(
+ self.db,
+ "InstallExecuteSequence",
+ [("PreInstall", "NOT Installed", 450)],
+ )
def add_ui(self):
db = self.db
@@ -428,168 +515,322 @@ class bdist_msi(Command):
title = "[ProductName] Setup"
# see "Dialog Style Bits"
- modal = 3 # visible | modal
- modeless = 1 # visible
+ modal = 3 # visible | modal
+ modeless = 1 # visible
track_disk_space = 32
# UI customization properties
- add_data(db, "Property",
- # See "DefaultUIFont Property"
- [("DefaultUIFont", "DlgFont8"),
- # See "ErrorDialog Style Bit"
- ("ErrorDialog", "ErrorDlg"),
- ("Progress1", "Install"), # modified in maintenance type dlg
- ("Progress2", "installs"),
- ("MaintenanceForm_Action", "Repair"),
- # possible values: ALL, JUSTME
- ("WhichUsers", "ALL")
- ])
+ add_data(
+ db,
+ "Property",
+ # See "DefaultUIFont Property"
+ [
+ ("DefaultUIFont", "DlgFont8"),
+ # See "ErrorDialog Style Bit"
+ ("ErrorDialog", "ErrorDlg"),
+ ("Progress1", "Install"), # modified in maintenance type dlg
+ ("Progress2", "installs"),
+ ("MaintenanceForm_Action", "Repair"),
+ # possible values: ALL, JUSTME
+ ("WhichUsers", "ALL"),
+ ],
+ )
# Fonts, see "TextStyle Table"
- add_data(db, "TextStyle",
- [("DlgFont8", "Tahoma", 9, None, 0),
- ("DlgFontBold8", "Tahoma", 8, None, 1), #bold
- ("VerdanaBold10", "Verdana", 10, None, 1),
- ("VerdanaRed9", "Verdana", 9, 255, 0),
- ])
+ add_data(
+ db,
+ "TextStyle",
+ [
+ ("DlgFont8", "Tahoma", 9, None, 0),
+ ("DlgFontBold8", "Tahoma", 8, None, 1), # bold
+ ("VerdanaBold10", "Verdana", 10, None, 1),
+ ("VerdanaRed9", "Verdana", 9, 255, 0),
+ ],
+ )
# UI Sequences, see "InstallUISequence Table", "Using a Sequence Table"
# Numbers indicate sequence; see sequence.py for how these action integrate
- add_data(db, "InstallUISequence",
- [("PrepareDlg", "Not Privileged or Windows9x or Installed", 140),
- ("WhichUsersDlg", "Privileged and not Windows9x and not Installed", 141),
- # In the user interface, assume all-users installation if privileged.
- ("SelectFeaturesDlg", "Not Installed", 1230),
- # XXX no support for resume installations yet
- #("ResumeDlg", "Installed AND (RESUME OR Preselected)", 1240),
- ("MaintenanceTypeDlg", "Installed AND NOT RESUME AND NOT Preselected", 1250),
- ("ProgressDlg", None, 1280)])
+ add_data(
+ db,
+ "InstallUISequence",
+ [
+ ("PrepareDlg", "Not Privileged or Windows9x or Installed", 140),
+ (
+ "WhichUsersDlg",
+ "Privileged and not Windows9x and not Installed",
+ 141,
+ ),
+ # In the user interface, assume all-users installation if privileged.
+ ("SelectFeaturesDlg", "Not Installed", 1230),
+ # XXX no support for resume installations yet
+ # ("ResumeDlg", "Installed AND (RESUME OR Preselected)", 1240),
+ (
+ "MaintenanceTypeDlg",
+ "Installed AND NOT RESUME AND NOT Preselected",
+ 1250,
+ ),
+ ("ProgressDlg", None, 1280),
+ ],
+ )
add_data(db, 'ActionText', text.ActionText)
add_data(db, 'UIText', text.UIText)
#####################################################################
# Standard dialogs: FatalError, UserExit, ExitDialog
- fatal=PyDialog(db, "FatalError", x, y, w, h, modal, title,
- "Finish", "Finish", "Finish")
+ fatal = PyDialog(
+ db, "FatalError", x, y, w, h, modal, title, "Finish", "Finish", "Finish"
+ )
fatal.title("[ProductName] Installer ended prematurely")
- fatal.back("< Back", "Finish", active = 0)
- fatal.cancel("Cancel", "Back", active = 0)
- fatal.text("Description1", 15, 70, 320, 80, 0x30003,
- "[ProductName] setup ended prematurely because of an error. Your system has not been modified. To install this program at a later time, please run the installation again.")
- fatal.text("Description2", 15, 155, 320, 20, 0x30003,
- "Click the Finish button to exit the Installer.")
- c=fatal.next("Finish", "Cancel", name="Finish")
+ fatal.back("< Back", "Finish", active=0)
+ fatal.cancel("Cancel", "Back", active=0)
+ fatal.text(
+ "Description1",
+ 15,
+ 70,
+ 320,
+ 80,
+ 0x30003,
+ "[ProductName] setup ended prematurely because of an error. Your system has not been modified. To install this program at a later time, please run the installation again.",
+ )
+ fatal.text(
+ "Description2",
+ 15,
+ 155,
+ 320,
+ 20,
+ 0x30003,
+ "Click the Finish button to exit the Installer.",
+ )
+ c = fatal.next("Finish", "Cancel", name="Finish")
c.event("EndDialog", "Exit")
- user_exit=PyDialog(db, "UserExit", x, y, w, h, modal, title,
- "Finish", "Finish", "Finish")
+ user_exit = PyDialog(
+ db, "UserExit", x, y, w, h, modal, title, "Finish", "Finish", "Finish"
+ )
user_exit.title("[ProductName] Installer was interrupted")
- user_exit.back("< Back", "Finish", active = 0)
- user_exit.cancel("Cancel", "Back", active = 0)
- user_exit.text("Description1", 15, 70, 320, 80, 0x30003,
- "[ProductName] setup was interrupted. Your system has not been modified. "
- "To install this program at a later time, please run the installation again.")
- user_exit.text("Description2", 15, 155, 320, 20, 0x30003,
- "Click the Finish button to exit the Installer.")
+ user_exit.back("< Back", "Finish", active=0)
+ user_exit.cancel("Cancel", "Back", active=0)
+ user_exit.text(
+ "Description1",
+ 15,
+ 70,
+ 320,
+ 80,
+ 0x30003,
+ "[ProductName] setup was interrupted. Your system has not been modified. "
+ "To install this program at a later time, please run the installation again.",
+ )
+ user_exit.text(
+ "Description2",
+ 15,
+ 155,
+ 320,
+ 20,
+ 0x30003,
+ "Click the Finish button to exit the Installer.",
+ )
c = user_exit.next("Finish", "Cancel", name="Finish")
c.event("EndDialog", "Exit")
- exit_dialog = PyDialog(db, "ExitDialog", x, y, w, h, modal, title,
- "Finish", "Finish", "Finish")
+ exit_dialog = PyDialog(
+ db, "ExitDialog", x, y, w, h, modal, title, "Finish", "Finish", "Finish"
+ )
exit_dialog.title("Completing the [ProductName] Installer")
- exit_dialog.back("< Back", "Finish", active = 0)
- exit_dialog.cancel("Cancel", "Back", active = 0)
- exit_dialog.text("Description", 15, 235, 320, 20, 0x30003,
- "Click the Finish button to exit the Installer.")
+ exit_dialog.back("< Back", "Finish", active=0)
+ exit_dialog.cancel("Cancel", "Back", active=0)
+ exit_dialog.text(
+ "Description",
+ 15,
+ 235,
+ 320,
+ 20,
+ 0x30003,
+ "Click the Finish button to exit the Installer.",
+ )
c = exit_dialog.next("Finish", "Cancel", name="Finish")
c.event("EndDialog", "Return")
#####################################################################
# Required dialog: FilesInUse, ErrorDlg
- inuse = PyDialog(db, "FilesInUse",
- x, y, w, h,
- 19, # KeepModeless|Modal|Visible
- title,
- "Retry", "Retry", "Retry", bitmap=False)
- inuse.text("Title", 15, 6, 200, 15, 0x30003,
- r"{\DlgFontBold8}Files in Use")
- inuse.text("Description", 20, 23, 280, 20, 0x30003,
- "Some files that need to be updated are currently in use.")
- inuse.text("Text", 20, 55, 330, 50, 3,
- "The following applications are using files that need to be updated by this setup. Close these applications and then click Retry to continue the installation or Cancel to exit it.")
- inuse.control("List", "ListBox", 20, 107, 330, 130, 7, "FileInUseProcess",
- None, None, None)
- c=inuse.back("Exit", "Ignore", name="Exit")
+ inuse = PyDialog(
+ db,
+ "FilesInUse",
+ x,
+ y,
+ w,
+ h,
+ 19, # KeepModeless|Modal|Visible
+ title,
+ "Retry",
+ "Retry",
+ "Retry",
+ bitmap=False,
+ )
+ inuse.text("Title", 15, 6, 200, 15, 0x30003, r"{\DlgFontBold8}Files in Use")
+ inuse.text(
+ "Description",
+ 20,
+ 23,
+ 280,
+ 20,
+ 0x30003,
+ "Some files that need to be updated are currently in use.",
+ )
+ inuse.text(
+ "Text",
+ 20,
+ 55,
+ 330,
+ 50,
+ 3,
+ "The following applications are using files that need to be updated by this setup. Close these applications and then click Retry to continue the installation or Cancel to exit it.",
+ )
+ inuse.control(
+ "List",
+ "ListBox",
+ 20,
+ 107,
+ 330,
+ 130,
+ 7,
+ "FileInUseProcess",
+ None,
+ None,
+ None,
+ )
+ c = inuse.back("Exit", "Ignore", name="Exit")
c.event("EndDialog", "Exit")
- c=inuse.next("Ignore", "Retry", name="Ignore")
+ c = inuse.next("Ignore", "Retry", name="Ignore")
c.event("EndDialog", "Ignore")
- c=inuse.cancel("Retry", "Exit", name="Retry")
- c.event("EndDialog","Retry")
+ c = inuse.cancel("Retry", "Exit", name="Retry")
+ c.event("EndDialog", "Retry")
# See "Error Dialog". See "ICE20" for the required names of the controls.
- error = Dialog(db, "ErrorDlg",
- 50, 10, 330, 101,
- 65543, # Error|Minimize|Modal|Visible
- title,
- "ErrorText", None, None)
- error.text("ErrorText", 50,9,280,48,3, "")
- #error.control("ErrorIcon", "Icon", 15, 9, 24, 24, 5242881, None, "py.ico", None, None)
- error.pushbutton("N",120,72,81,21,3,"No",None).event("EndDialog","ErrorNo")
- error.pushbutton("Y",240,72,81,21,3,"Yes",None).event("EndDialog","ErrorYes")
- error.pushbutton("A",0,72,81,21,3,"Abort",None).event("EndDialog","ErrorAbort")
- error.pushbutton("C",42,72,81,21,3,"Cancel",None).event("EndDialog","ErrorCancel")
- error.pushbutton("I",81,72,81,21,3,"Ignore",None).event("EndDialog","ErrorIgnore")
- error.pushbutton("O",159,72,81,21,3,"Ok",None).event("EndDialog","ErrorOk")
- error.pushbutton("R",198,72,81,21,3,"Retry",None).event("EndDialog","ErrorRetry")
+ error = Dialog(
+ db,
+ "ErrorDlg",
+ 50,
+ 10,
+ 330,
+ 101,
+ 65543, # Error|Minimize|Modal|Visible
+ title,
+ "ErrorText",
+ None,
+ None,
+ )
+ error.text("ErrorText", 50, 9, 280, 48, 3, "")
+ # error.control("ErrorIcon", "Icon", 15, 9, 24, 24, 5242881, None, "py.ico", None, None)
+ error.pushbutton("N", 120, 72, 81, 21, 3, "No", None).event(
+ "EndDialog", "ErrorNo"
+ )
+ error.pushbutton("Y", 240, 72, 81, 21, 3, "Yes", None).event(
+ "EndDialog", "ErrorYes"
+ )
+ error.pushbutton("A", 0, 72, 81, 21, 3, "Abort", None).event(
+ "EndDialog", "ErrorAbort"
+ )
+ error.pushbutton("C", 42, 72, 81, 21, 3, "Cancel", None).event(
+ "EndDialog", "ErrorCancel"
+ )
+ error.pushbutton("I", 81, 72, 81, 21, 3, "Ignore", None).event(
+ "EndDialog", "ErrorIgnore"
+ )
+ error.pushbutton("O", 159, 72, 81, 21, 3, "Ok", None).event(
+ "EndDialog", "ErrorOk"
+ )
+ error.pushbutton("R", 198, 72, 81, 21, 3, "Retry", None).event(
+ "EndDialog", "ErrorRetry"
+ )
#####################################################################
# Global "Query Cancel" dialog
- cancel = Dialog(db, "CancelDlg", 50, 10, 260, 85, 3, title,
- "No", "No", "No")
- cancel.text("Text", 48, 15, 194, 30, 3,
- "Are you sure you want to cancel [ProductName] installation?")
- #cancel.control("Icon", "Icon", 15, 15, 24, 24, 5242881, None,
+ cancel = Dialog(db, "CancelDlg", 50, 10, 260, 85, 3, title, "No", "No", "No")
+ cancel.text(
+ "Text",
+ 48,
+ 15,
+ 194,
+ 30,
+ 3,
+ "Are you sure you want to cancel [ProductName] installation?",
+ )
+ # cancel.control("Icon", "Icon", 15, 15, 24, 24, 5242881, None,
# "py.ico", None, None)
- c=cancel.pushbutton("Yes", 72, 57, 56, 17, 3, "Yes", "No")
+ c = cancel.pushbutton("Yes", 72, 57, 56, 17, 3, "Yes", "No")
c.event("EndDialog", "Exit")
- c=cancel.pushbutton("No", 132, 57, 56, 17, 3, "No", "Yes")
+ c = cancel.pushbutton("No", 132, 57, 56, 17, 3, "No", "Yes")
c.event("EndDialog", "Return")
#####################################################################
# Global "Wait for costing" dialog
- costing = Dialog(db, "WaitForCostingDlg", 50, 10, 260, 85, modal, title,
- "Return", "Return", "Return")
- costing.text("Text", 48, 15, 194, 30, 3,
- "Please wait while the installer finishes determining your disk space requirements.")
+ costing = Dialog(
+ db,
+ "WaitForCostingDlg",
+ 50,
+ 10,
+ 260,
+ 85,
+ modal,
+ title,
+ "Return",
+ "Return",
+ "Return",
+ )
+ costing.text(
+ "Text",
+ 48,
+ 15,
+ 194,
+ 30,
+ 3,
+ "Please wait while the installer finishes determining your disk space requirements.",
+ )
c = costing.pushbutton("Return", 102, 57, 56, 17, 3, "Return", None)
c.event("EndDialog", "Exit")
#####################################################################
# Preparation dialog: no user input except cancellation
- prep = PyDialog(db, "PrepareDlg", x, y, w, h, modeless, title,
- "Cancel", "Cancel", "Cancel")
- prep.text("Description", 15, 70, 320, 40, 0x30003,
- "Please wait while the Installer prepares to guide you through the installation.")
+ prep = PyDialog(
+ db, "PrepareDlg", x, y, w, h, modeless, title, "Cancel", "Cancel", "Cancel"
+ )
+ prep.text(
+ "Description",
+ 15,
+ 70,
+ 320,
+ 40,
+ 0x30003,
+ "Please wait while the Installer prepares to guide you through the installation.",
+ )
prep.title("Welcome to the [ProductName] Installer")
- c=prep.text("ActionText", 15, 110, 320, 20, 0x30003, "Pondering...")
+ c = prep.text("ActionText", 15, 110, 320, 20, 0x30003, "Pondering...")
c.mapping("ActionText", "Text")
- c=prep.text("ActionData", 15, 135, 320, 30, 0x30003, None)
+ c = prep.text("ActionData", 15, 135, 320, 30, 0x30003, None)
c.mapping("ActionData", "Text")
prep.back("Back", None, active=0)
prep.next("Next", None, active=0)
- c=prep.cancel("Cancel", None)
+ c = prep.cancel("Cancel", None)
c.event("SpawnDialog", "CancelDlg")
#####################################################################
# Feature (Python directory) selection
- seldlg = PyDialog(db, "SelectFeaturesDlg", x, y, w, h, modal, title,
- "Next", "Next", "Cancel")
+ seldlg = PyDialog(
+ db, "SelectFeaturesDlg", x, y, w, h, modal, title, "Next", "Next", "Cancel"
+ )
seldlg.title("Select Python Installations")
- seldlg.text("Hint", 15, 30, 300, 20, 3,
- "Select the Python locations where %s should be installed."
- % self.distribution.get_fullname())
+ seldlg.text(
+ "Hint",
+ 15,
+ 30,
+ 300,
+ 20,
+ 3,
+ "Select the Python locations where %s should be installed."
+ % self.distribution.get_fullname(),
+ )
seldlg.back("< Back", None, active=0)
c = seldlg.next("Next >", "Cancel")
@@ -597,30 +838,56 @@ class bdist_msi(Command):
c.event("[TARGETDIR]", "[SourceDir]", ordering=order)
for version in self.versions + [self.other_version]:
order += 1
- c.event("[TARGETDIR]", "[TARGETDIR%s]" % version,
- "FEATURE_SELECTED AND &Python%s=3" % version,
- ordering=order)
+ c.event(
+ "[TARGETDIR]",
+ "[TARGETDIR%s]" % version,
+ "FEATURE_SELECTED AND &Python%s=3" % version,
+ ordering=order,
+ )
c.event("SpawnWaitDialog", "WaitForCostingDlg", ordering=order + 1)
c.event("EndDialog", "Return", ordering=order + 2)
c = seldlg.cancel("Cancel", "Features")
c.event("SpawnDialog", "CancelDlg")
- c = seldlg.control("Features", "SelectionTree", 15, 60, 300, 120, 3,
- "FEATURE", None, "PathEdit", None)
+ c = seldlg.control(
+ "Features",
+ "SelectionTree",
+ 15,
+ 60,
+ 300,
+ 120,
+ 3,
+ "FEATURE",
+ None,
+ "PathEdit",
+ None,
+ )
c.event("[FEATURE_SELECTED]", "1")
ver = self.other_version
install_other_cond = "FEATURE_SELECTED AND &Python%s=3" % ver
dont_install_other_cond = "FEATURE_SELECTED AND &Python%s<>3" % ver
- c = seldlg.text("Other", 15, 200, 300, 15, 3,
- "Provide an alternate Python location")
+ c = seldlg.text(
+ "Other", 15, 200, 300, 15, 3, "Provide an alternate Python location"
+ )
c.condition("Enable", install_other_cond)
c.condition("Show", install_other_cond)
c.condition("Disable", dont_install_other_cond)
c.condition("Hide", dont_install_other_cond)
- c = seldlg.control("PathEdit", "PathEdit", 15, 215, 300, 16, 1,
- "TARGETDIR" + ver, None, "Next", None)
+ c = seldlg.control(
+ "PathEdit",
+ "PathEdit",
+ 15,
+ 215,
+ 300,
+ 16,
+ 1,
+ "TARGETDIR" + ver,
+ None,
+ "Next",
+ None,
+ )
c.condition("Enable", install_other_cond)
c.condition("Show", install_other_cond)
c.condition("Disable", dont_install_other_cond)
@@ -628,20 +895,47 @@ class bdist_msi(Command):
#####################################################################
# Disk cost
- cost = PyDialog(db, "DiskCostDlg", x, y, w, h, modal, title,
- "OK", "OK", "OK", bitmap=False)
- cost.text("Title", 15, 6, 200, 15, 0x30003,
- r"{\DlgFontBold8}Disk Space Requirements")
- cost.text("Description", 20, 20, 280, 20, 0x30003,
- "The disk space required for the installation of the selected features.")
- cost.text("Text", 20, 53, 330, 60, 3,
- "The highlighted volumes (if any) do not have enough disk space "
- "available for the currently selected features. You can either "
- "remove some files from the highlighted volumes, or choose to "
- "install less features onto local drive(s), or select different "
- "destination drive(s).")
- cost.control("VolumeList", "VolumeCostList", 20, 100, 330, 150, 393223,
- None, "{120}{70}{70}{70}{70}", None, None)
+ cost = PyDialog(
+ db, "DiskCostDlg", x, y, w, h, modal, title, "OK", "OK", "OK", bitmap=False
+ )
+ cost.text(
+ "Title", 15, 6, 200, 15, 0x30003, r"{\DlgFontBold8}Disk Space Requirements"
+ )
+ cost.text(
+ "Description",
+ 20,
+ 20,
+ 280,
+ 20,
+ 0x30003,
+ "The disk space required for the installation of the selected features.",
+ )
+ cost.text(
+ "Text",
+ 20,
+ 53,
+ 330,
+ 60,
+ 3,
+ "The highlighted volumes (if any) do not have enough disk space "
+ "available for the currently selected features. You can either "
+ "remove some files from the highlighted volumes, or choose to "
+ "install less features onto local drive(s), or select different "
+ "destination drive(s).",
+ )
+ cost.control(
+ "VolumeList",
+ "VolumeCostList",
+ 20,
+ 100,
+ 330,
+ 150,
+ 393223,
+ None,
+ "{120}{70}{70}{70}{70}",
+ None,
+ None,
+ )
cost.xbutton("OK", "Ok", None, 0.5).event("EndDialog", "Return")
#####################################################################
@@ -655,12 +949,26 @@ class bdist_msi(Command):
# On Windows9x, the ALLUSERS property is ignored on the command line
# and in the Property table, but installer fails according to the documentation
# if a dialog attempts to set ALLUSERS.
- whichusers = PyDialog(db, "WhichUsersDlg", x, y, w, h, modal, title,
- "AdminInstall", "Next", "Cancel")
- whichusers.title("Select whether to install [ProductName] for all users of this computer.")
+ whichusers = PyDialog(
+ db,
+ "WhichUsersDlg",
+ x,
+ y,
+ w,
+ h,
+ modal,
+ title,
+ "AdminInstall",
+ "Next",
+ "Cancel",
+ )
+ whichusers.title(
+ "Select whether to install [ProductName] for all users of this computer."
+ )
# A radio group with two options: allusers, justme
- g = whichusers.radiogroup("AdminInstall", 15, 60, 260, 50, 3,
- "WhichUsers", "", "Next")
+ g = whichusers.radiogroup(
+ "AdminInstall", 15, 60, 260, 50, 3, "WhichUsers", "", "Next"
+ )
g.add("ALL", 0, 5, 150, 20, "Install for all users")
g.add("JUSTME", 0, 25, 150, 20, "Install just for me")
@@ -668,30 +976,67 @@ class bdist_msi(Command):
c = whichusers.next("Next >", "Cancel")
c.event("[ALLUSERS]", "1", 'WhichUsers="ALL"', 1)
- c.event("EndDialog", "Return", ordering = 2)
+ c.event("EndDialog", "Return", ordering=2)
c = whichusers.cancel("Cancel", "AdminInstall")
c.event("SpawnDialog", "CancelDlg")
#####################################################################
# Installation Progress dialog (modeless)
- progress = PyDialog(db, "ProgressDlg", x, y, w, h, modeless, title,
- "Cancel", "Cancel", "Cancel", bitmap=False)
- progress.text("Title", 20, 15, 200, 15, 0x30003,
- r"{\DlgFontBold8}[Progress1] [ProductName]")
- progress.text("Text", 35, 65, 300, 30, 3,
- "Please wait while the Installer [Progress2] [ProductName]. "
- "This may take several minutes.")
+ progress = PyDialog(
+ db,
+ "ProgressDlg",
+ x,
+ y,
+ w,
+ h,
+ modeless,
+ title,
+ "Cancel",
+ "Cancel",
+ "Cancel",
+ bitmap=False,
+ )
+ progress.text(
+ "Title",
+ 20,
+ 15,
+ 200,
+ 15,
+ 0x30003,
+ r"{\DlgFontBold8}[Progress1] [ProductName]",
+ )
+ progress.text(
+ "Text",
+ 35,
+ 65,
+ 300,
+ 30,
+ 3,
+ "Please wait while the Installer [Progress2] [ProductName]. "
+ "This may take several minutes.",
+ )
progress.text("StatusLabel", 35, 100, 35, 20, 3, "Status:")
- c=progress.text("ActionText", 70, 100, w-70, 20, 3, "Pondering...")
+ c = progress.text("ActionText", 70, 100, w - 70, 20, 3, "Pondering...")
c.mapping("ActionText", "Text")
- #c=progress.text("ActionData", 35, 140, 300, 20, 3, None)
- #c.mapping("ActionData", "Text")
-
- c=progress.control("ProgressBar", "ProgressBar", 35, 120, 300, 10, 65537,
- None, "Progress done", None, None)
+ # c=progress.text("ActionData", 35, 140, 300, 20, 3, None)
+ # c.mapping("ActionData", "Text")
+
+ c = progress.control(
+ "ProgressBar",
+ "ProgressBar",
+ 35,
+ 120,
+ 300,
+ 10,
+ 65537,
+ None,
+ "Progress done",
+ None,
+ None,
+ )
c.mapping("SetProgress", "Progress")
progress.back("< Back", "Next", active=False)
@@ -700,23 +1045,40 @@ class bdist_msi(Command):
###################################################################
# Maintenance type: repair/uninstall
- maint = PyDialog(db, "MaintenanceTypeDlg", x, y, w, h, modal, title,
- "Next", "Next", "Cancel")
+ maint = PyDialog(
+ db, "MaintenanceTypeDlg", x, y, w, h, modal, title, "Next", "Next", "Cancel"
+ )
maint.title("Welcome to the [ProductName] Setup Wizard")
- maint.text("BodyText", 15, 63, 330, 42, 3,
- "Select whether you want to repair or remove [ProductName].")
- g=maint.radiogroup("RepairRadioGroup", 15, 108, 330, 60, 3,
- "MaintenanceForm_Action", "", "Next")
- #g.add("Change", 0, 0, 200, 17, "&Change [ProductName]")
+ maint.text(
+ "BodyText",
+ 15,
+ 63,
+ 330,
+ 42,
+ 3,
+ "Select whether you want to repair or remove [ProductName].",
+ )
+ g = maint.radiogroup(
+ "RepairRadioGroup",
+ 15,
+ 108,
+ 330,
+ 60,
+ 3,
+ "MaintenanceForm_Action",
+ "",
+ "Next",
+ )
+ # g.add("Change", 0, 0, 200, 17, "&Change [ProductName]")
g.add("Repair", 0, 18, 200, 17, "&Repair [ProductName]")
g.add("Remove", 0, 36, 200, 17, "Re&move [ProductName]")
maint.back("< Back", None, active=False)
- c=maint.next("Finish", "Cancel")
+ c = maint.next("Finish", "Cancel")
# Change installation: Change progress dialog to "Change", then ask
# for feature selection
- #c.event("[Progress1]", "Change", 'MaintenanceForm_Action="Change"', 1)
- #c.event("[Progress2]", "changes", 'MaintenanceForm_Action="Change"', 2)
+ # c.event("[Progress1]", "Change", 'MaintenanceForm_Action="Change"', 1)
+ # c.event("[Progress2]", "changes", 'MaintenanceForm_Action="Change"', 2)
# Reinstall: Change progress dialog to "Repair", then invoke reinstall
# Also set list of reinstalled features to "ALL"
@@ -734,15 +1096,18 @@ class bdist_msi(Command):
# Close dialog when maintenance action scheduled
c.event("EndDialog", "Return", 'MaintenanceForm_Action<>"Change"', 20)
- #c.event("NewDialog", "SelectFeaturesDlg", 'MaintenanceForm_Action="Change"', 21)
+ # c.event("NewDialog", "SelectFeaturesDlg", 'MaintenanceForm_Action="Change"', 21)
maint.cancel("Cancel", "RepairRadioGroup").event("SpawnDialog", "CancelDlg")
def get_installer_filename(self, fullname):
# Factored out to allow overriding in subclasses
if self.target_version:
- base_name = "%s.%s-py%s.msi" % (fullname, self.plat_name,
- self.target_version)
+ base_name = "%s.%s-py%s.msi" % (
+ fullname,
+ self.plat_name,
+ self.target_version,
+ )
else:
base_name = "%s.%s.msi" % (fullname, self.plat_name)
installer_name = os.path.join(self.dist_dir, base_name)
diff --git a/setuptools/_distutils/command/bdist_rpm.py b/setuptools/_distutils/command/bdist_rpm.py
index 550cbfa1..cf4b9525 100644
--- a/setuptools/_distutils/command/bdist_rpm.py
+++ b/setuptools/_distutils/command/bdist_rpm.py
@@ -11,126 +11,137 @@ from distutils.errors import *
from distutils.sysconfig import get_python_version
from distutils import log
+
class bdist_rpm(Command):
description = "create an RPM distribution"
user_options = [
- ('bdist-base=', None,
- "base directory for creating built distributions"),
- ('rpm-base=', None,
- "base directory for creating RPMs (defaults to \"rpm\" under "
- "--bdist-base; must be specified for RPM 2)"),
- ('dist-dir=', 'd',
- "directory to put final RPM files in "
- "(and .spec files if --spec-only)"),
- ('python=', None,
- "path to Python interpreter to hard-code in the .spec file "
- "(default: \"python\")"),
- ('fix-python', None,
- "hard-code the exact path to the current Python interpreter in "
- "the .spec file"),
- ('spec-only', None,
- "only regenerate spec file"),
- ('source-only', None,
- "only generate source RPM"),
- ('binary-only', None,
- "only generate binary RPM"),
- ('use-bzip2', None,
- "use bzip2 instead of gzip to create source distribution"),
-
+ ('bdist-base=', None, "base directory for creating built distributions"),
+ (
+ 'rpm-base=',
+ None,
+ "base directory for creating RPMs (defaults to \"rpm\" under "
+ "--bdist-base; must be specified for RPM 2)",
+ ),
+ (
+ 'dist-dir=',
+ 'd',
+ "directory to put final RPM files in " "(and .spec files if --spec-only)",
+ ),
+ (
+ 'python=',
+ None,
+ "path to Python interpreter to hard-code in the .spec file "
+ "(default: \"python\")",
+ ),
+ (
+ 'fix-python',
+ None,
+ "hard-code the exact path to the current Python interpreter in "
+ "the .spec file",
+ ),
+ ('spec-only', None, "only regenerate spec file"),
+ ('source-only', None, "only generate source RPM"),
+ ('binary-only', None, "only generate binary RPM"),
+ ('use-bzip2', None, "use bzip2 instead of gzip to create source distribution"),
# More meta-data: too RPM-specific to put in the setup script,
# but needs to go in the .spec file -- so we make these options
# to "bdist_rpm". The idea is that packagers would put this
# info in setup.cfg, although they are of course free to
# supply it on the command line.
- ('distribution-name=', None,
- "name of the (Linux) distribution to which this "
- "RPM applies (*not* the name of the module distribution!)"),
- ('group=', None,
- "package classification [default: \"Development/Libraries\"]"),
- ('release=', None,
- "RPM release number"),
- ('serial=', None,
- "RPM serial number"),
- ('vendor=', None,
- "RPM \"vendor\" (eg. \"Joe Blow <joe@example.com>\") "
- "[default: maintainer or author from setup script]"),
- ('packager=', None,
- "RPM packager (eg. \"Jane Doe <jane@example.net>\") "
- "[default: vendor]"),
- ('doc-files=', None,
- "list of documentation files (space or comma-separated)"),
- ('changelog=', None,
- "RPM changelog"),
- ('icon=', None,
- "name of icon file"),
- ('provides=', None,
- "capabilities provided by this package"),
- ('requires=', None,
- "capabilities required by this package"),
- ('conflicts=', None,
- "capabilities which conflict with this package"),
- ('build-requires=', None,
- "capabilities required to build this package"),
- ('obsoletes=', None,
- "capabilities made obsolete by this package"),
- ('no-autoreq', None,
- "do not automatically calculate dependencies"),
-
+ (
+ 'distribution-name=',
+ None,
+ "name of the (Linux) distribution to which this "
+ "RPM applies (*not* the name of the module distribution!)",
+ ),
+ ('group=', None, "package classification [default: \"Development/Libraries\"]"),
+ ('release=', None, "RPM release number"),
+ ('serial=', None, "RPM serial number"),
+ (
+ 'vendor=',
+ None,
+ "RPM \"vendor\" (eg. \"Joe Blow <joe@example.com>\") "
+ "[default: maintainer or author from setup script]",
+ ),
+ (
+ 'packager=',
+ None,
+ "RPM packager (eg. \"Jane Doe <jane@example.net>\") " "[default: vendor]",
+ ),
+ ('doc-files=', None, "list of documentation files (space or comma-separated)"),
+ ('changelog=', None, "RPM changelog"),
+ ('icon=', None, "name of icon file"),
+ ('provides=', None, "capabilities provided by this package"),
+ ('requires=', None, "capabilities required by this package"),
+ ('conflicts=', None, "capabilities which conflict with this package"),
+ ('build-requires=', None, "capabilities required to build this package"),
+ ('obsoletes=', None, "capabilities made obsolete by this package"),
+ ('no-autoreq', None, "do not automatically calculate dependencies"),
# Actions to take when building RPM
- ('keep-temp', 'k',
- "don't clean up RPM build directory"),
- ('no-keep-temp', None,
- "clean up RPM build directory [default]"),
- ('use-rpm-opt-flags', None,
- "compile with RPM_OPT_FLAGS when building from source RPM"),
- ('no-rpm-opt-flags', None,
- "do not pass any RPM CFLAGS to compiler"),
- ('rpm3-mode', None,
- "RPM 3 compatibility mode (default)"),
- ('rpm2-mode', None,
- "RPM 2 compatibility mode"),
-
+ ('keep-temp', 'k', "don't clean up RPM build directory"),
+ ('no-keep-temp', None, "clean up RPM build directory [default]"),
+ (
+ 'use-rpm-opt-flags',
+ None,
+ "compile with RPM_OPT_FLAGS when building from source RPM",
+ ),
+ ('no-rpm-opt-flags', None, "do not pass any RPM CFLAGS to compiler"),
+ ('rpm3-mode', None, "RPM 3 compatibility mode (default)"),
+ ('rpm2-mode', None, "RPM 2 compatibility mode"),
# Add the hooks necessary for specifying custom scripts
- ('prep-script=', None,
- "Specify a script for the PREP phase of RPM building"),
- ('build-script=', None,
- "Specify a script for the BUILD phase of RPM building"),
-
- ('pre-install=', None,
- "Specify a script for the pre-INSTALL phase of RPM building"),
- ('install-script=', None,
- "Specify a script for the INSTALL phase of RPM building"),
- ('post-install=', None,
- "Specify a script for the post-INSTALL phase of RPM building"),
-
- ('pre-uninstall=', None,
- "Specify a script for the pre-UNINSTALL phase of RPM building"),
- ('post-uninstall=', None,
- "Specify a script for the post-UNINSTALL phase of RPM building"),
-
- ('clean-script=', None,
- "Specify a script for the CLEAN phase of RPM building"),
-
- ('verify-script=', None,
- "Specify a script for the VERIFY phase of the RPM build"),
-
+ ('prep-script=', None, "Specify a script for the PREP phase of RPM building"),
+ ('build-script=', None, "Specify a script for the BUILD phase of RPM building"),
+ (
+ 'pre-install=',
+ None,
+ "Specify a script for the pre-INSTALL phase of RPM building",
+ ),
+ (
+ 'install-script=',
+ None,
+ "Specify a script for the INSTALL phase of RPM building",
+ ),
+ (
+ 'post-install=',
+ None,
+ "Specify a script for the post-INSTALL phase of RPM building",
+ ),
+ (
+ 'pre-uninstall=',
+ None,
+ "Specify a script for the pre-UNINSTALL phase of RPM building",
+ ),
+ (
+ 'post-uninstall=',
+ None,
+ "Specify a script for the post-UNINSTALL phase of RPM building",
+ ),
+ ('clean-script=', None, "Specify a script for the CLEAN phase of RPM building"),
+ (
+ 'verify-script=',
+ None,
+ "Specify a script for the VERIFY phase of the RPM build",
+ ),
# Allow a packager to explicitly force an architecture
- ('force-arch=', None,
- "Force an architecture onto the RPM build process"),
-
- ('quiet', 'q',
- "Run the INSTALL phase of RPM building in quiet mode"),
- ]
-
- boolean_options = ['keep-temp', 'use-rpm-opt-flags', 'rpm3-mode',
- 'no-autoreq', 'quiet']
-
- negative_opt = {'no-keep-temp': 'keep-temp',
- 'no-rpm-opt-flags': 'use-rpm-opt-flags',
- 'rpm2-mode': 'rpm3-mode'}
-
+ ('force-arch=', None, "Force an architecture onto the RPM build process"),
+ ('quiet', 'q', "Run the INSTALL phase of RPM building in quiet mode"),
+ ]
+
+ boolean_options = [
+ 'keep-temp',
+ 'use-rpm-opt-flags',
+ 'rpm3-mode',
+ 'no-autoreq',
+ 'quiet',
+ ]
+
+ negative_opt = {
+ 'no-keep-temp': 'keep-temp',
+ 'no-rpm-opt-flags': 'use-rpm-opt-flags',
+ 'rpm2-mode': 'rpm3-mode',
+ }
def initialize_options(self):
self.bdist_base = None
@@ -181,8 +192,7 @@ class bdist_rpm(Command):
self.set_undefined_options('bdist', ('bdist_base', 'bdist_base'))
if self.rpm_base is None:
if not self.rpm3_mode:
- raise DistutilsOptionError(
- "you must specify --rpm-base in RPM 2 mode")
+ raise DistutilsOptionError("you must specify --rpm-base in RPM 2 mode")
self.rpm_base = os.path.join(self.bdist_base, "rpm")
if self.python is None:
@@ -192,14 +202,17 @@ class bdist_rpm(Command):
self.python = "python3"
elif self.fix_python:
raise DistutilsOptionError(
- "--python and --fix-python are mutually exclusive options")
+ "--python and --fix-python are mutually exclusive options"
+ )
if os.name != 'posix':
- raise DistutilsPlatformError("don't know how to create RPM "
- "distributions on platform %s" % os.name)
+ raise DistutilsPlatformError(
+ "don't know how to create RPM " "distributions on platform %s" % os.name
+ )
if self.binary_only and self.source_only:
raise DistutilsOptionError(
- "cannot supply both '--source-only' and '--binary-only'")
+ "cannot supply both '--source-only' and '--binary-only'"
+ )
# don't pass CFLAGS to pure python distributions
if not self.distribution.has_ext_modules():
@@ -210,9 +223,11 @@ class bdist_rpm(Command):
def finalize_package_data(self):
self.ensure_string('group', "Development/Libraries")
- self.ensure_string('vendor',
- "%s <%s>" % (self.distribution.get_contact(),
- self.distribution.get_contact_email()))
+ self.ensure_string(
+ 'vendor',
+ "%s <%s>"
+ % (self.distribution.get_contact(), self.distribution.get_contact_email()),
+ )
self.ensure_string('packager')
self.ensure_string_list('doc_files')
if isinstance(self.doc_files, list):
@@ -221,12 +236,12 @@ class bdist_rpm(Command):
self.doc_files.append(readme)
self.ensure_string('release', "1")
- self.ensure_string('serial') # should it be an int?
+ self.ensure_string('serial') # should it be an int?
self.ensure_string('distribution_name')
self.ensure_string('changelog')
- # Format changelog correctly
+ # Format changelog correctly
self.changelog = self._format_changelog(self.changelog)
self.ensure_filename('icon')
@@ -274,14 +289,12 @@ class bdist_rpm(Command):
# Spec file goes into 'dist_dir' if '--spec-only specified',
# build/rpm.<plat> otherwise.
- spec_path = os.path.join(spec_dir,
- "%s.spec" % self.distribution.get_name())
- self.execute(write_file,
- (spec_path,
- self._make_spec_file()),
- "writing '%s'" % spec_path)
-
- if self.spec_only: # stop if requested
+ spec_path = os.path.join(spec_dir, "%s.spec" % self.distribution.get_name())
+ self.execute(
+ write_file, (spec_path, self._make_spec_file()), "writing '%s'" % spec_path
+ )
+
+ if self.spec_only: # stop if requested
return
# Make a source distribution and copy to SOURCES directory with
@@ -303,14 +316,13 @@ class bdist_rpm(Command):
if os.path.exists(self.icon):
self.copy_file(self.icon, source_dir)
else:
- raise DistutilsFileError(
- "icon file '%s' does not exist" % self.icon)
+ raise DistutilsFileError("icon file '%s' does not exist" % self.icon)
# build package
log.info("building RPMs")
rpm_cmd = ['rpmbuild']
- if self.source_only: # what kind of RPMs?
+ if self.source_only: # what kind of RPMs?
rpm_cmd.append('-bs')
elif self.binary_only:
rpm_cmd.append('-bb')
@@ -318,8 +330,7 @@ class bdist_rpm(Command):
rpm_cmd.append('-ba')
rpm_cmd.extend(['--define', '__python %s' % self.python])
if self.rpm3_mode:
- rpm_cmd.extend(['--define',
- '_topdir %s' % os.path.abspath(self.rpm_base)])
+ rpm_cmd.extend(['--define', '_topdir %s' % os.path.abspath(self.rpm_base)])
if not self.keep_temp:
rpm_cmd.append('--clean')
@@ -335,7 +346,10 @@ class bdist_rpm(Command):
src_rpm = nvr_string + ".src.rpm"
non_src_rpm = "%{arch}/" + nvr_string + ".%{arch}.rpm"
q_cmd = r"rpm -q --qf '%s %s\n' --specfile '%s'" % (
- src_rpm, non_src_rpm, spec_path)
+ src_rpm,
+ non_src_rpm,
+ spec_path,
+ )
out = os.popen(q_cmd)
try:
@@ -346,7 +360,7 @@ class bdist_rpm(Command):
if not line:
break
l = line.strip().split()
- assert(len(l) == 2)
+ assert len(l) == 2
binary_rpms.append(l[1])
# The source rpm is named after the first entry in the spec file
if source_rpm is None:
@@ -369,21 +383,20 @@ class bdist_rpm(Command):
if not self.binary_only:
srpm = os.path.join(rpm_dir['SRPMS'], source_rpm)
- assert(os.path.exists(srpm))
+ assert os.path.exists(srpm)
self.move_file(srpm, self.dist_dir)
filename = os.path.join(self.dist_dir, source_rpm)
- self.distribution.dist_files.append(
- ('bdist_rpm', pyversion, filename))
+ self.distribution.dist_files.append(('bdist_rpm', pyversion, filename))
if not self.source_only:
for rpm in binary_rpms:
rpm = os.path.join(rpm_dir['RPMS'], rpm)
if os.path.exists(rpm):
self.move_file(rpm, self.dist_dir)
- filename = os.path.join(self.dist_dir,
- os.path.basename(rpm))
+ filename = os.path.join(self.dist_dir, os.path.basename(rpm))
self.distribution.dist_files.append(
- ('bdist_rpm', pyversion, filename))
+ ('bdist_rpm', pyversion, filename)
+ )
def _dist_path(self, path):
return os.path.join(self.dist_dir, os.path.basename(path))
@@ -395,12 +408,12 @@ class bdist_rpm(Command):
# definitions and headers
spec_file = [
'%define name ' + self.distribution.get_name(),
- '%define version ' + self.distribution.get_version().replace('-','_'),
+ '%define version ' + self.distribution.get_version().replace('-', '_'),
'%define unmangled_version ' + self.distribution.get_version(),
- '%define release ' + self.release.replace('-','_'),
+ '%define release ' + self.release.replace('-', '_'),
'',
- 'Summary: ' + self.distribution.get_description(),
- ]
+ 'Summary: ' + (self.distribution.get_description() or "UNKNOWN"),
+ ]
# Workaround for #14443 which affects some RPM based systems such as
# RHEL6 (and probably derivatives)
@@ -408,8 +421,9 @@ class bdist_rpm(Command):
# Generate a potential replacement value for __os_install_post (whilst
# normalizing the whitespace to simplify the test for whether the
# invocation of brp-python-bytecompile passes in __python):
- vendor_hook = '\n'.join([' %s \\' % line.strip()
- for line in vendor_hook.splitlines()])
+ vendor_hook = '\n'.join(
+ [' %s \\' % line.strip() for line in vendor_hook.splitlines()]
+ )
problem = "brp-python-bytecompile \\\n"
fixed = "brp-python-bytecompile %{__python} \\\n"
fixed_hook = vendor_hook.replace(problem, fixed)
@@ -420,14 +434,17 @@ class bdist_rpm(Command):
# put locale summaries into spec file
# XXX not supported for now (hard to put a dictionary
# in a config file -- arg!)
- #for locale in self.summaries.keys():
+ # for locale in self.summaries.keys():
# spec_file.append('Summary(%s): %s' % (locale,
# self.summaries[locale]))
- spec_file.extend([
- 'Name: %{name}',
- 'Version: %{version}',
- 'Release: %{release}',])
+ spec_file.extend(
+ [
+ 'Name: %{name}',
+ 'Version: %{version}',
+ 'Release: %{release}',
+ ]
+ )
# XXX yuck! this filename is available from the "sdist" command,
# but only after it has run: and we create the spec file before
@@ -437,42 +454,44 @@ class bdist_rpm(Command):
else:
spec_file.append('Source0: %{name}-%{unmangled_version}.tar.gz')
- spec_file.extend([
- 'License: ' + self.distribution.get_license(),
- 'Group: ' + self.group,
- 'BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-buildroot',
- 'Prefix: %{_prefix}', ])
+ spec_file.extend(
+ [
+ 'License: ' + (self.distribution.get_license() or "UNKNOWN"),
+ 'Group: ' + self.group,
+ 'BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-buildroot',
+ 'Prefix: %{_prefix}',
+ ]
+ )
if not self.force_arch:
# noarch if no extension modules
if not self.distribution.has_ext_modules():
spec_file.append('BuildArch: noarch')
else:
- spec_file.append( 'BuildArch: %s' % self.force_arch )
-
- for field in ('Vendor',
- 'Packager',
- 'Provides',
- 'Requires',
- 'Conflicts',
- 'Obsoletes',
- ):
+ spec_file.append('BuildArch: %s' % self.force_arch)
+
+ for field in (
+ 'Vendor',
+ 'Packager',
+ 'Provides',
+ 'Requires',
+ 'Conflicts',
+ 'Obsoletes',
+ ):
val = getattr(self, field.lower())
if isinstance(val, list):
spec_file.append('%s: %s' % (field, ' '.join(val)))
elif val is not None:
spec_file.append('%s: %s' % (field, val))
-
- if self.distribution.get_url() != 'UNKNOWN':
+ if self.distribution.get_url():
spec_file.append('Url: ' + self.distribution.get_url())
if self.distribution_name:
spec_file.append('Distribution: ' + self.distribution_name)
if self.build_requires:
- spec_file.append('BuildRequires: ' +
- ' '.join(self.build_requires))
+ spec_file.append('BuildRequires: ' + ' '.join(self.build_requires))
if self.icon:
spec_file.append('Icon: ' + os.path.basename(self.icon))
@@ -480,16 +499,18 @@ class bdist_rpm(Command):
if self.no_autoreq:
spec_file.append('AutoReq: 0')
- spec_file.extend([
- '',
- '%description',
- self.distribution.get_long_description()
- ])
+ spec_file.extend(
+ [
+ '',
+ '%description',
+ self.distribution.get_long_description() or "",
+ ]
+ )
# put locale descriptions into spec file
# XXX again, suppressed because config file syntax doesn't
# easily support this ;-(
- #for locale in self.descriptions.keys():
+ # for locale in self.descriptions.keys():
# spec_file.extend([
# '',
# '%description -l ' + locale,
@@ -498,7 +519,7 @@ class bdist_rpm(Command):
# rpm scripts
# figure out default build script
- def_setup_call = "%s %s" % (self.python,os.path.basename(sys.argv[0]))
+ def_setup_call = "%s %s" % (self.python, os.path.basename(sys.argv[0]))
def_build = "%s build" % def_setup_call
if self.use_rpm_opt_flags:
def_build = 'env CFLAGS="$RPM_OPT_FLAGS" ' + def_build
@@ -509,8 +530,9 @@ class bdist_rpm(Command):
# that we open and interpolate into the spec file, but the defaults
# are just text that we drop in as-is. Hmmm.
- install_cmd = ('%s install -O1 --root=$RPM_BUILD_ROOT '
- '--record=INSTALLED_FILES') % def_setup_call
+ install_cmd = (
+ '%s install -O1 --root=$RPM_BUILD_ROOT ' '--record=INSTALLED_FILES'
+ ) % def_setup_call
script_options = [
('prep', 'prep_script', "%setup -n %{name}-%{unmangled_version}"),
@@ -529,37 +551,43 @@ class bdist_rpm(Command):
# use 'default' as contents of script
val = getattr(self, attr)
if val or default:
- spec_file.extend([
- '',
- '%' + rpm_opt,])
+ spec_file.extend(
+ [
+ '',
+ '%' + rpm_opt,
+ ]
+ )
if val:
with open(val) as f:
spec_file.extend(f.read().split('\n'))
else:
spec_file.append(default)
-
# files section
- spec_file.extend([
- '',
- '%files -f INSTALLED_FILES',
- '%defattr(-,root,root)',
- ])
+ spec_file.extend(
+ [
+ '',
+ '%files -f INSTALLED_FILES',
+ '%defattr(-,root,root)',
+ ]
+ )
if self.doc_files:
spec_file.append('%doc ' + ' '.join(self.doc_files))
if self.changelog:
- spec_file.extend([
- '',
- '%changelog',])
+ spec_file.extend(
+ [
+ '',
+ '%changelog',
+ ]
+ )
spec_file.extend(self.changelog)
return spec_file
def _format_changelog(self, changelog):
- """Format the changelog correctly and convert it to a list of strings
- """
+ """Format the changelog correctly and convert it to a list of strings"""
if not changelog:
return changelog
new_changelog = []
diff --git a/setuptools/_distutils/command/bdist_wininst.py b/setuptools/_distutils/command/bdist_wininst.py
index 0e9ddaa2..76b8a890 100644
--- a/setuptools/_distutils/command/bdist_wininst.py
+++ b/setuptools/_distutils/command/bdist_wininst.py
@@ -13,58 +13,88 @@ from distutils.errors import *
from distutils.sysconfig import get_python_version
from distutils import log
+
class bdist_wininst(Command):
description = "create an executable installer for MS Windows"
- user_options = [('bdist-dir=', None,
- "temporary directory for creating the distribution"),
- ('plat-name=', 'p',
- "platform name to embed in generated filenames "
- "(default: %s)" % get_platform()),
- ('keep-temp', 'k',
- "keep the pseudo-installation tree around after " +
- "creating the distribution archive"),
- ('target-version=', None,
- "require a specific python version" +
- " on the target system"),
- ('no-target-compile', 'c',
- "do not compile .py to .pyc on the target system"),
- ('no-target-optimize', 'o',
- "do not compile .py to .pyo (optimized) "
- "on the target system"),
- ('dist-dir=', 'd',
- "directory to put final built distributions in"),
- ('bitmap=', 'b',
- "bitmap to use for the installer instead of python-powered logo"),
- ('title=', 't',
- "title to display on the installer background instead of default"),
- ('skip-build', None,
- "skip rebuilding everything (for testing/debugging)"),
- ('install-script=', None,
- "basename of installation script to be run after "
- "installation or before deinstallation"),
- ('pre-install-script=', None,
- "Fully qualified filename of a script to be run before "
- "any files are installed. This script need not be in the "
- "distribution"),
- ('user-access-control=', None,
- "specify Vista's UAC handling - 'none'/default=no "
- "handling, 'auto'=use UAC if target Python installed for "
- "all users, 'force'=always use UAC"),
- ]
-
- boolean_options = ['keep-temp', 'no-target-compile', 'no-target-optimize',
- 'skip-build']
+ user_options = [
+ ('bdist-dir=', None, "temporary directory for creating the distribution"),
+ (
+ 'plat-name=',
+ 'p',
+ "platform name to embed in generated filenames "
+ "(default: %s)" % get_platform(),
+ ),
+ (
+ 'keep-temp',
+ 'k',
+ "keep the pseudo-installation tree around after "
+ + "creating the distribution archive",
+ ),
+ (
+ 'target-version=',
+ None,
+ "require a specific python version" + " on the target system",
+ ),
+ ('no-target-compile', 'c', "do not compile .py to .pyc on the target system"),
+ (
+ 'no-target-optimize',
+ 'o',
+ "do not compile .py to .pyo (optimized) " "on the target system",
+ ),
+ ('dist-dir=', 'd', "directory to put final built distributions in"),
+ (
+ 'bitmap=',
+ 'b',
+ "bitmap to use for the installer instead of python-powered logo",
+ ),
+ (
+ 'title=',
+ 't',
+ "title to display on the installer background instead of default",
+ ),
+ ('skip-build', None, "skip rebuilding everything (for testing/debugging)"),
+ (
+ 'install-script=',
+ None,
+ "basename of installation script to be run after "
+ "installation or before deinstallation",
+ ),
+ (
+ 'pre-install-script=',
+ None,
+ "Fully qualified filename of a script to be run before "
+ "any files are installed. This script need not be in the "
+ "distribution",
+ ),
+ (
+ 'user-access-control=',
+ None,
+ "specify Vista's UAC handling - 'none'/default=no "
+ "handling, 'auto'=use UAC if target Python installed for "
+ "all users, 'force'=always use UAC",
+ ),
+ ]
+
+ boolean_options = [
+ 'keep-temp',
+ 'no-target-compile',
+ 'no-target-optimize',
+ 'skip-build',
+ ]
# bpo-10945: bdist_wininst requires mbcs encoding only available on Windows
- _unsupported = (sys.platform != "win32")
+ _unsupported = sys.platform != "win32"
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
- warnings.warn("bdist_wininst command is deprecated since Python 3.8, "
- "use bdist_wheel (wheel packages) instead",
- DeprecationWarning, 2)
+ warnings.warn(
+ "bdist_wininst command is deprecated since Python 3.8, "
+ "use bdist_wheel (wheel packages) instead",
+ DeprecationWarning,
+ 2,
+ )
def initialize_options(self):
self.bdist_dir = None
@@ -81,7 +111,6 @@ class bdist_wininst(Command):
self.pre_install_script = None
self.user_access_control = None
-
def finalize_options(self):
self.set_undefined_options('bdist', ('skip_build', 'skip_build'))
@@ -102,14 +131,16 @@ class bdist_wininst(Command):
short_version = get_python_version()
if self.target_version and self.target_version != short_version:
raise DistutilsOptionError(
- "target version can only be %s, or the '--skip-build'" \
- " option must be specified" % (short_version,))
+ "target version can only be %s, or the '--skip-build'"
+ " option must be specified" % (short_version,)
+ )
self.target_version = short_version
- self.set_undefined_options('bdist',
- ('dist_dir', 'dist_dir'),
- ('plat_name', 'plat_name'),
- )
+ self.set_undefined_options(
+ 'bdist',
+ ('dist_dir', 'dist_dir'),
+ ('plat_name', 'plat_name'),
+ )
if self.install_script:
for script in self.distribution.scripts:
@@ -117,16 +148,17 @@ class bdist_wininst(Command):
break
else:
raise DistutilsOptionError(
- "install_script '%s' not found in scripts"
- % self.install_script)
+ "install_script '%s' not found in scripts" % self.install_script
+ )
def run(self):
- if (sys.platform != "win32" and
- (self.distribution.has_ext_modules() or
- self.distribution.has_c_libraries())):
- raise DistutilsPlatformError \
- ("distribution contains extensions and/or C libraries; "
- "must be compiled on a Windows 32 platform")
+ if sys.platform != "win32" and (
+ self.distribution.has_ext_modules() or self.distribution.has_c_libraries()
+ ):
+ raise DistutilsPlatformError(
+ "distribution contains extensions and/or C libraries; "
+ "must be compiled on a Windows 32 platform"
+ )
if not self.skip_build:
self.run_command('build')
@@ -155,8 +187,7 @@ class bdist_wininst(Command):
target_version = '%d.%d' % sys.version_info[:2]
plat_specifier = ".%s-%s" % (self.plat_name, target_version)
build = self.get_finalized_command('build')
- build.build_lib = os.path.join(build.build_base,
- 'lib' + plat_specifier)
+ build.build_lib = os.path.join(build.build_base, 'lib' + plat_specifier)
# Use a custom scheme for the zip-file, because we have to decide
# at installation time which scheme to use.
@@ -164,9 +195,7 @@ class bdist_wininst(Command):
value = key.upper()
if key == 'headers':
value = value + '/Include/$dist_name'
- setattr(install,
- 'install_' + key,
- value)
+ setattr(install, 'install_' + key, value)
log.info("installing to %s", self.bdist_dir)
install.ensure_finalized()
@@ -182,18 +211,19 @@ class bdist_wininst(Command):
# And make an archive relative to the root of the
# pseudo-installation tree.
from tempfile import mktemp
+
archive_basename = mktemp()
fullname = self.distribution.get_fullname()
- arcname = self.make_archive(archive_basename, "zip",
- root_dir=self.bdist_dir)
+ arcname = self.make_archive(archive_basename, "zip", root_dir=self.bdist_dir)
# create an exe containing the zip-file
self.create_exe(arcname, fullname, self.bitmap)
if self.distribution.has_ext_modules():
pyversion = get_python_version()
else:
pyversion = 'any'
- self.distribution.dist_files.append(('bdist_wininst', pyversion,
- self.get_installer_filename(fullname)))
+ self.distribution.dist_files.append(
+ ('bdist_wininst', pyversion, self.get_installer_filename(fullname))
+ )
# remove the zip-file again
log.debug("removing temporary file '%s'", arcname)
os.remove(arcname)
@@ -217,12 +247,19 @@ class bdist_wininst(Command):
def escape(s):
return s.replace("\n", "\\n")
- for name in ["author", "author_email", "description", "maintainer",
- "maintainer_email", "name", "url", "version"]:
+ for name in [
+ "author",
+ "author_email",
+ "description",
+ "maintainer",
+ "maintainer_email",
+ "name",
+ "url",
+ "version",
+ ]:
data = getattr(metadata, name, "")
if data:
- info = info + ("\n %s: %s" % \
- (name.capitalize(), escape(data)))
+ info = info + ("\n %s: %s" % (name.capitalize(), escape(data)))
lines.append("%s=%s" % (name, escape(data)))
# The [setup] section contains entries controlling
@@ -242,8 +279,11 @@ class bdist_wininst(Command):
lines.append("title=%s" % escape(title))
import time
import distutils
- build_info = "Built %s with distutils-%s" % \
- (time.ctime(time.time()), distutils.__version__)
+
+ build_info = "Built %s with distutils-%s" % (
+ time.ctime(time.time()),
+ distutils.__version__,
+ )
lines.append("build_info=%s" % build_info)
return "\n".join(lines)
@@ -279,8 +319,7 @@ class bdist_wininst(Command):
# We need to normalize newlines, so we open in text mode and
# convert back to bytes. "latin-1" simply avoids any possible
# failures.
- with open(self.pre_install_script, "r",
- encoding="latin-1") as script:
+ with open(self.pre_install_script, "r", encoding="latin-1") as script:
script_data = script.read().encode("latin-1")
cfgdata = cfgdata + script_data + b"\n\0"
else:
@@ -293,11 +332,12 @@ class bdist_wininst(Command):
# expects. If the layout changes, increment that number, make
# the corresponding changes to the wininst.exe sources, and
# recompile them.
- header = struct.pack("<iii",
- 0x1234567B, # tag
- len(cfgdata), # length
- bitmaplen, # number of bytes in bitmap
- )
+ header = struct.pack(
+ "<iii",
+ 0x1234567B, # tag
+ len(cfgdata), # length
+ bitmaplen, # number of bytes in bitmap
+ )
file.write(header)
with open(arcname, "rb") as f:
file.write(f.read())
@@ -307,12 +347,14 @@ class bdist_wininst(Command):
if self.target_version:
# if we create an installer for a specific python version,
# it's better to include this in the name
- installer_name = os.path.join(self.dist_dir,
- "%s.%s-py%s.exe" %
- (fullname, self.plat_name, self.target_version))
+ installer_name = os.path.join(
+ self.dist_dir,
+ "%s.%s-py%s.exe" % (fullname, self.plat_name, self.target_version),
+ )
else:
- installer_name = os.path.join(self.dist_dir,
- "%s.%s.exe" % (fullname, self.plat_name))
+ installer_name = os.path.join(
+ self.dist_dir, "%s.%s.exe" % (fullname, self.plat_name)
+ )
return installer_name
def get_exe_bytes(self):
@@ -355,7 +397,6 @@ class bdist_wininst(Command):
major = CRT_ASSEMBLY_VERSION.partition('.')[0]
bv = major + '.0'
-
# wininst-x.y.exe is in the same directory as this file
directory = os.path.dirname(__file__)
# we must use a wininst-x.y.exe built with the same C compiler
diff --git a/setuptools/_distutils/command/build.py b/setuptools/_distutils/command/build.py
index 9606b81a..3aa7fac7 100644
--- a/setuptools/_distutils/command/build.py
+++ b/setuptools/_distutils/command/build.py
@@ -10,6 +10,7 @@ from distutils.util import get_platform
def show_compilers():
from distutils.ccompiler import show_compilers
+
show_compilers()
@@ -18,40 +19,35 @@ class build(Command):
description = "build everything needed to install"
user_options = [
- ('build-base=', 'b',
- "base directory for build library"),
- ('build-purelib=', None,
- "build directory for platform-neutral distributions"),
- ('build-platlib=', None,
- "build directory for platform-specific distributions"),
- ('build-lib=', None,
- "build directory for all distribution (defaults to either " +
- "build-purelib or build-platlib"),
- ('build-scripts=', None,
- "build directory for scripts"),
- ('build-temp=', 't',
- "temporary build directory"),
- ('plat-name=', 'p',
- "platform name to build for, if supported "
- "(default: %s)" % get_platform()),
- ('compiler=', 'c',
- "specify the compiler type"),
- ('parallel=', 'j',
- "number of parallel build jobs"),
- ('debug', 'g',
- "compile extensions and libraries with debugging information"),
- ('force', 'f',
- "forcibly build everything (ignore file timestamps)"),
- ('executable=', 'e',
- "specify final destination interpreter path (build.py)"),
- ]
+ ('build-base=', 'b', "base directory for build library"),
+ ('build-purelib=', None, "build directory for platform-neutral distributions"),
+ ('build-platlib=', None, "build directory for platform-specific distributions"),
+ (
+ 'build-lib=',
+ None,
+ "build directory for all distribution (defaults to either "
+ + "build-purelib or build-platlib",
+ ),
+ ('build-scripts=', None, "build directory for scripts"),
+ ('build-temp=', 't', "temporary build directory"),
+ (
+ 'plat-name=',
+ 'p',
+ "platform name to build for, if supported "
+ "(default: %s)" % get_platform(),
+ ),
+ ('compiler=', 'c', "specify the compiler type"),
+ ('parallel=', 'j', "number of parallel build jobs"),
+ ('debug', 'g', "compile extensions and libraries with debugging information"),
+ ('force', 'f', "forcibly build everything (ignore file timestamps)"),
+ ('executable=', 'e', "specify final destination interpreter path (build.py)"),
+ ]
boolean_options = ['debug', 'force']
help_options = [
- ('help-compiler', None,
- "list available compilers", show_compilers),
- ]
+ ('help-compiler', None, "list available compilers", show_compilers),
+ ]
def initialize_options(self):
self.build_base = 'build'
@@ -78,11 +74,11 @@ class build(Command):
# other platforms.
if os.name != 'nt':
raise DistutilsOptionError(
- "--plat-name only supported on Windows (try "
- "using './configure --help' on your platform)")
+ "--plat-name only supported on Windows (try "
+ "using './configure --help' on your platform)"
+ )
- plat_specifier = ".%s-%s" % (self.plat_name,
- sys.implementation.cache_tag)
+ plat_specifier = ".%s-%s" % (self.plat_name, sys.implementation.cache_tag)
# Make it so Python 2.x and Python 2.x with --with-pydebug don't
# share the same build directories. Doing so confuses the build
@@ -96,8 +92,7 @@ class build(Command):
if self.build_purelib is None:
self.build_purelib = os.path.join(self.build_base, 'lib')
if self.build_platlib is None:
- self.build_platlib = os.path.join(self.build_base,
- 'lib' + plat_specifier)
+ self.build_platlib = os.path.join(self.build_base, 'lib' + plat_specifier)
# 'build_lib' is the actual directory that we will use for this
# particular module distribution -- if user didn't supply it, pick
@@ -111,11 +106,11 @@ class build(Command):
# 'build_temp' -- temporary directory for compiler turds,
# "build/temp.<plat>"
if self.build_temp is None:
- self.build_temp = os.path.join(self.build_base,
- 'temp' + plat_specifier)
+ self.build_temp = os.path.join(self.build_base, 'temp' + plat_specifier)
if self.build_scripts is None:
- self.build_scripts = os.path.join(self.build_base,
- 'scripts-%d.%d' % sys.version_info[:2])
+ self.build_scripts = os.path.join(
+ self.build_base, 'scripts-%d.%d' % sys.version_info[:2]
+ )
if self.executable is None and sys.executable:
self.executable = os.path.normpath(sys.executable)
@@ -135,7 +130,6 @@ class build(Command):
for cmd_name in self.get_sub_commands():
self.run_command(cmd_name)
-
# -- Predicates for the sub-command list ---------------------------
def has_pure_modules(self):
@@ -150,9 +144,9 @@ class build(Command):
def has_scripts(self):
return self.distribution.has_scripts()
-
- sub_commands = [('build_py', has_pure_modules),
- ('build_clib', has_c_libraries),
- ('build_ext', has_ext_modules),
- ('build_scripts', has_scripts),
- ]
+ sub_commands = [
+ ('build_py', has_pure_modules),
+ ('build_clib', has_c_libraries),
+ ('build_ext', has_ext_modules),
+ ('build_scripts', has_scripts),
+ ]
diff --git a/setuptools/_distutils/command/build_clib.py b/setuptools/_distutils/command/build_clib.py
index 3e20ef23..003499fa 100644
--- a/setuptools/_distutils/command/build_clib.py
+++ b/setuptools/_distutils/command/build_clib.py
@@ -20,8 +20,10 @@ from distutils.errors import *
from distutils.sysconfig import customize_compiler
from distutils import log
+
def show_compilers():
from distutils.ccompiler import show_compilers
+
show_compilers()
@@ -30,24 +32,18 @@ class build_clib(Command):
description = "build C/C++ libraries used by Python extensions"
user_options = [
- ('build-clib=', 'b',
- "directory to build C/C++ libraries to"),
- ('build-temp=', 't',
- "directory to put temporary build by-products"),
- ('debug', 'g',
- "compile with debugging information"),
- ('force', 'f',
- "forcibly build everything (ignore file timestamps)"),
- ('compiler=', 'c',
- "specify the compiler type"),
- ]
+ ('build-clib=', 'b', "directory to build C/C++ libraries to"),
+ ('build-temp=', 't', "directory to put temporary build by-products"),
+ ('debug', 'g', "compile with debugging information"),
+ ('force', 'f', "forcibly build everything (ignore file timestamps)"),
+ ('compiler=', 'c', "specify the compiler type"),
+ ]
boolean_options = ['debug', 'force']
help_options = [
- ('help-compiler', None,
- "list available compilers", show_compilers),
- ]
+ ('help-compiler', None, "list available compilers", show_compilers),
+ ]
def initialize_options(self):
self.build_clib = None
@@ -64,19 +60,20 @@ class build_clib(Command):
self.force = 0
self.compiler = None
-
def finalize_options(self):
# This might be confusing: both build-clib and build-temp default
# to build-temp as defined by the "build" command. This is because
# I think that C libraries are really just temporary build
# by-products, at least from the point of view of building Python
# extensions -- but I want to keep my options open.
- self.set_undefined_options('build',
- ('build_temp', 'build_clib'),
- ('build_temp', 'build_temp'),
- ('compiler', 'compiler'),
- ('debug', 'debug'),
- ('force', 'force'))
+ self.set_undefined_options(
+ 'build',
+ ('build_temp', 'build_clib'),
+ ('build_temp', 'build_temp'),
+ ('compiler', 'compiler'),
+ ('debug', 'debug'),
+ ('force', 'force'),
+ )
self.libraries = self.distribution.libraries
if self.libraries:
@@ -90,23 +87,23 @@ class build_clib(Command):
# XXX same as for build_ext -- what about 'self.define' and
# 'self.undef' ?
-
def run(self):
if not self.libraries:
return
# Yech -- this is cut 'n pasted from build_ext.py!
from distutils.ccompiler import new_compiler
- self.compiler = new_compiler(compiler=self.compiler,
- dry_run=self.dry_run,
- force=self.force)
+
+ self.compiler = new_compiler(
+ compiler=self.compiler, dry_run=self.dry_run, force=self.force
+ )
customize_compiler(self.compiler)
if self.include_dirs is not None:
self.compiler.set_include_dirs(self.include_dirs)
if self.define is not None:
# 'define' option is a list of (name,value) tuples
- for (name,value) in self.define:
+ for (name, value) in self.define:
self.compiler.define_macro(name, value)
if self.undef is not None:
for macro in self.undef:
@@ -114,7 +111,6 @@ class build_clib(Command):
self.build_libraries(self.libraries)
-
def check_library_list(self, libraries):
"""Ensure that the list of libraries is valid.
@@ -126,30 +122,31 @@ class build_clib(Command):
just returns otherwise.
"""
if not isinstance(libraries, list):
- raise DistutilsSetupError(
- "'libraries' option must be a list of tuples")
+ raise DistutilsSetupError("'libraries' option must be a list of tuples")
for lib in libraries:
if not isinstance(lib, tuple) and len(lib) != 2:
- raise DistutilsSetupError(
- "each element of 'libraries' must a 2-tuple")
+ raise DistutilsSetupError("each element of 'libraries' must a 2-tuple")
name, build_info = lib
if not isinstance(name, str):
raise DistutilsSetupError(
- "first element of each tuple in 'libraries' "
- "must be a string (the library name)")
+ "first element of each tuple in 'libraries' "
+ "must be a string (the library name)"
+ )
if '/' in name or (os.sep != '/' and os.sep in name):
- raise DistutilsSetupError("bad library name '%s': "
- "may not contain directory separators" % lib[0])
+ raise DistutilsSetupError(
+ "bad library name '%s': "
+ "may not contain directory separators" % lib[0]
+ )
if not isinstance(build_info, dict):
raise DistutilsSetupError(
- "second element of each tuple in 'libraries' "
- "must be a dictionary (build info)")
-
+ "second element of each tuple in 'libraries' "
+ "must be a dictionary (build info)"
+ )
def get_library_names(self):
# Assume the library list is valid -- 'check_library_list()' is
@@ -162,7 +159,6 @@ class build_clib(Command):
lib_names.append(lib_name)
return lib_names
-
def get_source_files(self):
self.check_library_list(self.libraries)
filenames = []
@@ -170,22 +166,23 @@ class build_clib(Command):
sources = build_info.get('sources')
if sources is None or not isinstance(sources, (list, tuple)):
raise DistutilsSetupError(
- "in 'libraries' option (library '%s'), "
- "'sources' must be present and must be "
- "a list of source filenames" % lib_name)
+ "in 'libraries' option (library '%s'), "
+ "'sources' must be present and must be "
+ "a list of source filenames" % lib_name
+ )
filenames.extend(sources)
return filenames
-
def build_libraries(self, libraries):
for (lib_name, build_info) in libraries:
sources = build_info.get('sources')
if sources is None or not isinstance(sources, (list, tuple)):
raise DistutilsSetupError(
- "in 'libraries' option (library '%s'), "
- "'sources' must be present and must be "
- "a list of source filenames" % lib_name)
+ "in 'libraries' option (library '%s'), "
+ "'sources' must be present and must be "
+ "a list of source filenames" % lib_name
+ )
sources = list(sources)
log.info("building '%s' library", lib_name)
@@ -195,15 +192,17 @@ class build_clib(Command):
# files in a temporary build directory.)
macros = build_info.get('macros')
include_dirs = build_info.get('include_dirs')
- objects = self.compiler.compile(sources,
- output_dir=self.build_temp,
- macros=macros,
- include_dirs=include_dirs,
- debug=self.debug)
+ objects = self.compiler.compile(
+ sources,
+ output_dir=self.build_temp,
+ macros=macros,
+ include_dirs=include_dirs,
+ debug=self.debug,
+ )
# Now "link" the object files together into a static library.
# (On Unix at least, this isn't really linking -- it just
# builds an archive. Whatever.)
- self.compiler.create_static_lib(objects, lib_name,
- output_dir=self.build_clib,
- debug=self.debug)
+ self.compiler.create_static_lib(
+ objects, lib_name, output_dir=self.build_clib, debug=self.debug
+ )
diff --git a/setuptools/_distutils/command/build_ext.py b/setuptools/_distutils/command/build_ext.py
index 181671bf..1a6dd394 100644
--- a/setuptools/_distutils/command/build_ext.py
+++ b/setuptools/_distutils/command/build_ext.py
@@ -22,12 +22,12 @@ from site import USER_BASE
# An extension name is just a dot-separated list of Python NAMEs (ie.
# the same as a fully-qualified module name).
-extension_name_re = re.compile \
- (r'^[a-zA-Z_][a-zA-Z_0-9]*(\.[a-zA-Z_][a-zA-Z_0-9]*)*$')
+extension_name_re = re.compile(r'^[a-zA-Z_][a-zA-Z_0-9]*(\.[a-zA-Z_][a-zA-Z_0-9]*)*$')
-def show_compilers ():
+def show_compilers():
from distutils.ccompiler import show_compilers
+
show_compilers()
@@ -55,54 +55,50 @@ class build_ext(Command):
sep_by = " (separated by '%s')" % os.pathsep
user_options = [
- ('build-lib=', 'b',
- "directory for compiled extension modules"),
- ('build-temp=', 't',
- "directory for temporary files (build by-products)"),
- ('plat-name=', 'p',
- "platform name to cross-compile for, if supported "
- "(default: %s)" % get_platform()),
- ('inplace', 'i',
- "ignore build-lib and put compiled extensions into the source " +
- "directory alongside your pure Python modules"),
- ('include-dirs=', 'I',
- "list of directories to search for header files" + sep_by),
- ('define=', 'D',
- "C preprocessor macros to define"),
- ('undef=', 'U',
- "C preprocessor macros to undefine"),
- ('libraries=', 'l',
- "external C libraries to link with"),
- ('library-dirs=', 'L',
- "directories to search for external C libraries" + sep_by),
- ('rpath=', 'R',
- "directories to search for shared C libraries at runtime"),
- ('link-objects=', 'O',
- "extra explicit link objects to include in the link"),
- ('debug', 'g',
- "compile/link with debugging information"),
- ('force', 'f',
- "forcibly build everything (ignore file timestamps)"),
- ('compiler=', 'c',
- "specify the compiler type"),
- ('parallel=', 'j',
- "number of parallel build jobs"),
- ('swig-cpp', None,
- "make SWIG create C++ files (default is C)"),
- ('swig-opts=', None,
- "list of SWIG command line options"),
- ('swig=', None,
- "path to the SWIG executable"),
- ('user', None,
- "add user include, library and rpath")
- ]
+ ('build-lib=', 'b', "directory for compiled extension modules"),
+ ('build-temp=', 't', "directory for temporary files (build by-products)"),
+ (
+ 'plat-name=',
+ 'p',
+ "platform name to cross-compile for, if supported "
+ "(default: %s)" % get_platform(),
+ ),
+ (
+ 'inplace',
+ 'i',
+ "ignore build-lib and put compiled extensions into the source "
+ + "directory alongside your pure Python modules",
+ ),
+ (
+ 'include-dirs=',
+ 'I',
+ "list of directories to search for header files" + sep_by,
+ ),
+ ('define=', 'D', "C preprocessor macros to define"),
+ ('undef=', 'U', "C preprocessor macros to undefine"),
+ ('libraries=', 'l', "external C libraries to link with"),
+ (
+ 'library-dirs=',
+ 'L',
+ "directories to search for external C libraries" + sep_by,
+ ),
+ ('rpath=', 'R', "directories to search for shared C libraries at runtime"),
+ ('link-objects=', 'O', "extra explicit link objects to include in the link"),
+ ('debug', 'g', "compile/link with debugging information"),
+ ('force', 'f', "forcibly build everything (ignore file timestamps)"),
+ ('compiler=', 'c', "specify the compiler type"),
+ ('parallel=', 'j', "number of parallel build jobs"),
+ ('swig-cpp', None, "make SWIG create C++ files (default is C)"),
+ ('swig-opts=', None, "list of SWIG command line options"),
+ ('swig=', None, "path to the SWIG executable"),
+ ('user', None, "add user include, library and rpath"),
+ ]
boolean_options = ['inplace', 'debug', 'force', 'swig-cpp', 'user']
help_options = [
- ('help-compiler', None,
- "list available compilers", show_compilers),
- ]
+ ('help-compiler', None, "list available compilers", show_compilers),
+ ]
def initialize_options(self):
self.extensions = None
@@ -131,15 +127,16 @@ class build_ext(Command):
def finalize_options(self):
from distutils import sysconfig
- self.set_undefined_options('build',
- ('build_lib', 'build_lib'),
- ('build_temp', 'build_temp'),
- ('compiler', 'compiler'),
- ('debug', 'debug'),
- ('force', 'force'),
- ('parallel', 'parallel'),
- ('plat_name', 'plat_name'),
- )
+ self.set_undefined_options(
+ 'build',
+ ('build_lib', 'build_lib'),
+ ('build_temp', 'build_temp'),
+ ('compiler', 'compiler'),
+ ('debug', 'debug'),
+ ('force', 'force'),
+ ('parallel', 'parallel'),
+ ('plat_name', 'plat_name'),
+ )
if self.package is None:
self.package = self.distribution.ext_package
@@ -164,8 +161,7 @@ class build_ext(Command):
# any local include dirs take precedence.
self.include_dirs.extend(py_include.split(os.path.pathsep))
if plat_py_include != py_include:
- self.include_dirs.extend(
- plat_py_include.split(os.path.pathsep))
+ self.include_dirs.extend(plat_py_include.split(os.path.pathsep))
self.ensure_string_list('libraries')
self.ensure_string_list('link_objects')
@@ -220,9 +216,11 @@ class build_ext(Command):
if sys.platform[:6] == 'cygwin':
if not sysconfig.python_build:
# building third party extensions
- self.library_dirs.append(os.path.join(sys.prefix, "lib",
- "python" + get_python_version(),
- "config"))
+ self.library_dirs.append(
+ os.path.join(
+ sys.prefix, "lib", "python" + get_python_version(), "config"
+ )
+ )
else:
# building python standard extensions
self.library_dirs.append('.')
@@ -230,7 +228,7 @@ class build_ext(Command):
# For building extensions with a shared Python library,
# Python's library directory must be appended to library_dirs
# See Issues: #1600860, #4366
- if (sysconfig.get_config_var('Py_ENABLE_SHARED')):
+ if sysconfig.get_config_var('Py_ENABLE_SHARED'):
if not sysconfig.python_build:
# building third party extensions
self.library_dirs.append(sysconfig.get_config_var('LIBDIR'))
@@ -302,10 +300,12 @@ class build_ext(Command):
# Setup the CCompiler object that we'll use to do all the
# compiling and linking
- self.compiler = new_compiler(compiler=self.compiler,
- verbose=self.verbose,
- dry_run=self.dry_run,
- force=self.force)
+ self.compiler = new_compiler(
+ compiler=self.compiler,
+ verbose=self.verbose,
+ dry_run=self.dry_run,
+ force=self.force,
+ )
customize_compiler(self.compiler)
# If we are cross-compiling, init the compiler now (if we are not
# cross-compiling, init would not hurt, but people may rely on
@@ -350,34 +350,40 @@ class build_ext(Command):
"""
if not isinstance(extensions, list):
raise DistutilsSetupError(
- "'ext_modules' option must be a list of Extension instances")
+ "'ext_modules' option must be a list of Extension instances"
+ )
for i, ext in enumerate(extensions):
if isinstance(ext, Extension):
- continue # OK! (assume type-checking done
- # by Extension constructor)
+ continue # OK! (assume type-checking done
+ # by Extension constructor)
if not isinstance(ext, tuple) or len(ext) != 2:
raise DistutilsSetupError(
- "each element of 'ext_modules' option must be an "
- "Extension instance or 2-tuple")
+ "each element of 'ext_modules' option must be an "
+ "Extension instance or 2-tuple"
+ )
ext_name, build_info = ext
- log.warn("old-style (ext_name, build_info) tuple found in "
- "ext_modules for extension '%s' "
- "-- please convert to Extension instance", ext_name)
+ log.warn(
+ "old-style (ext_name, build_info) tuple found in "
+ "ext_modules for extension '%s' "
+ "-- please convert to Extension instance",
+ ext_name,
+ )
- if not (isinstance(ext_name, str) and
- extension_name_re.match(ext_name)):
+ if not (isinstance(ext_name, str) and extension_name_re.match(ext_name)):
raise DistutilsSetupError(
- "first element of each tuple in 'ext_modules' "
- "must be the extension name (a string)")
+ "first element of each tuple in 'ext_modules' "
+ "must be the extension name (a string)"
+ )
if not isinstance(build_info, dict):
raise DistutilsSetupError(
- "second element of each tuple in 'ext_modules' "
- "must be a dictionary (build info)")
+ "second element of each tuple in 'ext_modules' "
+ "must be a dictionary (build info)"
+ )
# OK, the (ext_name, build_info) dict is type-safe: convert it
# to an Extension instance.
@@ -385,9 +391,14 @@ class build_ext(Command):
# Easy stuff: one-to-one mapping from dict elements to
# instance attributes.
- for key in ('include_dirs', 'library_dirs', 'libraries',
- 'extra_objects', 'extra_compile_args',
- 'extra_link_args'):
+ for key in (
+ 'include_dirs',
+ 'library_dirs',
+ 'libraries',
+ 'extra_objects',
+ 'extra_compile_args',
+ 'extra_link_args',
+ ):
val = build_info.get(key)
if val is not None:
setattr(ext, key, val)
@@ -395,8 +406,7 @@ class build_ext(Command):
# Medium-easy stuff: same syntax/semantics, different names.
ext.runtime_library_dirs = build_info.get('rpath')
if 'def_file' in build_info:
- log.warn("'def_file' element of build info dict "
- "no longer supported")
+ log.warn("'def_file' element of build info dict " "no longer supported")
# Non-trivial stuff: 'macros' split into 'define_macros'
# and 'undef_macros'.
@@ -407,8 +417,9 @@ class build_ext(Command):
for macro in macros:
if not (isinstance(macro, tuple) and len(macro) in (1, 2)):
raise DistutilsSetupError(
- "'macros' element of build info dict "
- "must be 1- or 2-tuple")
+ "'macros' element of build info dict "
+ "must be 1- or 2-tuple"
+ )
if len(macro) == 1:
ext.undef_macros.append(macro[0])
elif len(macro) == 2:
@@ -461,8 +472,9 @@ class build_ext(Command):
return
with ThreadPoolExecutor(max_workers=workers) as executor:
- futures = [executor.submit(self.build_extension, ext)
- for ext in self.extensions]
+ futures = [
+ executor.submit(self.build_extension, ext) for ext in self.extensions
+ ]
for ext, fut in zip(self.extensions, futures):
with self._filter_build_errors(ext):
fut.result()
@@ -479,16 +491,16 @@ class build_ext(Command):
except (CCompilerError, DistutilsError, CompileError) as e:
if not ext.optional:
raise
- self.warn('building extension "%s" failed: %s' %
- (ext.name, e))
+ self.warn('building extension "%s" failed: %s' % (ext.name, e))
def build_extension(self, ext):
sources = ext.sources
if sources is None or not isinstance(sources, (list, tuple)):
raise DistutilsSetupError(
- "in 'ext_modules' option (extension '%s'), "
- "'sources' must be present and must be "
- "a list of source filenames" % ext.name)
+ "in 'ext_modules' option (extension '%s'), "
+ "'sources' must be present and must be "
+ "a list of source filenames" % ext.name
+ )
# sort to make the resulting .so file build reproducible
sources = sorted(sources)
@@ -525,13 +537,15 @@ class build_ext(Command):
for undef in ext.undef_macros:
macros.append((undef,))
- objects = self.compiler.compile(sources,
- output_dir=self.build_temp,
- macros=macros,
- include_dirs=ext.include_dirs,
- debug=self.debug,
- extra_postargs=extra_args,
- depends=ext.depends)
+ objects = self.compiler.compile(
+ sources,
+ output_dir=self.build_temp,
+ macros=macros,
+ include_dirs=ext.include_dirs,
+ debug=self.debug,
+ extra_postargs=extra_args,
+ depends=ext.depends,
+ )
# XXX outdated variable, kept here in case third-part code
# needs it.
@@ -548,7 +562,8 @@ class build_ext(Command):
language = ext.language or self.compiler.detect_language(sources)
self.compiler.link_shared_object(
- objects, ext_path,
+ objects,
+ ext_path,
libraries=self.get_libraries(ext),
library_dirs=ext.library_dirs,
runtime_library_dirs=ext.runtime_library_dirs,
@@ -556,7 +571,8 @@ class build_ext(Command):
export_symbols=self.get_export_symbols(ext),
debug=self.debug,
build_temp=self.build_temp,
- target_lang=language)
+ target_lang=language,
+ )
def swig_sources(self, sources, extension):
"""Walk the list of source files in 'sources', looking for SWIG
@@ -576,15 +592,18 @@ class build_ext(Command):
if self.swig_cpp:
log.warn("--swig-cpp is deprecated - use --swig-opts=-c++")
- if self.swig_cpp or ('-c++' in self.swig_opts) or \
- ('-c++' in extension.swig_opts):
+ if (
+ self.swig_cpp
+ or ('-c++' in self.swig_opts)
+ or ('-c++' in extension.swig_opts)
+ ):
target_ext = '.cpp'
else:
target_ext = '.c'
for source in sources:
(base, ext) = os.path.splitext(source)
- if ext == ".i": # SWIG interface file
+ if ext == ".i": # SWIG interface file
new_sources.append(base + '_wrap' + target_ext)
swig_sources.append(source)
swig_targets[source] = new_sources[-1]
@@ -631,8 +650,9 @@ class build_ext(Command):
return "swig.exe"
else:
raise DistutilsPlatformError(
- "I don't know how to find (much less run) SWIG "
- "on platform '%s'" % os.name)
+ "I don't know how to find (much less run) SWIG "
+ "on platform '%s'" % os.name
+ )
# -- Name generators -----------------------------------------------
# (extension names, filenames, whatever)
@@ -650,7 +670,7 @@ class build_ext(Command):
# no further work needed
# returning :
# build_dir/package/path/filename
- filename = os.path.join(*modpath[:-1]+[filename])
+ filename = os.path.join(*modpath[:-1] + [filename])
return os.path.join(self.build_lib, filename)
# the inplace option requires to find the package directory
@@ -678,6 +698,7 @@ class build_ext(Command):
"foo\bar.pyd").
"""
from distutils.sysconfig import get_config_var
+
ext_path = ext_name.split('.')
ext_suffix = get_config_var('EXT_SUFFIX')
return os.path.join(*ext_path) + ext_suffix
@@ -715,12 +736,15 @@ class build_ext(Command):
# Append '_d' to the python import library on debug builds.
if sys.platform == "win32":
from distutils._msvccompiler import MSVCCompiler
+
if not isinstance(self.compiler, MSVCCompiler):
template = "python%d%d"
if self.debug:
template = template + '_d'
- pythonlib = (template %
- (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
+ pythonlib = template % (
+ sys.hexversion >> 24,
+ (sys.hexversion >> 16) & 0xFF,
+ )
# don't extend ext.libraries, it may be shared with other
# extensions, it is a reference to the original list
return ext.libraries + [pythonlib]
@@ -734,6 +758,7 @@ class build_ext(Command):
# Windows like MinGW) it is simply necessary that all symbols in
# shared libraries are resolved at link time.
from distutils.sysconfig import get_config_var
+
link_libpython = False
if get_config_var('Py_ENABLE_SHARED'):
# A native build on an Android device or on Cygwin
diff --git a/setuptools/_distutils/command/build_py.py b/setuptools/_distutils/command/build_py.py
index 7ef9bcef..1b22004e 100644
--- a/setuptools/_distutils/command/build_py.py
+++ b/setuptools/_distutils/command/build_py.py
@@ -12,7 +12,8 @@ from distutils.errors import *
from distutils.util import convert_path
from distutils import log
-class build_py (Command):
+
+class build_py(Command):
description = "\"build\" pure Python modules (copy to build directory)"
@@ -20,14 +21,17 @@ class build_py (Command):
('build-lib=', 'd', "directory to \"build\" (copy) to"),
('compile', 'c', "compile .py to .pyc"),
('no-compile', None, "don't compile .py files [default]"),
- ('optimize=', 'O',
- "also compile with optimization: -O1 for \"python -O\", "
- "-O2 for \"python -OO\", and -O0 to disable [default: -O0]"),
+ (
+ 'optimize=',
+ 'O',
+ "also compile with optimization: -O1 for \"python -O\", "
+ "-O2 for \"python -OO\", and -O0 to disable [default: -O0]",
+ ),
('force', 'f', "forcibly build everything (ignore file timestamps)"),
- ]
+ ]
boolean_options = ['compile', 'force']
- negative_opt = {'no-compile' : 'compile'}
+ negative_opt = {'no-compile': 'compile'}
def initialize_options(self):
self.build_lib = None
@@ -40,9 +44,9 @@ class build_py (Command):
self.force = None
def finalize_options(self):
- self.set_undefined_options('build',
- ('build_lib', 'build_lib'),
- ('force', 'force'))
+ self.set_undefined_options(
+ 'build', ('build_lib', 'build_lib'), ('force', 'force')
+ )
# Get the distribution options that are aliases for build_py
# options -- list of packages and list of modules.
@@ -109,26 +113,26 @@ class build_py (Command):
# Length of path to strip from found files
plen = 0
if src_dir:
- plen = len(src_dir)+1
+ plen = len(src_dir) + 1
# Strip directory from globbed filenames
- filenames = [
- file[plen:] for file in self.find_data_files(package, src_dir)
- ]
+ filenames = [file[plen:] for file in self.find_data_files(package, src_dir)]
data.append((package, src_dir, build_dir, filenames))
return data
def find_data_files(self, package, src_dir):
"""Return filenames for package's data files in 'src_dir'"""
- globs = (self.package_data.get('', [])
- + self.package_data.get(package, []))
+ globs = self.package_data.get('', []) + self.package_data.get(package, [])
files = []
for pattern in globs:
# Each pattern has to be converted to a platform-specific path
- filelist = glob.glob(os.path.join(glob.escape(src_dir), convert_path(pattern)))
+ filelist = glob.glob(
+ os.path.join(glob.escape(src_dir), convert_path(pattern))
+ )
# Files that match more than one pattern are only added once
- files.extend([fn for fn in filelist if fn not in files
- and os.path.isfile(fn)])
+ files.extend(
+ [fn for fn in filelist if fn not in files and os.path.isfile(fn)]
+ )
return files
def build_package_data(self):
@@ -138,13 +142,14 @@ class build_py (Command):
for filename in filenames:
target = os.path.join(build_dir, filename)
self.mkpath(os.path.dirname(target))
- self.copy_file(os.path.join(src_dir, filename), target,
- preserve_mode=False)
+ self.copy_file(
+ os.path.join(src_dir, filename), target, preserve_mode=False
+ )
def get_package_dir(self, package):
"""Return the directory, relative to the top of the source
- distribution, where package 'package' should be found
- (at least according to the 'package_dir' option, if any)."""
+ distribution, where package 'package' should be found
+ (at least according to the 'package_dir' option, if any)."""
path = package.split('.')
if not self.package_dir:
@@ -188,11 +193,13 @@ class build_py (Command):
if package_dir != "":
if not os.path.exists(package_dir):
raise DistutilsFileError(
- "package directory '%s' does not exist" % package_dir)
+ "package directory '%s' does not exist" % package_dir
+ )
if not os.path.isdir(package_dir):
raise DistutilsFileError(
- "supposed package directory '%s' exists, "
- "but is not a directory" % package_dir)
+ "supposed package directory '%s' exists, "
+ "but is not a directory" % package_dir
+ )
# Require __init__.py for all but the "root package"
if package:
@@ -200,8 +207,10 @@ class build_py (Command):
if os.path.isfile(init_py):
return init_py
else:
- log.warn(("package init file '%s' not found " +
- "(or not a regular file)"), init_py)
+ log.warn(
+ ("package init file '%s' not found " + "(or not a regular file)"),
+ init_py,
+ )
# Either not in a package at all (__init__.py not expected), or
# __init__.py doesn't exist -- so don't return the filename.
@@ -313,17 +322,21 @@ class build_py (Command):
outputs.append(filename)
if include_bytecode:
if self.compile:
- outputs.append(importlib.util.cache_from_source(
- filename, optimization=''))
+ outputs.append(
+ importlib.util.cache_from_source(filename, optimization='')
+ )
if self.optimize > 0:
- outputs.append(importlib.util.cache_from_source(
- filename, optimization=self.optimize))
+ outputs.append(
+ importlib.util.cache_from_source(
+ filename, optimization=self.optimize
+ )
+ )
outputs += [
os.path.join(build_dir, filename)
for package, src_dir, build_dir, filenames in self.data_files
for filename in filenames
- ]
+ ]
return outputs
@@ -332,7 +345,8 @@ class build_py (Command):
package = package.split('.')
elif not isinstance(package, (list, tuple)):
raise TypeError(
- "'package' must be a string (dot-separated), list, or tuple")
+ "'package' must be a string (dot-separated), list, or tuple"
+ )
# Now put the module source file into the "build" area -- this is
# easy, we just copy it somewhere under self.build_lib (the build
@@ -377,6 +391,7 @@ class build_py (Command):
return
from distutils.util import byte_compile
+
prefix = self.build_lib
if prefix[-1] != os.sep:
prefix = prefix + os.sep
@@ -385,8 +400,14 @@ class build_py (Command):
# method of the "install_lib" command, except for the determination
# of the 'prefix' string. Hmmm.
if self.compile:
- byte_compile(files, optimize=0,
- force=self.force, prefix=prefix, dry_run=self.dry_run)
+ byte_compile(
+ files, optimize=0, force=self.force, prefix=prefix, dry_run=self.dry_run
+ )
if self.optimize > 0:
- byte_compile(files, optimize=self.optimize,
- force=self.force, prefix=prefix, dry_run=self.dry_run)
+ byte_compile(
+ files,
+ optimize=self.optimize,
+ force=self.force,
+ prefix=prefix,
+ dry_run=self.dry_run,
+ )
diff --git a/setuptools/_distutils/command/build_scripts.py b/setuptools/_distutils/command/build_scripts.py
index e56511da..17058dbf 100644
--- a/setuptools/_distutils/command/build_scripts.py
+++ b/setuptools/_distutils/command/build_scripts.py
@@ -29,7 +29,7 @@ class build_scripts(Command):
('build-dir=', 'd', "directory to \"build\" (copy) to"),
('force', 'f', "forcibly build everything (ignore file timestamps"),
('executable=', 'e', "specify final destination interpreter path"),
- ]
+ ]
boolean_options = ['force']
@@ -40,10 +40,12 @@ class build_scripts(Command):
self.executable = None
def finalize_options(self):
- self.set_undefined_options('build',
- ('build_scripts', 'build_dir'),
- ('force', 'force'),
- ('executable', 'executable'))
+ self.set_undefined_options(
+ 'build',
+ ('build_scripts', 'build_dir'),
+ ('force', 'force'),
+ ('executable', 'executable'),
+ )
self.scripts = self.distribution.scripts
def get_source_files(self):
@@ -101,17 +103,19 @@ class build_scripts(Command):
updated_files.append(outfile)
if shebang_match:
- log.info("copying and adjusting %s -> %s", script,
- self.build_dir)
+ log.info("copying and adjusting %s -> %s", script, self.build_dir)
if not self.dry_run:
if not sysconfig.python_build:
executable = self.executable
else:
executable = os.path.join(
sysconfig.get_config_var("BINDIR"),
- "python%s%s" % (
+ "python%s%s"
+ % (
sysconfig.get_config_var("VERSION"),
- sysconfig.get_config_var("EXE")))
+ sysconfig.get_config_var("EXE"),
+ ),
+ )
post_interp = shebang_match.group(1) or ''
shebang = "#!" + executable + post_interp + "\n"
self._validate_shebang(shebang, f.encoding)
@@ -140,8 +144,7 @@ class build_scripts(Command):
oldmode = os.stat(file)[ST_MODE] & 0o7777
newmode = (oldmode | 0o555) & 0o7777
if newmode != oldmode:
- log.info("changing mode of %s from %o to %o",
- file, oldmode, newmode)
+ log.info("changing mode of %s from %o to %o", file, oldmode, newmode)
os.chmod(file, newmode)
@staticmethod
@@ -155,8 +158,8 @@ class build_scripts(Command):
shebang.encode('utf-8')
except UnicodeEncodeError:
raise ValueError(
- "The shebang ({!r}) is not encodable "
- "to utf-8".format(shebang))
+ "The shebang ({!r}) is not encodable " "to utf-8".format(shebang)
+ )
# If the script is encoded to a custom encoding (use a
# #coding:xxx cookie), the shebang has to be encodable to
@@ -166,5 +169,5 @@ class build_scripts(Command):
except UnicodeEncodeError:
raise ValueError(
"The shebang ({!r}) is not encodable "
- "to the script encoding ({})"
- .format(shebang, encoding))
+ "to the script encoding ({})".format(shebang, encoding)
+ )
diff --git a/setuptools/_distutils/command/check.py b/setuptools/_distutils/command/check.py
index af311ca9..176a8b87 100644
--- a/setuptools/_distutils/command/check.py
+++ b/setuptools/_distutils/command/check.py
@@ -15,18 +15,26 @@ try:
from docutils import nodes
class SilentReporter(Reporter):
-
- def __init__(self, source, report_level, halt_level, stream=None,
- debug=0, encoding='ascii', error_handler='replace'):
+ def __init__(
+ self,
+ source,
+ report_level,
+ halt_level,
+ stream=None,
+ debug=0,
+ encoding='ascii',
+ error_handler='replace',
+ ):
self.messages = []
- super().__init__(source, report_level, halt_level, stream,
- debug, encoding, error_handler)
+ super().__init__(
+ source, report_level, halt_level, stream, debug, encoding, error_handler
+ )
def system_message(self, level, message, *children, **kwargs):
self.messages.append((level, message, children, kwargs))
- return nodes.system_message(message, level=level,
- type=self.levels[level],
- *children, **kwargs)
+ return nodes.system_message(
+ message, level=level, type=self.levels[level], *children, **kwargs
+ )
HAS_DOCUTILS = True
except Exception:
@@ -34,16 +42,23 @@ except Exception:
# indicate that docutils is not ported to Py3k.
HAS_DOCUTILS = False
+
class check(Command):
- """This command checks the meta-data of the package.
- """
- description = ("perform some checks on the package")
- user_options = [('metadata', 'm', 'Verify meta-data'),
- ('restructuredtext', 'r',
- ('Checks if long string meta-data syntax '
- 'are reStructuredText-compliant')),
- ('strict', 's',
- 'Will exit with an error if a check fails')]
+ """This command checks the meta-data of the package."""
+
+ description = "perform some checks on the package"
+ user_options = [
+ ('metadata', 'm', 'Verify meta-data'),
+ (
+ 'restructuredtext',
+ 'r',
+ (
+ 'Checks if long string meta-data syntax '
+ 'are reStructuredText-compliant'
+ ),
+ ),
+ ('strict', 's', 'Will exit with an error if a check fails'),
+ ]
boolean_options = ['metadata', 'restructuredtext', 'strict']
@@ -82,54 +97,19 @@ class check(Command):
"""Ensures that all required elements of meta-data are supplied.
Required fields:
- name, version, URL
-
- Recommended fields:
- (author and author_email) or (maintainer and maintainer_email))
+ name, version
Warns if any are missing.
"""
metadata = self.distribution.metadata
missing = []
- for attr in ('name', 'version', 'url'):
- if not (hasattr(metadata, attr) and getattr(metadata, attr)):
+ for attr in 'name', 'version':
+ if not getattr(metadata, attr, None):
missing.append(attr)
if missing:
- self.warn("missing required meta-data: %s" % ', '.join(missing))
- if not (
- self._check_contact("author", metadata) or
- self._check_contact("maintainer", metadata)
- ):
- self.warn("missing meta-data: either (author and author_email) " +
- "or (maintainer and maintainer_email) " +
- "should be supplied")
-
- def _check_contact(self, kind, metadata):
- """
- Returns True if the contact's name is specified and False otherwise.
- This function will warn if the contact's email is not specified.
- """
- name = getattr(metadata, kind) or ''
- email = getattr(metadata, kind + '_email') or ''
-
- msg = ("missing meta-data: if '{}' supplied, " +
- "'{}' should be supplied too")
-
- if name and email:
- return True
-
- if name:
- self.warn(msg.format(kind, kind + '_email'))
- return True
-
- addresses = [(alias, addr) for alias, addr in getaddresses([email])]
- if any(alias and addr for alias, addr in addresses):
- # The contact's name can be encoded in the email: `Name <email>`
- return True
-
- return False
+ self.warn("missing required meta-data: %s" % ', '.join(missing))
def check_restructuredtext(self):
"""Checks if the long string fields are reST-compliant."""
@@ -151,13 +131,15 @@ class check(Command):
settings.tab_width = 4
settings.pep_references = None
settings.rfc_references = None
- reporter = SilentReporter(source_path,
- settings.report_level,
- settings.halt_level,
- stream=settings.warning_stream,
- debug=settings.debug,
- encoding=settings.error_encoding,
- error_handler=settings.error_encoding_error_handler)
+ reporter = SilentReporter(
+ source_path,
+ settings.report_level,
+ settings.halt_level,
+ stream=settings.warning_stream,
+ debug=settings.debug,
+ encoding=settings.error_encoding,
+ error_handler=settings.error_encoding_error_handler,
+ )
document = nodes.document(settings, reporter, source=source_path)
document.note_source(source_path, -1)
@@ -165,6 +147,7 @@ class check(Command):
parser.parse(data, document)
except AttributeError as e:
reporter.messages.append(
- (-1, 'Could not finish the parsing: %s.' % e, '', {}))
+ (-1, 'Could not finish the parsing: %s.' % e, '', {})
+ )
return reporter.messages
diff --git a/setuptools/_distutils/command/clean.py b/setuptools/_distutils/command/clean.py
index 0cb27016..b731b606 100644
--- a/setuptools/_distutils/command/clean.py
+++ b/setuptools/_distutils/command/clean.py
@@ -9,22 +9,25 @@ from distutils.core import Command
from distutils.dir_util import remove_tree
from distutils import log
+
class clean(Command):
description = "clean up temporary files from 'build' command"
user_options = [
- ('build-base=', 'b',
- "base build directory (default: 'build.build-base')"),
- ('build-lib=', None,
- "build directory for all modules (default: 'build.build-lib')"),
- ('build-temp=', 't',
- "temporary build directory (default: 'build.build-temp')"),
- ('build-scripts=', None,
- "build directory for scripts (default: 'build.build-scripts')"),
- ('bdist-base=', None,
- "temporary directory for built distributions"),
- ('all', 'a',
- "remove all build output, not just temporary by-products")
+ ('build-base=', 'b', "base build directory (default: 'build.build-base')"),
+ (
+ 'build-lib=',
+ None,
+ "build directory for all modules (default: 'build.build-lib')",
+ ),
+ ('build-temp=', 't', "temporary build directory (default: 'build.build-temp')"),
+ (
+ 'build-scripts=',
+ None,
+ "build directory for scripts (default: 'build.build-scripts')",
+ ),
+ ('bdist-base=', None, "temporary directory for built distributions"),
+ ('all', 'a', "remove all build output, not just temporary by-products"),
]
boolean_options = ['all']
@@ -38,13 +41,14 @@ class clean(Command):
self.all = None
def finalize_options(self):
- self.set_undefined_options('build',
- ('build_base', 'build_base'),
- ('build_lib', 'build_lib'),
- ('build_scripts', 'build_scripts'),
- ('build_temp', 'build_temp'))
- self.set_undefined_options('bdist',
- ('bdist_base', 'bdist_base'))
+ self.set_undefined_options(
+ 'build',
+ ('build_base', 'build_base'),
+ ('build_lib', 'build_lib'),
+ ('build_scripts', 'build_scripts'),
+ ('build_temp', 'build_temp'),
+ )
+ self.set_undefined_options('bdist', ('bdist_base', 'bdist_base'))
def run(self):
# remove the build/temp.<plat> directory (unless it's already
@@ -52,19 +56,15 @@ class clean(Command):
if os.path.exists(self.build_temp):
remove_tree(self.build_temp, dry_run=self.dry_run)
else:
- log.debug("'%s' does not exist -- can't clean it",
- self.build_temp)
+ log.debug("'%s' does not exist -- can't clean it", self.build_temp)
if self.all:
# remove build directories
- for directory in (self.build_lib,
- self.bdist_base,
- self.build_scripts):
+ for directory in (self.build_lib, self.bdist_base, self.build_scripts):
if os.path.exists(directory):
remove_tree(directory, dry_run=self.dry_run)
else:
- log.warn("'%s' does not exist -- can't clean it",
- directory)
+ log.warn("'%s' does not exist -- can't clean it", directory)
# just for the heck of it, try to remove the base build directory:
# we might have emptied it right now, but if not we don't care
diff --git a/setuptools/_distutils/command/config.py b/setuptools/_distutils/command/config.py
index aeda408e..73de1d3e 100644
--- a/setuptools/_distutils/command/config.py
+++ b/setuptools/_distutils/command/config.py
@@ -18,32 +18,26 @@ from distutils import log
LANG_EXT = {"c": ".c", "c++": ".cxx"}
+
class config(Command):
description = "prepare to build"
user_options = [
- ('compiler=', None,
- "specify the compiler type"),
- ('cc=', None,
- "specify the compiler executable"),
- ('include-dirs=', 'I',
- "list of directories to search for header files"),
- ('define=', 'D',
- "C preprocessor macros to define"),
- ('undef=', 'U',
- "C preprocessor macros to undefine"),
- ('libraries=', 'l',
- "external C libraries to link with"),
- ('library-dirs=', 'L',
- "directories to search for external C libraries"),
-
- ('noisy', None,
- "show every action (compile, link, run, ...) taken"),
- ('dump-source', None,
- "dump generated source files before attempting to compile them"),
- ]
-
+ ('compiler=', None, "specify the compiler type"),
+ ('cc=', None, "specify the compiler executable"),
+ ('include-dirs=', 'I', "list of directories to search for header files"),
+ ('define=', 'D', "C preprocessor macros to define"),
+ ('undef=', 'U', "C preprocessor macros to undefine"),
+ ('libraries=', 'l', "external C libraries to link with"),
+ ('library-dirs=', 'L', "directories to search for external C libraries"),
+ ('noisy', None, "show every action (compile, link, run, ...) taken"),
+ (
+ 'dump-source',
+ None,
+ "dump generated source files before attempting to compile them",
+ ),
+ ]
# The three standard command methods: since the "config" command
# does nothing by default, these are empty.
@@ -93,9 +87,11 @@ class config(Command):
# We do this late, and only on-demand, because this is an expensive
# import.
from distutils.ccompiler import CCompiler, new_compiler
+
if not isinstance(self.compiler, CCompiler):
- self.compiler = new_compiler(compiler=self.compiler,
- dry_run=self.dry_run, force=1)
+ self.compiler = new_compiler(
+ compiler=self.compiler, dry_run=self.dry_run, force=1
+ )
customize_compiler(self.compiler)
if self.include_dirs:
self.compiler.set_include_dirs(self.include_dirs)
@@ -132,14 +128,16 @@ class config(Command):
self.compiler.compile([src], include_dirs=include_dirs)
return (src, obj)
- def _link(self, body, headers, include_dirs, libraries, library_dirs,
- lang):
+ def _link(self, body, headers, include_dirs, libraries, library_dirs, lang):
(src, obj) = self._compile(body, headers, include_dirs, lang)
prog = os.path.splitext(os.path.basename(src))[0]
- self.compiler.link_executable([obj], prog,
- libraries=libraries,
- library_dirs=library_dirs,
- target_lang=lang)
+ self.compiler.link_executable(
+ [obj],
+ prog,
+ libraries=libraries,
+ library_dirs=library_dirs,
+ target_lang=lang,
+ )
if self.compiler.exe_extension is not None:
prog = prog + self.compiler.exe_extension
@@ -158,7 +156,6 @@ class config(Command):
except OSError:
pass
-
# XXX these ignore the dry-run flag: what to do, what to do? even if
# you want a dry-run build, you still need some sort of configuration
# info. My inclination is to make it up to the real config command to
@@ -177,6 +174,7 @@ class config(Command):
('body' probably isn't of much use, but what the heck.)
"""
from distutils.ccompiler import CompileError
+
self._check_compiler()
ok = True
try:
@@ -187,8 +185,7 @@ class config(Command):
self._clean()
return ok
- def search_cpp(self, pattern, body=None, headers=None, include_dirs=None,
- lang="c"):
+ def search_cpp(self, pattern, body=None, headers=None, include_dirs=None, lang="c"):
"""Construct a source file (just like 'try_cpp()'), run it through
the preprocessor, and return true if any line of the output matches
'pattern'. 'pattern' should either be a compiled regex object or a
@@ -220,6 +217,7 @@ class config(Command):
Return true on success, false otherwise.
"""
from distutils.ccompiler import CompileError
+
self._check_compiler()
try:
self._compile(body, headers, include_dirs, lang)
@@ -231,17 +229,24 @@ class config(Command):
self._clean()
return ok
- def try_link(self, body, headers=None, include_dirs=None, libraries=None,
- library_dirs=None, lang="c"):
+ def try_link(
+ self,
+ body,
+ headers=None,
+ include_dirs=None,
+ libraries=None,
+ library_dirs=None,
+ lang="c",
+ ):
"""Try to compile and link a source file, built from 'body' and
'headers', to executable form. Return true on success, false
otherwise.
"""
from distutils.ccompiler import CompileError, LinkError
+
self._check_compiler()
try:
- self._link(body, headers, include_dirs,
- libraries, library_dirs, lang)
+ self._link(body, headers, include_dirs, libraries, library_dirs, lang)
ok = True
except (CompileError, LinkError):
ok = False
@@ -250,17 +255,26 @@ class config(Command):
self._clean()
return ok
- def try_run(self, body, headers=None, include_dirs=None, libraries=None,
- library_dirs=None, lang="c"):
+ def try_run(
+ self,
+ body,
+ headers=None,
+ include_dirs=None,
+ libraries=None,
+ library_dirs=None,
+ lang="c",
+ ):
"""Try to compile, link to an executable, and run a program
built from 'body' and 'headers'. Return true on success, false
otherwise.
"""
from distutils.ccompiler import CompileError, LinkError
+
self._check_compiler()
try:
- src, obj, exe = self._link(body, headers, include_dirs,
- libraries, library_dirs, lang)
+ src, obj, exe = self._link(
+ body, headers, include_dirs, libraries, library_dirs, lang
+ )
self.spawn([exe])
ok = True
except (CompileError, LinkError, DistutilsExecError):
@@ -270,13 +284,20 @@ class config(Command):
self._clean()
return ok
-
# -- High-level methods --------------------------------------------
# (these are the ones that are actually likely to be useful
# when implementing a real-world config command!)
- def check_func(self, func, headers=None, include_dirs=None,
- libraries=None, library_dirs=None, decl=0, call=0):
+ def check_func(
+ self,
+ func,
+ headers=None,
+ include_dirs=None,
+ libraries=None,
+ library_dirs=None,
+ decl=0,
+ call=0,
+ ):
"""Determine if function 'func' is available by constructing a
source file that refers to 'func', and compiles and links it.
If everything succeeds, returns true; otherwise returns false.
@@ -302,11 +323,16 @@ class config(Command):
body.append("}")
body = "\n".join(body) + "\n"
- return self.try_link(body, headers, include_dirs,
- libraries, library_dirs)
+ return self.try_link(body, headers, include_dirs, libraries, library_dirs)
- def check_lib(self, library, library_dirs=None, headers=None,
- include_dirs=None, other_libraries=[]):
+ def check_lib(
+ self,
+ library,
+ library_dirs=None,
+ headers=None,
+ include_dirs=None,
+ other_libraries=[],
+ ):
"""Determine if 'library' is available to be linked against,
without actually checking that any particular symbols are provided
by it. 'headers' will be used in constructing the source file to
@@ -316,17 +342,23 @@ class config(Command):
has symbols that depend on other libraries.
"""
self._check_compiler()
- return self.try_link("int main (void) { }", headers, include_dirs,
- [library] + other_libraries, library_dirs)
-
- def check_header(self, header, include_dirs=None, library_dirs=None,
- lang="c"):
+ return self.try_link(
+ "int main (void) { }",
+ headers,
+ include_dirs,
+ [library] + other_libraries,
+ library_dirs,
+ )
+
+ def check_header(self, header, include_dirs=None, library_dirs=None, lang="c"):
"""Determine if the system header file named by 'header_file'
exists and can be found by the preprocessor; return true if so,
false otherwise.
"""
- return self.try_cpp(body="/* No body */", headers=[header],
- include_dirs=include_dirs)
+ return self.try_cpp(
+ body="/* No body */", headers=[header], include_dirs=include_dirs
+ )
+
def dump_file(filename, head=None):
"""Dumps a file content into log.info.
diff --git a/setuptools/_distutils/command/install.py b/setuptools/_distutils/command/install.py
index 41c17d8a..0660406f 100644
--- a/setuptools/_distutils/command/install.py
+++ b/setuptools/_distutils/command/install.py
@@ -21,6 +21,7 @@ from .. import _collections
from site import USER_BASE
from site import USER_SITE
+
HAS_USER_SITE = True
WINDOWS_SCHEME = {
@@ -28,7 +29,7 @@ WINDOWS_SCHEME = {
'platlib': '{base}/Lib/site-packages',
'headers': '{base}/Include/{dist_name}',
'scripts': '{base}/Scripts',
- 'data' : '{base}',
+ 'data': '{base}',
}
INSTALL_SCHEMES = {
@@ -37,31 +38,31 @@ INSTALL_SCHEMES = {
'platlib': '{platbase}/{platlibdir}/{implementation_lower}{py_version_short}/site-packages',
'headers': '{base}/include/{implementation_lower}{py_version_short}{abiflags}/{dist_name}',
'scripts': '{base}/bin',
- 'data' : '{base}',
- },
+ 'data': '{base}',
+ },
'posix_home': {
'purelib': '{base}/lib/{implementation_lower}',
'platlib': '{base}/{platlibdir}/{implementation_lower}',
'headers': '{base}/include/{implementation_lower}/{dist_name}',
'scripts': '{base}/bin',
- 'data' : '{base}',
- },
+ 'data': '{base}',
+ },
'nt': WINDOWS_SCHEME,
'pypy': {
'purelib': '{base}/site-packages',
'platlib': '{base}/site-packages',
'headers': '{base}/include/{dist_name}',
'scripts': '{base}/bin',
- 'data' : '{base}',
- },
+ 'data': '{base}',
+ },
'pypy_nt': {
'purelib': '{base}/site-packages',
'platlib': '{base}/site-packages',
'headers': '{base}/include/{dist_name}',
'scripts': '{base}/Scripts',
- 'data' : '{base}',
- },
- }
+ 'data': '{base}',
+ },
+}
# user site schemes
if HAS_USER_SITE:
@@ -70,17 +71,16 @@ if HAS_USER_SITE:
'platlib': '{usersite}',
'headers': '{userbase}/{implementation}{py_version_nodot_plat}/Include/{dist_name}',
'scripts': '{userbase}/{implementation}{py_version_nodot_plat}/Scripts',
- 'data' : '{userbase}',
- }
+ 'data': '{userbase}',
+ }
INSTALL_SCHEMES['posix_user'] = {
'purelib': '{usersite}',
'platlib': '{usersite}',
- 'headers':
- '{userbase}/include/{implementation_lower}{py_version_short}{abiflags}/{dist_name}',
+ 'headers': '{userbase}/include/{implementation_lower}{py_version_short}{abiflags}/{dist_name}',
'scripts': '{userbase}/bin',
- 'data' : '{userbase}',
- }
+ 'data': '{userbase}',
+ }
# The keys to an installation scheme; if any new types of files are to be
# installed, be sure to add an entry to every installation scheme above,
@@ -128,11 +128,7 @@ def _remove_set(ob, attrs):
"""
Include only attrs that are None in ob.
"""
- return {
- key: value
- for key, value in attrs.items()
- if getattr(ob, key) is None
- }
+ return {key: value for key, value in attrs.items() if getattr(ob, key) is None}
def _resolve_scheme(name):
@@ -164,10 +160,7 @@ def _inject_headers(name, scheme):
def _scheme_attrs(scheme):
"""Resolve install directories by applying the install schemes."""
- return {
- f'install_{key}': scheme[key]
- for key in SCHEME_KEYS
- }
+ return {f'install_{key}': scheme[key] for key in SCHEME_KEYS}
def _pypy_hack(name):
@@ -184,72 +177,73 @@ class install(Command):
user_options = [
# Select installation scheme and set base director(y|ies)
- ('prefix=', None,
- "installation prefix"),
- ('exec-prefix=', None,
- "(Unix only) prefix for platform-specific files"),
- ('home=', None,
- "(Unix only) home directory to install under"),
-
+ ('prefix=', None, "installation prefix"),
+ ('exec-prefix=', None, "(Unix only) prefix for platform-specific files"),
+ ('home=', None, "(Unix only) home directory to install under"),
# Or, just set the base director(y|ies)
- ('install-base=', None,
- "base installation directory (instead of --prefix or --home)"),
- ('install-platbase=', None,
- "base installation directory for platform-specific files " +
- "(instead of --exec-prefix or --home)"),
- ('root=', None,
- "install everything relative to this alternate root directory"),
-
+ (
+ 'install-base=',
+ None,
+ "base installation directory (instead of --prefix or --home)",
+ ),
+ (
+ 'install-platbase=',
+ None,
+ "base installation directory for platform-specific files "
+ + "(instead of --exec-prefix or --home)",
+ ),
+ ('root=', None, "install everything relative to this alternate root directory"),
# Or, explicitly set the installation scheme
- ('install-purelib=', None,
- "installation directory for pure Python module distributions"),
- ('install-platlib=', None,
- "installation directory for non-pure module distributions"),
- ('install-lib=', None,
- "installation directory for all module distributions " +
- "(overrides --install-purelib and --install-platlib)"),
-
- ('install-headers=', None,
- "installation directory for C/C++ headers"),
- ('install-scripts=', None,
- "installation directory for Python scripts"),
- ('install-data=', None,
- "installation directory for data files"),
-
+ (
+ 'install-purelib=',
+ None,
+ "installation directory for pure Python module distributions",
+ ),
+ (
+ 'install-platlib=',
+ None,
+ "installation directory for non-pure module distributions",
+ ),
+ (
+ 'install-lib=',
+ None,
+ "installation directory for all module distributions "
+ + "(overrides --install-purelib and --install-platlib)",
+ ),
+ ('install-headers=', None, "installation directory for C/C++ headers"),
+ ('install-scripts=', None, "installation directory for Python scripts"),
+ ('install-data=', None, "installation directory for data files"),
# Byte-compilation options -- see install_lib.py for details, as
# these are duplicated from there (but only install_lib does
# anything with them).
('compile', 'c', "compile .py to .pyc [default]"),
('no-compile', None, "don't compile .py files"),
- ('optimize=', 'O',
- "also compile with optimization: -O1 for \"python -O\", "
- "-O2 for \"python -OO\", and -O0 to disable [default: -O0]"),
-
+ (
+ 'optimize=',
+ 'O',
+ "also compile with optimization: -O1 for \"python -O\", "
+ "-O2 for \"python -OO\", and -O0 to disable [default: -O0]",
+ ),
# Miscellaneous control options
- ('force', 'f',
- "force installation (overwrite any existing files)"),
- ('skip-build', None,
- "skip rebuilding everything (for testing/debugging)"),
-
+ ('force', 'f', "force installation (overwrite any existing files)"),
+ ('skip-build', None, "skip rebuilding everything (for testing/debugging)"),
# Where to install documentation (eventually!)
- #('doc-format=', None, "format of documentation to generate"),
- #('install-man=', None, "directory for Unix man pages"),
- #('install-html=', None, "directory for HTML documentation"),
- #('install-info=', None, "directory for GNU info files"),
-
- ('record=', None,
- "filename in which to record list of installed files"),
- ]
+ # ('doc-format=', None, "format of documentation to generate"),
+ # ('install-man=', None, "directory for Unix man pages"),
+ # ('install-html=', None, "directory for HTML documentation"),
+ # ('install-info=', None, "directory for GNU info files"),
+ ('record=', None, "filename in which to record list of installed files"),
+ ]
boolean_options = ['compile', 'force', 'skip-build']
if HAS_USER_SITE:
- user_options.append(('user', None,
- "install in user site-package '%s'" % USER_SITE))
+ user_options.append(
+ ('user', None, "install in user site-package '%s'" % USER_SITE)
+ )
boolean_options.append('user')
- negative_opt = {'no-compile' : 'compile'}
-
+ negative_opt = {'no-compile': 'compile'}
def initialize_options(self):
"""Initializes options."""
@@ -271,10 +265,10 @@ class install(Command):
# supplied by the user, they are filled in using the installation
# scheme implied by prefix/exec-prefix/home and the contents of
# that installation scheme.
- self.install_purelib = None # for pure module distributions
- self.install_platlib = None # non-pure (dists w/ extensions)
- self.install_headers = None # for C/C++ headers
- self.install_lib = None # set to either purelib or platlib
+ self.install_purelib = None # for pure module distributions
+ self.install_platlib = None # non-pure (dists w/ extensions)
+ self.install_headers = None # for C/C++ headers
+ self.install_lib = None # set to either purelib or platlib
self.install_scripts = None
self.install_data = None
self.install_userbase = USER_BASE
@@ -316,13 +310,12 @@ class install(Command):
# Not defined yet because we don't know anything about
# documentation yet.
- #self.install_man = None
- #self.install_html = None
- #self.install_info = None
+ # self.install_man = None
+ # self.install_html = None
+ # self.install_info = None
self.record = None
-
# -- Option finalizing methods -------------------------------------
# (This is rather more involved than for most commands,
# because this is where the policy for installing third-
@@ -345,20 +338,30 @@ class install(Command):
# Check for errors/inconsistencies in the options; first, stuff
# that's wrong on any platform.
- if ((self.prefix or self.exec_prefix or self.home) and
- (self.install_base or self.install_platbase)):
+ if (self.prefix or self.exec_prefix or self.home) and (
+ self.install_base or self.install_platbase
+ ):
raise DistutilsOptionError(
- "must supply either prefix/exec-prefix/home or " +
- "install-base/install-platbase -- not both")
+ "must supply either prefix/exec-prefix/home or "
+ + "install-base/install-platbase -- not both"
+ )
if self.home and (self.prefix or self.exec_prefix):
raise DistutilsOptionError(
- "must supply either home or prefix/exec-prefix -- not both")
+ "must supply either home or prefix/exec-prefix -- not both"
+ )
- if self.user and (self.prefix or self.exec_prefix or self.home or
- self.install_base or self.install_platbase):
- raise DistutilsOptionError("can't combine user with prefix, "
- "exec_prefix/home, or install_(plat)base")
+ if self.user and (
+ self.prefix
+ or self.exec_prefix
+ or self.home
+ or self.install_base
+ or self.install_platbase
+ ):
+ raise DistutilsOptionError(
+ "can't combine user with prefix, "
+ "exec_prefix/home, or install_(plat)base"
+ )
# Next, stuff that's wrong (or dubious) only on certain platforms.
if os.name != "posix":
@@ -423,7 +426,8 @@ class install(Command):
local_vars['usersite'] = self.install_usersite
self.config_vars = _collections.DictStack(
- [compat_vars, sysconfig.get_config_vars(), local_vars])
+ [compat_vars, sysconfig.get_config_vars(), local_vars]
+ )
self.expand_basedirs()
@@ -436,6 +440,7 @@ class install(Command):
if DEBUG:
from pprint import pprint
+
print("config vars:")
pprint(dict(self.config_vars))
@@ -454,17 +459,23 @@ class install(Command):
# module distribution is pure or not. Of course, if the user
# already specified install_lib, use their selection.
if self.install_lib is None:
- if self.distribution.has_ext_modules(): # has extensions: non-pure
+ if self.distribution.has_ext_modules(): # has extensions: non-pure
self.install_lib = self.install_platlib
else:
self.install_lib = self.install_purelib
-
# Convert directories from Unix /-separated syntax to the local
# convention.
- self.convert_paths('lib', 'purelib', 'platlib',
- 'scripts', 'data', 'headers',
- 'userbase', 'usersite')
+ self.convert_paths(
+ 'lib',
+ 'purelib',
+ 'platlib',
+ 'scripts',
+ 'data',
+ 'headers',
+ 'userbase',
+ 'usersite',
+ )
# Deprecated
# Well, we're not actually fully completely finalized yet: we still
@@ -472,21 +483,22 @@ class install(Command):
# non-packagized module distributions (hello, Numerical Python!) to
# get their own directories.
self.handle_extra_path()
- self.install_libbase = self.install_lib # needed for .pth file
+ self.install_libbase = self.install_lib # needed for .pth file
self.install_lib = os.path.join(self.install_lib, self.extra_dirs)
# If a new root directory was supplied, make all the installation
# dirs relative to it.
if self.root is not None:
- self.change_roots('libbase', 'lib', 'purelib', 'platlib',
- 'scripts', 'data', 'headers')
+ self.change_roots(
+ 'libbase', 'lib', 'purelib', 'platlib', 'scripts', 'data', 'headers'
+ )
self.dump_dirs("after prepending root")
# Find out the build directories, ie. where to install from.
- self.set_undefined_options('build',
- ('build_base', 'build_base'),
- ('build_lib', 'build_lib'))
+ self.set_undefined_options(
+ 'build', ('build_base', 'build_base'), ('build_lib', 'build_lib')
+ )
# Punt on doc directories for now -- after all, we're punting on
# documentation completely!
@@ -496,6 +508,7 @@ class install(Command):
if not DEBUG:
return
from distutils.fancy_getopt import longopt_xlate
+
log.debug(msg + ":")
for opt in self.user_options:
opt_name = opt[0]
@@ -515,24 +528,24 @@ class install(Command):
if self.install_base is not None or self.install_platbase is not None:
incomplete_scheme = (
(
- self.install_lib is None and
- self.install_purelib is None and
- self.install_platlib is None
- ) or
- self.install_headers is None or
- self.install_scripts is None or
- self.install_data is None
+ self.install_lib is None
+ and self.install_purelib is None
+ and self.install_platlib is None
+ )
+ or self.install_headers is None
+ or self.install_scripts is None
+ or self.install_data is None
)
if incomplete_scheme:
raise DistutilsOptionError(
- "install-base or install-platbase supplied, but "
- "installation scheme is incomplete")
+ "install-base or install-platbase supplied, but "
+ "installation scheme is incomplete"
+ )
return
if self.user:
if self.install_userbase is None:
- raise DistutilsPlatformError(
- "User base directory is not specified")
+ raise DistutilsPlatformError("User base directory is not specified")
self.install_base = self.install_platbase = self.install_userbase
self.select_scheme("posix_user")
elif self.home is not None:
@@ -542,15 +555,14 @@ class install(Command):
if self.prefix is None:
if self.exec_prefix is not None:
raise DistutilsOptionError(
- "must not supply exec-prefix without prefix")
+ "must not supply exec-prefix without prefix"
+ )
# Allow Fedora to add components to the prefix
_prefix_addition = getattr(sysconfig, '_prefix_addition', "")
- self.prefix = (
- os.path.normpath(sys.prefix) + _prefix_addition)
- self.exec_prefix = (
- os.path.normpath(sys.exec_prefix) + _prefix_addition)
+ self.prefix = os.path.normpath(sys.prefix) + _prefix_addition
+ self.exec_prefix = os.path.normpath(sys.exec_prefix) + _prefix_addition
else:
if self.exec_prefix is None:
@@ -564,8 +576,7 @@ class install(Command):
"""Finalizes options for non-posix platforms"""
if self.user:
if self.install_userbase is None:
- raise DistutilsPlatformError(
- "User base directory is not specified")
+ raise DistutilsPlatformError("User base directory is not specified")
self.install_base = self.install_platbase = self.install_userbase
self.select_scheme(os.name + "_user")
elif self.home is not None:
@@ -580,7 +591,8 @@ class install(Command):
self.select_scheme(os.name)
except KeyError:
raise DistutilsPlatformError(
- "I don't know how to install stuff on '%s'" % os.name)
+ "I don't know how to install stuff on '%s'" % os.name
+ )
def select_scheme(self, name):
_select_scheme(self, name)
@@ -601,9 +613,16 @@ class install(Command):
def expand_dirs(self):
"""Calls `os.path.expanduser` on install dirs."""
- self._expand_attrs(['install_purelib', 'install_platlib',
- 'install_lib', 'install_headers',
- 'install_scripts', 'install_data',])
+ self._expand_attrs(
+ [
+ 'install_purelib',
+ 'install_platlib',
+ 'install_lib',
+ 'install_headers',
+ 'install_scripts',
+ 'install_data',
+ ]
+ )
def convert_paths(self, *names):
"""Call `convert_path` over `names`."""
@@ -630,8 +649,9 @@ class install(Command):
path_file, extra_dirs = self.extra_path
else:
raise DistutilsOptionError(
- "'extra_path' option must be a list, tuple, or "
- "comma-separated string with 1 or 2 elements")
+ "'extra_path' option must be a list, tuple, or "
+ "comma-separated string with 1 or 2 elements"
+ )
# convert to local form in case Unix notation used (as it
# should be in setup scripts)
@@ -674,8 +694,7 @@ class install(Command):
# internally, and not to sys.path, so we don't check the platform
# matches what we are running.
if self.warn_dir and build_plat != get_platform():
- raise DistutilsPlatformError("Can't install when "
- "cross-compiling")
+ raise DistutilsPlatformError("Can't install when " "cross-compiling")
# Run all sub-commands (at least those that need to be run)
for cmd_name in self.get_sub_commands():
@@ -687,38 +706,43 @@ class install(Command):
# write list of installed files, if requested.
if self.record:
outputs = self.get_outputs()
- if self.root: # strip any package prefix
+ if self.root: # strip any package prefix
root_len = len(self.root)
for counter in range(len(outputs)):
outputs[counter] = outputs[counter][root_len:]
- self.execute(write_file,
- (self.record, outputs),
- "writing list of installed files to '%s'" %
- self.record)
+ self.execute(
+ write_file,
+ (self.record, outputs),
+ "writing list of installed files to '%s'" % self.record,
+ )
sys_path = map(os.path.normpath, sys.path)
sys_path = map(os.path.normcase, sys_path)
install_lib = os.path.normcase(os.path.normpath(self.install_lib))
- if (self.warn_dir and
- not (self.path_file and self.install_path_file) and
- install_lib not in sys_path):
- log.debug(("modules installed to '%s', which is not in "
- "Python's module search path (sys.path) -- "
- "you'll have to change the search path yourself"),
- self.install_lib)
+ if (
+ self.warn_dir
+ and not (self.path_file and self.install_path_file)
+ and install_lib not in sys_path
+ ):
+ log.debug(
+ (
+ "modules installed to '%s', which is not in "
+ "Python's module search path (sys.path) -- "
+ "you'll have to change the search path yourself"
+ ),
+ self.install_lib,
+ )
def create_path_file(self):
"""Creates the .pth file"""
- filename = os.path.join(self.install_libbase,
- self.path_file + ".pth")
+ filename = os.path.join(self.install_libbase, self.path_file + ".pth")
if self.install_path_file:
- self.execute(write_file,
- (filename, [self.extra_dirs]),
- "creating %s" % filename)
+ self.execute(
+ write_file, (filename, [self.extra_dirs]), "creating %s" % filename
+ )
else:
self.warn("path file '%s' not created" % filename)
-
# -- Reporting methods ---------------------------------------------
def get_outputs(self):
@@ -733,8 +757,7 @@ class install(Command):
outputs.append(filename)
if self.path_file and self.install_path_file:
- outputs.append(os.path.join(self.install_libbase,
- self.path_file + ".pth"))
+ outputs.append(os.path.join(self.install_libbase, self.path_file + ".pth"))
return outputs
@@ -753,8 +776,9 @@ class install(Command):
def has_lib(self):
"""Returns true if the current distribution has any Python
modules to install."""
- return (self.distribution.has_pure_modules() or
- self.distribution.has_ext_modules())
+ return (
+ self.distribution.has_pure_modules() or self.distribution.has_ext_modules()
+ )
def has_headers(self):
"""Returns true if the current distribution has any headers to
@@ -773,9 +797,10 @@ class install(Command):
# 'sub_commands': a list of commands this command might have to run to
# get its work done. See cmd.py for more info.
- sub_commands = [('install_lib', has_lib),
- ('install_headers', has_headers),
- ('install_scripts', has_scripts),
- ('install_data', has_data),
- ('install_egg_info', lambda self:True),
- ]
+ sub_commands = [
+ ('install_lib', has_lib),
+ ('install_headers', has_headers),
+ ('install_scripts', has_scripts),
+ ('install_data', has_data),
+ ('install_egg_info', lambda self: True),
+ ]
diff --git a/setuptools/_distutils/command/install_data.py b/setuptools/_distutils/command/install_data.py
index 947cd76a..23d91ade 100644
--- a/setuptools/_distutils/command/install_data.py
+++ b/setuptools/_distutils/command/install_data.py
@@ -9,18 +9,21 @@ import os
from distutils.core import Command
from distutils.util import change_root, convert_path
+
class install_data(Command):
description = "install data files"
user_options = [
- ('install-dir=', 'd',
- "base directory for installing data files "
- "(default: installation base dir)"),
- ('root=', None,
- "install everything relative to this alternate root directory"),
+ (
+ 'install-dir=',
+ 'd',
+ "base directory for installing data files "
+ "(default: installation base dir)",
+ ),
+ ('root=', None, "install everything relative to this alternate root directory"),
('force', 'f', "force installation (overwrite existing files)"),
- ]
+ ]
boolean_options = ['force']
@@ -33,11 +36,12 @@ class install_data(Command):
self.warn_dir = 1
def finalize_options(self):
- self.set_undefined_options('install',
- ('install_data', 'install_dir'),
- ('root', 'root'),
- ('force', 'force'),
- )
+ self.set_undefined_options(
+ 'install',
+ ('install_data', 'install_dir'),
+ ('root', 'root'),
+ ('force', 'force'),
+ )
def run(self):
self.mkpath(self.install_dir)
@@ -46,9 +50,10 @@ class install_data(Command):
# it's a simple file, so copy it
f = convert_path(f)
if self.warn_dir:
- self.warn("setup script did not provide a directory for "
- "'%s' -- installing right in '%s'" %
- (f, self.install_dir))
+ self.warn(
+ "setup script did not provide a directory for "
+ "'%s' -- installing right in '%s'" % (f, self.install_dir)
+ )
(out, _) = self.copy_file(f, self.install_dir)
self.outfiles.append(out)
else:
diff --git a/setuptools/_distutils/command/install_egg_info.py b/setuptools/_distutils/command/install_egg_info.py
index adc0323f..dc939633 100644
--- a/setuptools/_distutils/command/install_egg_info.py
+++ b/setuptools/_distutils/command/install_egg_info.py
@@ -8,6 +8,7 @@ from distutils.cmd import Command
from distutils import log, dir_util
import os, sys, re
+
class install_egg_info(Command):
"""Install an .egg-info file for the package"""
@@ -28,11 +29,11 @@ class install_egg_info(Command):
return "%s-%s-py%d.%d.egg-info" % (
to_filename(safe_name(self.distribution.get_name())),
to_filename(safe_version(self.distribution.get_version())),
- *sys.version_info[:2]
+ *sys.version_info[:2],
)
def finalize_options(self):
- self.set_undefined_options('install_lib',('install_dir','install_dir'))
+ self.set_undefined_options('install_lib', ('install_dir', 'install_dir'))
self.target = os.path.join(self.install_dir, self.basename)
self.outputs = [self.target]
@@ -41,10 +42,11 @@ class install_egg_info(Command):
if os.path.isdir(target) and not os.path.islink(target):
dir_util.remove_tree(target, dry_run=self.dry_run)
elif os.path.exists(target):
- self.execute(os.unlink,(self.target,),"Removing "+target)
+ self.execute(os.unlink, (self.target,), "Removing " + target)
elif not os.path.isdir(self.install_dir):
- self.execute(os.makedirs, (self.install_dir,),
- "Creating "+self.install_dir)
+ self.execute(
+ os.makedirs, (self.install_dir,), "Creating " + self.install_dir
+ )
log.info("Writing %s", target)
if not self.dry_run:
with open(target, 'w', encoding='UTF-8') as f:
@@ -58,6 +60,7 @@ class install_egg_info(Command):
# can be replaced by importing them from pkg_resources once it is included
# in the stdlib.
+
def safe_name(name):
"""Convert an arbitrary string to a standard distribution name
@@ -72,7 +75,7 @@ def safe_version(version):
Spaces become dots, and all other non-alphanumeric characters become
dashes, with runs of multiple dashes condensed to a single dash.
"""
- version = version.replace(' ','.')
+ version = version.replace(' ', '.')
return re.sub('[^A-Za-z0-9.]+', '-', version)
@@ -81,4 +84,4 @@ def to_filename(name):
Any '-' characters are currently replaced with '_'.
"""
- return name.replace('-','_')
+ return name.replace('-', '_')
diff --git a/setuptools/_distutils/command/install_headers.py b/setuptools/_distutils/command/install_headers.py
index 9bb0b18d..87046ab3 100644
--- a/setuptools/_distutils/command/install_headers.py
+++ b/setuptools/_distutils/command/install_headers.py
@@ -11,11 +11,10 @@ class install_headers(Command):
description = "install C/C++ header files"
- user_options = [('install-dir=', 'd',
- "directory to install header files to"),
- ('force', 'f',
- "force installation (overwrite existing files)"),
- ]
+ user_options = [
+ ('install-dir=', 'd', "directory to install header files to"),
+ ('force', 'f', "force installation (overwrite existing files)"),
+ ]
boolean_options = ['force']
@@ -25,10 +24,9 @@ class install_headers(Command):
self.outfiles = []
def finalize_options(self):
- self.set_undefined_options('install',
- ('install_headers', 'install_dir'),
- ('force', 'force'))
-
+ self.set_undefined_options(
+ 'install', ('install_headers', 'install_dir'), ('force', 'force')
+ )
def run(self):
headers = self.distribution.headers
diff --git a/setuptools/_distutils/command/install_lib.py b/setuptools/_distutils/command/install_lib.py
index 6154cf09..ad3089c8 100644
--- a/setuptools/_distutils/command/install_lib.py
+++ b/setuptools/_distutils/command/install_lib.py
@@ -14,6 +14,7 @@ from distutils.errors import DistutilsOptionError
# Extension for Python source files.
PYTHON_SOURCE_EXTENSION = ".py"
+
class install_lib(Command):
description = "install all Python modules (extensions and pure Python)"
@@ -35,18 +36,21 @@ class install_lib(Command):
user_options = [
('install-dir=', 'd', "directory to install to"),
- ('build-dir=','b', "build directory (where to install from)"),
+ ('build-dir=', 'b', "build directory (where to install from)"),
('force', 'f', "force installation (overwrite existing files)"),
('compile', 'c', "compile .py to .pyc [default]"),
('no-compile', None, "don't compile .py files"),
- ('optimize=', 'O',
- "also compile with optimization: -O1 for \"python -O\", "
- "-O2 for \"python -OO\", and -O0 to disable [default: -O0]"),
+ (
+ 'optimize=',
+ 'O',
+ "also compile with optimization: -O1 for \"python -O\", "
+ "-O2 for \"python -OO\", and -O0 to disable [default: -O0]",
+ ),
('skip-build', None, "skip the build steps"),
- ]
+ ]
boolean_options = ['force', 'compile', 'skip-build']
- negative_opt = {'no-compile' : 'compile'}
+ negative_opt = {'no-compile': 'compile'}
def initialize_options(self):
# let the 'install' command dictate our installation directory
@@ -61,14 +65,15 @@ class install_lib(Command):
# Get all the information we need to install pure Python modules
# from the umbrella 'install' command -- build (source) directory,
# install (target) directory, and whether to compile .py files.
- self.set_undefined_options('install',
- ('build_lib', 'build_dir'),
- ('install_lib', 'install_dir'),
- ('force', 'force'),
- ('compile', 'compile'),
- ('optimize', 'optimize'),
- ('skip_build', 'skip_build'),
- )
+ self.set_undefined_options(
+ 'install',
+ ('build_lib', 'build_dir'),
+ ('install_lib', 'install_dir'),
+ ('force', 'force'),
+ ('compile', 'compile'),
+ ('optimize', 'optimize'),
+ ('skip_build', 'skip_build'),
+ )
if self.compile is None:
self.compile = True
@@ -110,8 +115,9 @@ class install_lib(Command):
if os.path.isdir(self.build_dir):
outfiles = self.copy_tree(self.build_dir, self.install_dir)
else:
- self.warn("'%s' does not exist -- no Python modules to install" %
- self.build_dir)
+ self.warn(
+ "'%s' does not exist -- no Python modules to install" % self.build_dir
+ )
return
return outfiles
@@ -129,14 +135,22 @@ class install_lib(Command):
install_root = self.get_finalized_command('install').root
if self.compile:
- byte_compile(files, optimize=0,
- force=self.force, prefix=install_root,
- dry_run=self.dry_run)
+ byte_compile(
+ files,
+ optimize=0,
+ force=self.force,
+ prefix=install_root,
+ dry_run=self.dry_run,
+ )
if self.optimize > 0:
- byte_compile(files, optimize=self.optimize,
- force=self.force, prefix=install_root,
- verbose=self.verbose, dry_run=self.dry_run)
-
+ byte_compile(
+ files,
+ optimize=self.optimize,
+ force=self.force,
+ prefix=install_root,
+ verbose=self.verbose,
+ dry_run=self.dry_run,
+ )
# -- Utility methods -----------------------------------------------
@@ -165,15 +179,18 @@ class install_lib(Command):
if ext != PYTHON_SOURCE_EXTENSION:
continue
if self.compile:
- bytecode_files.append(importlib.util.cache_from_source(
- py_file, optimization=''))
+ bytecode_files.append(
+ importlib.util.cache_from_source(py_file, optimization='')
+ )
if self.optimize > 0:
- bytecode_files.append(importlib.util.cache_from_source(
- py_file, optimization=self.optimize))
+ bytecode_files.append(
+ importlib.util.cache_from_source(
+ py_file, optimization=self.optimize
+ )
+ )
return bytecode_files
-
# -- External interface --------------------------------------------
# (called by outsiders)
@@ -182,19 +199,23 @@ class install_lib(Command):
were actually run. Not affected by the "dry-run" flag or whether
modules have actually been built yet.
"""
- pure_outputs = \
- self._mutate_outputs(self.distribution.has_pure_modules(),
- 'build_py', 'build_lib',
- self.install_dir)
+ pure_outputs = self._mutate_outputs(
+ self.distribution.has_pure_modules(),
+ 'build_py',
+ 'build_lib',
+ self.install_dir,
+ )
if self.compile:
bytecode_outputs = self._bytecode_filenames(pure_outputs)
else:
bytecode_outputs = []
- ext_outputs = \
- self._mutate_outputs(self.distribution.has_ext_modules(),
- 'build_ext', 'build_lib',
- self.install_dir)
+ ext_outputs = self._mutate_outputs(
+ self.distribution.has_ext_modules(),
+ 'build_ext',
+ 'build_lib',
+ self.install_dir,
+ )
return pure_outputs + bytecode_outputs + ext_outputs
diff --git a/setuptools/_distutils/command/install_scripts.py b/setuptools/_distutils/command/install_scripts.py
index 31a1130e..f09bd644 100644
--- a/setuptools/_distutils/command/install_scripts.py
+++ b/setuptools/_distutils/command/install_scripts.py
@@ -17,7 +17,7 @@ class install_scripts(Command):
user_options = [
('install-dir=', 'd', "directory to install scripts to"),
- ('build-dir=','b', "build directory (where to install from)"),
+ ('build-dir=', 'b', "build directory (where to install from)"),
('force', 'f', "force installation (overwrite existing files)"),
('skip-build', None, "skip the build steps"),
]
@@ -32,11 +32,12 @@ class install_scripts(Command):
def finalize_options(self):
self.set_undefined_options('build', ('build_scripts', 'build_dir'))
- self.set_undefined_options('install',
- ('install_scripts', 'install_dir'),
- ('force', 'force'),
- ('skip_build', 'skip_build'),
- )
+ self.set_undefined_options(
+ 'install',
+ ('install_scripts', 'install_dir'),
+ ('force', 'force'),
+ ('skip_build', 'skip_build'),
+ )
def run(self):
if not self.skip_build:
diff --git a/setuptools/_distutils/command/py37compat.py b/setuptools/_distutils/command/py37compat.py
index 754715a5..aa0c0a7f 100644
--- a/setuptools/_distutils/command/py37compat.py
+++ b/setuptools/_distutils/command/py37compat.py
@@ -7,12 +7,13 @@ def _pythonlib_compat():
library. See pypa/distutils#9.
"""
from distutils import sysconfig
+
if not sysconfig.get_config_var('Py_ENABLED_SHARED'):
return
yield 'python{}.{}{}'.format(
sys.hexversion >> 24,
- (sys.hexversion >> 16) & 0xff,
+ (sys.hexversion >> 16) & 0xFF,
sysconfig.get_config_var('ABIFLAGS'),
)
diff --git a/setuptools/_distutils/command/register.py b/setuptools/_distutils/command/register.py
index 0fac94e9..ca407eb7 100644
--- a/setuptools/_distutils/command/register.py
+++ b/setuptools/_distutils/command/register.py
@@ -14,17 +14,23 @@ from distutils.core import PyPIRCCommand
from distutils.errors import *
from distutils import log
+
class register(PyPIRCCommand):
- description = ("register the distribution with the Python package index")
+ description = "register the distribution with the Python package index"
user_options = PyPIRCCommand.user_options + [
- ('list-classifiers', None,
- 'list the valid Trove classifiers'),
- ('strict', None ,
- 'Will stop the registering if the meta-data are not fully compliant')
- ]
+ ('list-classifiers', None, 'list the valid Trove classifiers'),
+ (
+ 'strict',
+ None,
+ 'Will stop the registering if the meta-data are not fully compliant',
+ ),
+ ]
boolean_options = PyPIRCCommand.boolean_options + [
- 'verify', 'list-classifiers', 'strict']
+ 'verify',
+ 'list-classifiers',
+ 'strict',
+ ]
sub_commands = [('check', lambda self: True)]
@@ -36,8 +42,10 @@ class register(PyPIRCCommand):
def finalize_options(self):
PyPIRCCommand.finalize_options(self)
# setting options for the `check` subcommand
- check_options = {'strict': ('register', self.strict),
- 'restructuredtext': ('register', 1)}
+ check_options = {
+ 'strict': ('register', self.strict),
+ 'restructuredtext': ('register', 1),
+ }
self.distribution.command_options['check'] = check_options
def run(self):
@@ -57,8 +65,11 @@ class register(PyPIRCCommand):
def check_metadata(self):
"""Deprecated API."""
- warn("distutils.command.register.check_metadata is deprecated, \
- use the check command instead", PendingDeprecationWarning)
+ warn(
+ "distutils.command.register.check_metadata is deprecated, \
+ use the check command instead",
+ PendingDeprecationWarning,
+ )
check = self.distribution.get_command_obj('check')
check.ensure_finalized()
check.strict = self.strict
@@ -66,8 +77,7 @@ class register(PyPIRCCommand):
check.run()
def _set_config(self):
- ''' Reads the configuration file and set attributes.
- '''
+ '''Reads the configuration file and set attributes.'''
config = self._read_pypirc()
if config != {}:
self.username = config['username']
@@ -83,45 +93,43 @@ class register(PyPIRCCommand):
self.has_config = False
def classifiers(self):
- ''' Fetch the list of classifiers from the server.
- '''
- url = self.repository+'?:action=list_classifiers'
+ '''Fetch the list of classifiers from the server.'''
+ url = self.repository + '?:action=list_classifiers'
response = urllib.request.urlopen(url)
log.info(self._read_pypi_response(response))
def verify_metadata(self):
- ''' Send the metadata to the package index server to be checked.
- '''
+ '''Send the metadata to the package index server to be checked.'''
# send the info to the server and report the result
(code, result) = self.post_to_server(self.build_post_data('verify'))
log.info('Server response (%s): %s', code, result)
def send_metadata(self):
- ''' Send the metadata to the package index server.
+ '''Send the metadata to the package index server.
- Well, do the following:
- 1. figure who the user is, and then
- 2. send the data as a Basic auth'ed POST.
+ Well, do the following:
+ 1. figure who the user is, and then
+ 2. send the data as a Basic auth'ed POST.
- First we try to read the username/password from $HOME/.pypirc,
- which is a ConfigParser-formatted file with a section
- [distutils] containing username and password entries (both
- in clear text). Eg:
+ First we try to read the username/password from $HOME/.pypirc,
+ which is a ConfigParser-formatted file with a section
+ [distutils] containing username and password entries (both
+ in clear text). Eg:
- [distutils]
- index-servers =
- pypi
+ [distutils]
+ index-servers =
+ pypi
- [pypi]
- username: fred
- password: sekrit
+ [pypi]
+ username: fred
+ password: sekrit
- Otherwise, to figure who the user is, we offer the user three
- choices:
+ Otherwise, to figure who the user is, we offer the user three
+ choices:
- 1. use existing login,
- 2. register as a new user, or
- 3. set the password to a random string and email the user.
+ 1. use existing login,
+ 2. register as a new user, or
+ 3. set the password to a random string and email the user.
'''
# see if we can short-cut and get the username/password from the
@@ -137,13 +145,16 @@ class register(PyPIRCCommand):
# get the user's login info
choices = '1 2 3 4'.split()
while choice not in choices:
- self.announce('''\
+ self.announce(
+ '''\
We need to know who you are, so please choose either:
1. use your existing login,
2. register as a new user,
3. have the server generate a new password for you (and email it to you), or
4. quit
-Your selection [default 1]: ''', log.INFO)
+Your selection [default 1]: ''',
+ log.INFO,
+ )
choice = input()
if not choice:
choice = '1'
@@ -162,10 +173,8 @@ Your selection [default 1]: ''', log.INFO)
host = urllib.parse.urlparse(self.repository)[1]
auth.add_password(self.realm, host, username, password)
# send the info to the server and report the result
- code, result = self.post_to_server(self.build_post_data('submit'),
- auth)
- self.announce('Server response (%s): %s' % (code, result),
- log.INFO)
+ code, result = self.post_to_server(self.build_post_data('submit'), auth)
+ self.announce('Server response (%s): %s' % (code, result), log.INFO)
# possibly save the login
if code == 200:
@@ -174,10 +183,17 @@ Your selection [default 1]: ''', log.INFO)
# so the upload command can reuse it
self.distribution.password = password
else:
- self.announce(('I can store your PyPI login so future '
- 'submissions will be faster.'), log.INFO)
- self.announce('(the login will be stored in %s)' % \
- self._get_rc_file(), log.INFO)
+ self.announce(
+ (
+ 'I can store your PyPI login so future '
+ 'submissions will be faster.'
+ ),
+ log.INFO,
+ )
+ self.announce(
+ '(the login will be stored in %s)' % self._get_rc_file(),
+ log.INFO,
+ )
choice = 'X'
while choice.lower() not in 'yn':
choice = input('Save your login (y/N)?')
@@ -208,8 +224,7 @@ Your selection [default 1]: ''', log.INFO)
log.info('Server response (%s): %s', code, result)
else:
log.info('You will receive an email shortly.')
- log.info(('Follow the instructions in it to '
- 'complete registration.'))
+ log.info(('Follow the instructions in it to ' 'complete registration.'))
elif choice == '3':
data = {':action': 'password_reset'}
data['email'] = ''
@@ -224,7 +239,7 @@ Your selection [default 1]: ''', log.INFO)
meta = self.distribution.metadata
data = {
':action': action,
- 'metadata_version' : '1.0',
+ 'metadata_version': '1.0',
'name': meta.get_name(),
'version': meta.get_version(),
'summary': meta.get_description(),
@@ -247,12 +262,11 @@ Your selection [default 1]: ''', log.INFO)
return data
def post_to_server(self, data, auth=None):
- ''' Post a query to the server, and return a string response.
- '''
+ '''Post a query to the server, and return a string response.'''
if 'name' in data:
- self.announce('Registering %s to %s' % (data['name'],
- self.repository),
- log.INFO)
+ self.announce(
+ 'Registering %s to %s' % (data['name'], self.repository), log.INFO
+ )
# Build up the MIME payload for the urllib2 POST data
boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'
sep_boundary = '\n--' + boundary
@@ -260,12 +274,12 @@ Your selection [default 1]: ''', log.INFO)
body = io.StringIO()
for key, value in data.items():
# handle multiple entries for the same name
- if type(value) not in (type([]), type( () )):
+ if type(value) not in (type([]), type(())):
value = [value]
for value in value:
value = str(value)
body.write(sep_boundary)
- body.write('\nContent-Disposition: form-data; name="%s"'%key)
+ body.write('\nContent-Disposition: form-data; name="%s"' % key)
body.write("\n\n")
body.write(value)
if value and value[-1] == '\r':
@@ -276,8 +290,9 @@ Your selection [default 1]: ''', log.INFO)
# build the Request
headers = {
- 'Content-type': 'multipart/form-data; boundary=%s; charset=utf-8'%boundary,
- 'Content-length': str(len(body))
+ 'Content-type': 'multipart/form-data; boundary=%s; charset=utf-8'
+ % boundary,
+ 'Content-length': str(len(body)),
}
req = urllib.request.Request(self.repository, body, headers)
diff --git a/setuptools/_distutils/command/sdist.py b/setuptools/_distutils/command/sdist.py
index b4996fcb..aad3e713 100644
--- a/setuptools/_distutils/command/sdist.py
+++ b/setuptools/_distutils/command/sdist.py
@@ -24,13 +24,12 @@ def show_formats():
"""
from distutils.fancy_getopt import FancyGetopt
from distutils.archive_util import ARCHIVE_FORMATS
+
formats = []
for format in ARCHIVE_FORMATS.keys():
- formats.append(("formats=" + format, None,
- ARCHIVE_FORMATS[format][2]))
+ formats.append(("formats=" + format, None, ARCHIVE_FORMATS[format][2]))
formats.sort()
- FancyGetopt(formats).print_help(
- "List of available source distribution formats:")
+ FancyGetopt(formats).print_help("List of available source distribution formats:")
class sdist(Command):
@@ -44,55 +43,77 @@ class sdist(Command):
return self.metadata_check
user_options = [
- ('template=', 't',
- "name of manifest template file [default: MANIFEST.in]"),
- ('manifest=', 'm',
- "name of manifest file [default: MANIFEST]"),
- ('use-defaults', None,
- "include the default file set in the manifest "
- "[default; disable with --no-defaults]"),
- ('no-defaults', None,
- "don't include the default file set"),
- ('prune', None,
- "specifically exclude files/directories that should not be "
- "distributed (build tree, RCS/CVS dirs, etc.) "
- "[default; disable with --no-prune]"),
- ('no-prune', None,
- "don't automatically exclude anything"),
- ('manifest-only', 'o',
- "just regenerate the manifest and then stop "
- "(implies --force-manifest)"),
- ('force-manifest', 'f',
- "forcibly regenerate the manifest and carry on as usual. "
- "Deprecated: now the manifest is always regenerated."),
- ('formats=', None,
- "formats for source distribution (comma-separated list)"),
- ('keep-temp', 'k',
- "keep the distribution tree around after creating " +
- "archive file(s)"),
- ('dist-dir=', 'd',
- "directory to put the source distribution archive(s) in "
- "[default: dist]"),
- ('metadata-check', None,
- "Ensure that all required elements of meta-data "
- "are supplied. Warn if any missing. [default]"),
- ('owner=', 'u',
- "Owner name used when creating a tar file [default: current user]"),
- ('group=', 'g',
- "Group name used when creating a tar file [default: current group]"),
- ]
-
- boolean_options = ['use-defaults', 'prune',
- 'manifest-only', 'force-manifest',
- 'keep-temp', 'metadata-check']
+ ('template=', 't', "name of manifest template file [default: MANIFEST.in]"),
+ ('manifest=', 'm', "name of manifest file [default: MANIFEST]"),
+ (
+ 'use-defaults',
+ None,
+ "include the default file set in the manifest "
+ "[default; disable with --no-defaults]",
+ ),
+ ('no-defaults', None, "don't include the default file set"),
+ (
+ 'prune',
+ None,
+ "specifically exclude files/directories that should not be "
+ "distributed (build tree, RCS/CVS dirs, etc.) "
+ "[default; disable with --no-prune]",
+ ),
+ ('no-prune', None, "don't automatically exclude anything"),
+ (
+ 'manifest-only',
+ 'o',
+ "just regenerate the manifest and then stop " "(implies --force-manifest)",
+ ),
+ (
+ 'force-manifest',
+ 'f',
+ "forcibly regenerate the manifest and carry on as usual. "
+ "Deprecated: now the manifest is always regenerated.",
+ ),
+ ('formats=', None, "formats for source distribution (comma-separated list)"),
+ (
+ 'keep-temp',
+ 'k',
+ "keep the distribution tree around after creating " + "archive file(s)",
+ ),
+ (
+ 'dist-dir=',
+ 'd',
+ "directory to put the source distribution archive(s) in " "[default: dist]",
+ ),
+ (
+ 'metadata-check',
+ None,
+ "Ensure that all required elements of meta-data "
+ "are supplied. Warn if any missing. [default]",
+ ),
+ (
+ 'owner=',
+ 'u',
+ "Owner name used when creating a tar file [default: current user]",
+ ),
+ (
+ 'group=',
+ 'g',
+ "Group name used when creating a tar file [default: current group]",
+ ),
+ ]
+
+ boolean_options = [
+ 'use-defaults',
+ 'prune',
+ 'manifest-only',
+ 'force-manifest',
+ 'keep-temp',
+ 'metadata-check',
+ ]
help_options = [
- ('help-formats', None,
- "list available distribution formats", show_formats),
- ]
+ ('help-formats', None, "list available distribution formats", show_formats),
+ ]
- negative_opt = {'no-defaults': 'use-defaults',
- 'no-prune': 'prune' }
+ negative_opt = {'no-defaults': 'use-defaults', 'no-prune': 'prune'}
sub_commands = [('check', checking_metadata)]
@@ -131,8 +152,7 @@ class sdist(Command):
bad_format = archive_util.check_archive_formats(self.formats)
if bad_format:
- raise DistutilsOptionError(
- "unknown archive format '%s'" % bad_format)
+ raise DistutilsOptionError("unknown archive format '%s'" % bad_format)
if self.dist_dir is None:
self.dist_dir = "dist"
@@ -161,8 +181,11 @@ class sdist(Command):
def check_metadata(self):
"""Deprecated API."""
- warn("distutils.command.sdist.check_metadata is deprecated, \
- use the check command instead", PendingDeprecationWarning)
+ warn(
+ "distutils.command.sdist.check_metadata is deprecated, \
+ use the check command instead",
+ PendingDeprecationWarning,
+ )
check = self.distribution.get_command_obj('check')
check.ensure_finalized()
check.run()
@@ -189,9 +212,10 @@ class sdist(Command):
return
if not template_exists:
- self.warn(("manifest template '%s' does not exist " +
- "(using default file list)") %
- self.template)
+ self.warn(
+ ("manifest template '%s' does not exist " + "(using default file list)")
+ % self.template
+ )
self.filelist.findall()
if self.use_defaults:
@@ -259,8 +283,9 @@ class sdist(Command):
break
if not got_it:
- self.warn("standard file not found: should have one of " +
- ', '.join(alts))
+ self.warn(
+ "standard file not found: should have one of " + ', '.join(alts)
+ )
else:
if self._cs_path_exists(fn):
self.filelist.append(fn)
@@ -328,14 +353,20 @@ class sdist(Command):
'self.filelist', which updates itself accordingly.
"""
log.info("reading manifest template '%s'", self.template)
- template = TextFile(self.template, strip_comments=1, skip_blanks=1,
- join_lines=1, lstrip_ws=1, rstrip_ws=1,
- collapse_join=1)
+ template = TextFile(
+ self.template,
+ strip_comments=1,
+ skip_blanks=1,
+ join_lines=1,
+ lstrip_ws=1,
+ rstrip_ws=1,
+ collapse_join=1,
+ )
try:
while True:
line = template.readline()
- if line is None: # end of file
+ if line is None: # end of file
break
try:
@@ -344,9 +375,10 @@ class sdist(Command):
# malformed lines, or a ValueError from the lower-level
# convert_path function
except (DistutilsTemplateError, ValueError) as msg:
- self.warn("%s, line %d: %s" % (template.filename,
- template.current_line,
- msg))
+ self.warn(
+ "%s, line %d: %s"
+ % (template.filename, template.current_line, msg)
+ )
finally:
template.close()
@@ -369,8 +401,7 @@ class sdist(Command):
else:
seps = '/'
- vcs_dirs = ['RCS', 'CVS', r'\.svn', r'\.hg', r'\.git', r'\.bzr',
- '_darcs']
+ vcs_dirs = ['RCS', 'CVS', r'\.svn', r'\.hg', r'\.git', r'\.bzr', '_darcs']
vcs_ptrn = r'(^|%s)(%s)(%s).*' % (seps, '|'.join(vcs_dirs), seps)
self.filelist.exclude_pattern(vcs_ptrn, is_regex=1)
@@ -380,14 +411,19 @@ class sdist(Command):
named by 'self.manifest'.
"""
if self._manifest_is_not_generated():
- log.info("not writing to manually maintained "
- "manifest file '%s'" % self.manifest)
+ log.info(
+ "not writing to manually maintained "
+ "manifest file '%s'" % self.manifest
+ )
return
content = self.filelist.files[:]
content.insert(0, '# file GENERATED by distutils, do NOT edit')
- self.execute(file_util.write_file, (self.manifest, content),
- "writing manifest file '%s'" % self.manifest)
+ self.execute(
+ file_util.write_file,
+ (self.manifest, content),
+ "writing manifest file '%s'" % self.manifest,
+ )
def _manifest_is_not_generated(self):
# check for special comment used in 3.1.3 and higher
@@ -437,10 +473,10 @@ class sdist(Command):
# out-of-date, because by default we blow away 'base_dir' when
# we're done making the distribution archives.)
- if hasattr(os, 'link'): # can make hard links on this system
+ if hasattr(os, 'link'): # can make hard links on this system
link = 'hard'
msg = "making hard links in %s..." % base_dir
- else: # nope, have to copy
+ else: # nope, have to copy
link = None
msg = "copying files to %s..." % base_dir
@@ -471,14 +507,15 @@ class sdist(Command):
base_name = os.path.join(self.dist_dir, base_dir)
self.make_release_tree(base_dir, self.filelist.files)
- archive_files = [] # remember names of files we create
+ archive_files = [] # remember names of files we create
# tar archive must be created last to avoid overwrite and remove
if 'tar' in self.formats:
self.formats.append(self.formats.pop(self.formats.index('tar')))
for fmt in self.formats:
- file = self.make_archive(base_name, fmt, base_dir=base_dir,
- owner=self.owner, group=self.group)
+ file = self.make_archive(
+ base_name, fmt, base_dir=base_dir, owner=self.owner, group=self.group
+ )
archive_files.append(file)
self.distribution.dist_files.append(('sdist', '', file))
diff --git a/setuptools/_distutils/command/upload.py b/setuptools/_distutils/command/upload.py
index 95e9fda1..782e3dea 100644
--- a/setuptools/_distutils/command/upload.py
+++ b/setuptools/_distutils/command/upload.py
@@ -31,10 +31,9 @@ class upload(PyPIRCCommand):
description = "upload binary package to PyPI"
user_options = PyPIRCCommand.user_options + [
- ('sign', 's',
- 'sign files to upload using gpg'),
+ ('sign', 's', 'sign files to upload using gpg'),
('identity=', 'i', 'GPG identity used to sign files'),
- ]
+ ]
boolean_options = PyPIRCCommand.boolean_options + ['sign']
@@ -49,9 +48,7 @@ class upload(PyPIRCCommand):
def finalize_options(self):
PyPIRCCommand.finalize_options(self)
if self.identity and not self.sign:
- raise DistutilsOptionError(
- "Must use --sign for --identity to have meaning"
- )
+ raise DistutilsOptionError("Must use --sign for --identity to have meaning")
config = self._read_pypirc()
if config != {}:
self.username = config['username']
@@ -66,16 +63,17 @@ class upload(PyPIRCCommand):
def run(self):
if not self.distribution.dist_files:
- msg = ("Must create and upload files in one command "
- "(e.g. setup.py sdist upload)")
+ msg = (
+ "Must create and upload files in one command "
+ "(e.g. setup.py sdist upload)"
+ )
raise DistutilsOptionError(msg)
for command, pyversion, filename in self.distribution.dist_files:
self.upload_file(command, pyversion, filename)
def upload_file(self, command, pyversion, filename):
# Makes sure the repository URL is compliant
- schema, netloc, url, params, query, fragments = \
- urlparse(self.repository)
+ schema, netloc, url, params, query, fragments = urlparse(self.repository)
if params or query or fragments:
raise AssertionError("Incompatible url %s" % self.repository)
@@ -87,12 +85,11 @@ class upload(PyPIRCCommand):
gpg_args = ["gpg", "--detach-sign", "-a", filename]
if self.identity:
gpg_args[2:2] = ["--local-user", self.identity]
- spawn(gpg_args,
- dry_run=self.dry_run)
+ spawn(gpg_args, dry_run=self.dry_run)
# Fill in the data - send all the meta-data in case we need to
# register a new release
- f = open(filename,'rb')
+ f = open(filename, 'rb')
try:
content = f.read()
finally:
@@ -103,16 +100,13 @@ class upload(PyPIRCCommand):
# action
':action': 'file_upload',
'protocol_version': '1',
-
# identify release
'name': meta.get_name(),
'version': meta.get_version(),
-
# file content
- 'content': (os.path.basename(filename),content),
+ 'content': (os.path.basename(filename), content),
'filetype': command,
'pyversion': pyversion,
-
# additional meta-data
'metadata_version': '1.0',
'summary': meta.get_description(),
@@ -129,7 +123,7 @@ class upload(PyPIRCCommand):
'provides': meta.get_provides(),
'requires': meta.get_requires(),
'obsoletes': meta.get_obsoletes(),
- }
+ }
data['comment'] = ''
@@ -145,8 +139,7 @@ class upload(PyPIRCCommand):
if self.sign:
with open(filename + ".asc", "rb") as f:
- data['gpg_signature'] = (os.path.basename(filename) + ".asc",
- f.read())
+ data['gpg_signature'] = (os.path.basename(filename) + ".asc", f.read())
# set up the authentication
user_pass = (self.username + ":" + self.password).encode('ascii')
@@ -187,8 +180,7 @@ class upload(PyPIRCCommand):
'Authorization': auth,
}
- request = Request(self.repository, data=body,
- headers=headers)
+ request = Request(self.repository, data=body, headers=headers)
# send the data
try:
result = urlopen(request)
@@ -202,8 +194,7 @@ class upload(PyPIRCCommand):
raise
if status == 200:
- self.announce('Server response (%s): %s' % (status, reason),
- log.INFO)
+ self.announce('Server response (%s): %s' % (status, reason), log.INFO)
if self.show_response:
text = self._read_pypi_response(result)
msg = '\n'.join(('-' * 75, text, '-' * 75))
diff --git a/setuptools/_distutils/config.py b/setuptools/_distutils/config.py
index 2171abd6..34a1c3b7 100644
--- a/setuptools/_distutils/config.py
+++ b/setuptools/_distutils/config.py
@@ -18,20 +18,19 @@ username:%s
password:%s
"""
+
class PyPIRCCommand(Command):
- """Base command that knows how to handle the .pypirc file
- """
+ """Base command that knows how to handle the .pypirc file"""
+
DEFAULT_REPOSITORY = 'https://upload.pypi.org/legacy/'
DEFAULT_REALM = 'pypi'
repository = None
realm = None
user_options = [
- ('repository=', 'r',
- "url of repository [default: %s]" % \
- DEFAULT_REPOSITORY),
- ('show-response', None,
- 'display full response text from server')]
+ ('repository=', 'r', "url of repository [default: %s]" % DEFAULT_REPOSITORY),
+ ('show-response', None, 'display full response text from server'),
+ ]
boolean_options = ['show-response']
@@ -58,9 +57,11 @@ class PyPIRCCommand(Command):
if 'distutils' in sections:
# let's get the list of servers
index_servers = config.get('distutils', 'index-servers')
- _servers = [server.strip() for server in
- index_servers.split('\n')
- if server.strip() != '']
+ _servers = [
+ server.strip()
+ for server in index_servers.split('\n')
+ if server.strip() != ''
+ ]
if _servers == []:
# nothing set, let's try to get the default pypi
if 'pypi' in sections:
@@ -74,10 +75,11 @@ class PyPIRCCommand(Command):
current['username'] = config.get(server, 'username')
# optional params
- for key, default in (('repository',
- self.DEFAULT_REPOSITORY),
- ('realm', self.DEFAULT_REALM),
- ('password', None)):
+ for key, default in (
+ ('repository', self.DEFAULT_REPOSITORY),
+ ('realm', self.DEFAULT_REALM),
+ ('password', None),
+ ):
if config.has_option(server, key):
current[key] = config.get(server, key)
else:
@@ -86,13 +88,17 @@ class PyPIRCCommand(Command):
# work around people having "repository" for the "pypi"
# section of their config set to the HTTP (rather than
# HTTPS) URL
- if (server == 'pypi' and
- repository in (self.DEFAULT_REPOSITORY, 'pypi')):
+ if server == 'pypi' and repository in (
+ self.DEFAULT_REPOSITORY,
+ 'pypi',
+ ):
current['repository'] = self.DEFAULT_REPOSITORY
return current
- if (current['server'] == repository or
- current['repository'] == repository):
+ if (
+ current['server'] == repository
+ or current['repository'] == repository
+ ):
return current
elif 'server-login' in sections:
# old format
@@ -101,17 +107,20 @@ class PyPIRCCommand(Command):
repository = config.get(server, 'repository')
else:
repository = self.DEFAULT_REPOSITORY
- return {'username': config.get(server, 'username'),
- 'password': config.get(server, 'password'),
- 'repository': repository,
- 'server': server,
- 'realm': self.DEFAULT_REALM}
+ return {
+ 'username': config.get(server, 'username'),
+ 'password': config.get(server, 'password'),
+ 'repository': repository,
+ 'server': server,
+ 'realm': self.DEFAULT_REALM,
+ }
return {}
def _read_pypi_response(self, response):
"""Read and decode a PyPI HTTP response."""
import cgi
+
content_type = response.getheader('content-type', 'text/plain')
encoding = cgi.parse_header(content_type)[1].get('charset', 'ascii')
return response.read().decode(encoding)
diff --git a/setuptools/_distutils/core.py b/setuptools/_distutils/core.py
index f43888ea..305ecf69 100644
--- a/setuptools/_distutils/core.py
+++ b/setuptools/_distutils/core.py
@@ -30,7 +30,8 @@ usage: %(script)s [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: %(script)s cmd --help
"""
-def gen_usage (script_name):
+
+def gen_usage(script_name):
script = os.path.basename(script_name)
return USAGE % vars()
@@ -40,22 +41,51 @@ _setup_stop_after = None
_setup_distribution = None
# Legal keyword arguments for the setup() function
-setup_keywords = ('distclass', 'script_name', 'script_args', 'options',
- 'name', 'version', 'author', 'author_email',
- 'maintainer', 'maintainer_email', 'url', 'license',
- 'description', 'long_description', 'keywords',
- 'platforms', 'classifiers', 'download_url',
- 'requires', 'provides', 'obsoletes',
- )
+setup_keywords = (
+ 'distclass',
+ 'script_name',
+ 'script_args',
+ 'options',
+ 'name',
+ 'version',
+ 'author',
+ 'author_email',
+ 'maintainer',
+ 'maintainer_email',
+ 'url',
+ 'license',
+ 'description',
+ 'long_description',
+ 'keywords',
+ 'platforms',
+ 'classifiers',
+ 'download_url',
+ 'requires',
+ 'provides',
+ 'obsoletes',
+)
# Legal keyword arguments for the Extension constructor
-extension_keywords = ('name', 'sources', 'include_dirs',
- 'define_macros', 'undef_macros',
- 'library_dirs', 'libraries', 'runtime_library_dirs',
- 'extra_objects', 'extra_compile_args', 'extra_link_args',
- 'swig_opts', 'export_symbols', 'depends', 'language')
-
-def setup (**attrs):
+extension_keywords = (
+ 'name',
+ 'sources',
+ 'include_dirs',
+ 'define_macros',
+ 'undef_macros',
+ 'library_dirs',
+ 'libraries',
+ 'runtime_library_dirs',
+ 'extra_objects',
+ 'extra_compile_args',
+ 'extra_link_args',
+ 'swig_opts',
+ 'export_symbols',
+ 'depends',
+ 'language',
+)
+
+
+def setup(**attrs):
"""The gateway to the Distutils: do everything your setup script needs
to do, in a highly flexible and user-driven way. Briefly: create a
Distribution instance; find and parse config files; parse the command
@@ -100,7 +130,7 @@ def setup (**attrs):
if 'script_name' not in attrs:
attrs['script_name'] = os.path.basename(sys.argv[0])
- if 'script_args' not in attrs:
+ if 'script_args' not in attrs:
attrs['script_args'] = sys.argv[1:]
# Create the Distribution instance, using the remaining arguments
@@ -111,8 +141,7 @@ def setup (**attrs):
if 'name' not in attrs:
raise SystemExit("error in setup command: %s" % msg)
else:
- raise SystemExit("error in %s setup command: %s" % \
- (attrs['name'], msg))
+ raise SystemExit("error in %s setup command: %s" % (attrs['name'], msg))
if _setup_stop_after == "init":
return dist
@@ -149,10 +178,11 @@ def setup (**attrs):
return dist
+
# setup ()
-def run_commands (dist):
+def run_commands(dist):
"""Given a Distribution object run all the commands,
raising ``SystemExit`` errors in the case of failure.
@@ -170,8 +200,7 @@ def run_commands (dist):
else:
raise SystemExit("error: %s" % (exc,))
- except (DistutilsError,
- CCompilerError) as msg:
+ except (DistutilsError, CCompilerError) as msg:
if DEBUG:
raise
else:
@@ -180,7 +209,7 @@ def run_commands (dist):
return dist
-def run_setup (script_name, script_args=None, stop_after="run"):
+def run_setup(script_name, script_args=None, stop_after="run"):
"""Run a setup script in a somewhat controlled environment, and
return the Distribution instance that drives things. This is useful
if you need to find out the distribution meta-data (passed as
@@ -237,13 +266,18 @@ def run_setup (script_name, script_args=None, stop_after="run"):
pass
if _setup_distribution is None:
- raise RuntimeError(("'distutils.core.setup()' was never called -- "
- "perhaps '%s' is not a Distutils setup script?") % \
- script_name)
+ raise RuntimeError(
+ (
+ "'distutils.core.setup()' was never called -- "
+ "perhaps '%s' is not a Distutils setup script?"
+ )
+ % script_name
+ )
# I wonder if the setup script's namespace -- g and l -- would be of
# any interest to callers?
- #print "_setup_distribution:", _setup_distribution
+ # print "_setup_distribution:", _setup_distribution
return _setup_distribution
+
# run_setup ()
diff --git a/setuptools/_distutils/cygwinccompiler.py b/setuptools/_distutils/cygwinccompiler.py
index c5c86d8f..931b3661 100644
--- a/setuptools/_distutils/cygwinccompiler.py
+++ b/setuptools/_distutils/cygwinccompiler.py
@@ -56,17 +56,22 @@ from subprocess import check_output
from distutils.unixccompiler import UnixCCompiler
from distutils.file_util import write_file
-from distutils.errors import (DistutilsExecError, CCompilerError,
- CompileError, UnknownFileError)
+from distutils.errors import (
+ DistutilsExecError,
+ CCompilerError,
+ CompileError,
+ UnknownFileError,
+)
from distutils.version import LooseVersion, suppress_known_deprecation
+
def get_msvcr():
"""Include the appropriate MSVC runtime library if Python was built
with MSVC 7.0 or later.
"""
msc_pos = sys.version.find('MSC v.')
if msc_pos != -1:
- msc_ver = sys.version[msc_pos+6:msc_pos+10]
+ msc_ver = sys.version[msc_pos + 6 : msc_pos + 10]
if msc_ver == '1300':
# MSVC 7.0
return ['msvcr70']
@@ -90,20 +95,22 @@ def get_msvcr():
return ['msvcr120']
elif 1900 <= int(msc_ver) < 2000:
# VS2015 / MSVC 14.0
- return ['ucrt', 'vcruntime140']
+ return ['ucrt', 'vcruntime140']
else:
raise ValueError("Unknown MS Compiler version %s " % msc_ver)
class CygwinCCompiler(UnixCCompiler):
- """ Handles the Cygwin port of the GNU C compiler to Windows.
- """
+ """Handles the Cygwin port of the GNU C compiler to Windows."""
+
compiler_type = 'cygwin'
obj_extension = ".o"
static_lib_extension = ".a"
- shared_lib_extension = ".dll"
+ shared_lib_extension = ".dll.a"
+ dylib_lib_extension = ".dll"
static_lib_format = "lib%s%s"
- shared_lib_format = "%s%s"
+ shared_lib_format = "lib%s%s"
+ dylib_lib_format = "cyg%s%s"
exe_extension = ".exe"
def __init__(self, verbose=0, dry_run=0, force=0):
@@ -111,14 +118,13 @@ class CygwinCCompiler(UnixCCompiler):
super().__init__(verbose, dry_run, force)
status, details = check_config_h()
- self.debug_print("Python's GCC status: %s (details: %s)" %
- (status, details))
+ self.debug_print("Python's GCC status: %s (details: %s)" % (status, details))
if status is not CONFIG_H_OK:
self.warn(
"Python's pyconfig.h doesn't seem to support your compiler. "
"Reason: %s. "
- "Compiling may fail because of undefined preprocessor macros."
- % details)
+ "Compiling may fail because of undefined preprocessor macros." % details
+ )
self.cc = os.environ.get('CC', 'gcc')
self.cxx = os.environ.get('CXX', 'g++')
@@ -126,12 +132,13 @@ class CygwinCCompiler(UnixCCompiler):
self.linker_dll = self.cc
shared_option = "-shared"
- self.set_executables(compiler='%s -mcygwin -O -Wall' % self.cc,
- compiler_so='%s -mcygwin -mdll -O -Wall' % self.cc,
- compiler_cxx='%s -mcygwin -O -Wall' % self.cxx,
- linker_exe='%s -mcygwin' % self.cc,
- linker_so=('%s -mcygwin %s' %
- (self.linker_dll, shared_option)))
+ self.set_executables(
+ compiler='%s -mcygwin -O -Wall' % self.cc,
+ compiler_so='%s -mcygwin -mdll -O -Wall' % self.cc,
+ compiler_cxx='%s -mcygwin -O -Wall' % self.cxx,
+ linker_exe='%s -mcygwin' % self.cc,
+ linker_so=('%s -mcygwin %s' % (self.linker_dll, shared_option)),
+ )
# Include the appropriate MSVC runtime library if Python was built
# with MSVC 7.0 or later.
@@ -160,17 +167,30 @@ class CygwinCCompiler(UnixCCompiler):
self.spawn(["windres", "-i", src, "-o", obj])
except DistutilsExecError as msg:
raise CompileError(msg)
- else: # for other files use the C-compiler
+ else: # for other files use the C-compiler
try:
- self.spawn(self.compiler_so + cc_args + [src, '-o', obj] +
- extra_postargs)
+ self.spawn(
+ self.compiler_so + cc_args + [src, '-o', obj] + extra_postargs
+ )
except DistutilsExecError as msg:
raise CompileError(msg)
- def link(self, target_desc, objects, output_filename, output_dir=None,
- libraries=None, library_dirs=None, runtime_library_dirs=None,
- export_symbols=None, debug=0, extra_preargs=None,
- extra_postargs=None, build_temp=None, target_lang=None):
+ def link(
+ self,
+ target_desc,
+ objects,
+ output_filename,
+ output_dir=None,
+ libraries=None,
+ library_dirs=None,
+ runtime_library_dirs=None,
+ export_symbols=None,
+ debug=0,
+ extra_preargs=None,
+ extra_postargs=None,
+ build_temp=None,
+ target_lang=None,
+ ):
"""Link the objects."""
# use separate copies, so we can modify the lists
extra_preargs = copy.copy(extra_preargs or [])
@@ -182,8 +202,9 @@ class CygwinCCompiler(UnixCCompiler):
# handle export symbols by creating a def-file
# with executables this only works with gcc/ld as linker
- if ((export_symbols is not None) and
- (target_desc != self.EXECUTABLE or self.linker_dll == "gcc")):
+ if (export_symbols is not None) and (
+ target_desc != self.EXECUTABLE or self.linker_dll == "gcc"
+ ):
# (The linker doesn't do anything if output is up-to-date.
# So it would probably better to check if we really need this,
# but for this we had to insert some unchanged parts of
@@ -195,29 +216,27 @@ class CygwinCCompiler(UnixCCompiler):
temp_dir = os.path.dirname(objects[0])
# name of dll to give the helper files the same base name
(dll_name, dll_extension) = os.path.splitext(
- os.path.basename(output_filename))
+ os.path.basename(output_filename)
+ )
# generate the filenames for these files
def_file = os.path.join(temp_dir, dll_name + ".def")
lib_file = os.path.join(temp_dir, 'lib' + dll_name + ".a")
# Generate .def file
- contents = [
- "LIBRARY %s" % os.path.basename(output_filename),
- "EXPORTS"]
+ contents = ["LIBRARY %s" % os.path.basename(output_filename), "EXPORTS"]
for sym in export_symbols:
contents.append(sym)
- self.execute(write_file, (def_file, contents),
- "writing %s" % def_file)
+ self.execute(write_file, (def_file, contents), "writing %s" % def_file)
# next add options for def-file and to creating import libraries
# doesn't work: bfd_close build\...\libfoo.a: Invalid operation
- #extra_preargs.extend(["-Wl,--out-implib,%s" % lib_file])
+ # extra_preargs.extend(["-Wl,--out-implib,%s" % lib_file])
# for gcc/ld the def-file is specified as any object files
objects.append(def_file)
- #end: if ((export_symbols is not None) and
+ # end: if ((export_symbols is not None) and
# (target_desc != self.EXECUTABLE or self.linker_dll == "gcc")):
# who wants symbols and a many times larger output file
@@ -229,12 +248,22 @@ class CygwinCCompiler(UnixCCompiler):
if not debug:
extra_preargs.append("-s")
- UnixCCompiler.link(self, target_desc, objects, output_filename,
- output_dir, libraries, library_dirs,
- runtime_library_dirs,
- None, # export_symbols, we do this in our def-file
- debug, extra_preargs, extra_postargs, build_temp,
- target_lang)
+ UnixCCompiler.link(
+ self,
+ target_desc,
+ objects,
+ output_filename,
+ output_dir,
+ libraries,
+ library_dirs,
+ runtime_library_dirs,
+ None, # export_symbols, we do this in our def-file
+ debug,
+ extra_preargs,
+ extra_postargs,
+ build_temp,
+ target_lang,
+ )
# -- Miscellaneous methods -----------------------------------------
@@ -246,54 +275,57 @@ class CygwinCCompiler(UnixCCompiler):
for src_name in source_filenames:
# use normcase to make sure '.rc' is really '.rc' and not '.RC'
base, ext = os.path.splitext(os.path.normcase(src_name))
- if ext not in (self.src_extensions + ['.rc','.res']):
- raise UnknownFileError("unknown file type '%s' (from '%s')" % \
- (ext, src_name))
+ if ext not in (self.src_extensions + ['.rc', '.res']):
+ raise UnknownFileError(
+ "unknown file type '%s' (from '%s')" % (ext, src_name)
+ )
if strip_dir:
- base = os.path.basename (base)
+ base = os.path.basename(base)
if ext in ('.res', '.rc'):
# these need to be compiled to object files
- obj_names.append (os.path.join(output_dir,
- base + ext + self.obj_extension))
+ obj_names.append(
+ os.path.join(output_dir, base + ext + self.obj_extension)
+ )
else:
- obj_names.append (os.path.join(output_dir,
- base + self.obj_extension))
+ obj_names.append(os.path.join(output_dir, base + self.obj_extension))
return obj_names
+
# the same as cygwin plus some additional parameters
class Mingw32CCompiler(CygwinCCompiler):
- """ Handles the Mingw32 port of the GNU C compiler to Windows.
- """
+ """Handles the Mingw32 port of the GNU C compiler to Windows."""
+
compiler_type = 'mingw32'
def __init__(self, verbose=0, dry_run=0, force=0):
- super().__init__ (verbose, dry_run, force)
+ super().__init__(verbose, dry_run, force)
shared_option = "-shared"
if is_cygwincc(self.cc):
- raise CCompilerError(
- 'Cygwin gcc cannot be used with --compiler=mingw32')
-
- self.set_executables(compiler='%s -O -Wall' % self.cc,
- compiler_so='%s -mdll -O -Wall' % self.cc,
- compiler_cxx='%s -O -Wall' % self.cxx,
- linker_exe='%s' % self.cc,
- linker_so='%s %s'
- % (self.linker_dll, shared_option))
+ raise CCompilerError('Cygwin gcc cannot be used with --compiler=mingw32')
+
+ self.set_executables(
+ compiler='%s -O -Wall' % self.cc,
+ compiler_so='%s -mdll -O -Wall' % self.cc,
+ compiler_cxx='%s -O -Wall' % self.cxx,
+ linker_exe='%s' % self.cc,
+ linker_so='%s %s' % (self.linker_dll, shared_option),
+ )
# Maybe we should also append -mthreads, but then the finished
# dlls need another dll (mingwm10.dll see Mingw32 docs)
# (-mthreads: Support thread-safe exception handling on `Mingw32')
# no additional libraries needed
- self.dll_libraries=[]
+ self.dll_libraries = []
# Include the appropriate MSVC runtime library if Python was built
# with MSVC 7.0 or later.
self.dll_libraries = get_msvcr()
+
# Because these compilers aren't configured in Python's pyconfig.h file by
# default, we should at least warn the user if he is using an unmodified
# version.
@@ -302,6 +334,7 @@ CONFIG_H_OK = "ok"
CONFIG_H_NOTOK = "not ok"
CONFIG_H_UNCERTAIN = "uncertain"
+
def check_config_h():
"""Check if the current Python installation appears amenable to building
extensions with GCC.
@@ -346,8 +379,8 @@ def check_config_h():
finally:
config_h.close()
except OSError as exc:
- return (CONFIG_H_UNCERTAIN,
- "couldn't read '%s': %s" % (fn, exc.strerror))
+ return (CONFIG_H_UNCERTAIN, "couldn't read '%s': %s" % (fn, exc.strerror))
+
def is_cygwincc(cc):
'''Try to determine if the compiler that would be used is from cygwin.'''
diff --git a/setuptools/_distutils/dep_util.py b/setuptools/_distutils/dep_util.py
index d74f5e4e..d94e111c 100644
--- a/setuptools/_distutils/dep_util.py
+++ b/setuptools/_distutils/dep_util.py
@@ -8,28 +8,29 @@ import os
from distutils.errors import DistutilsFileError
-def newer (source, target):
+def newer(source, target):
"""Return true if 'source' exists and is more recently modified than
'target', or if 'source' exists and 'target' doesn't. Return false if
both exist and 'target' is the same age or younger than 'source'.
Raise DistutilsFileError if 'source' does not exist.
"""
if not os.path.exists(source):
- raise DistutilsFileError("file '%s' does not exist" %
- os.path.abspath(source))
+ raise DistutilsFileError("file '%s' does not exist" % os.path.abspath(source))
if not os.path.exists(target):
return 1
from stat import ST_MTIME
+
mtime1 = os.stat(source)[ST_MTIME]
mtime2 = os.stat(target)[ST_MTIME]
return mtime1 > mtime2
+
# newer ()
-def newer_pairwise (sources, targets):
+def newer_pairwise(sources, targets):
"""Walk two filename lists in parallel, testing if each source is newer
than its corresponding target. Return a pair of lists (sources,
targets) where source is newer than target, according to the semantics
@@ -48,10 +49,11 @@ def newer_pairwise (sources, targets):
return (n_sources, n_targets)
+
# newer_pairwise ()
-def newer_group (sources, target, missing='error'):
+def newer_group(sources, target, missing='error'):
"""Return true if 'target' is out-of-date with respect to any file
listed in 'sources'. In other words, if 'target' exists and is newer
than every file in 'sources', return false; otherwise return true.
@@ -73,15 +75,16 @@ def newer_group (sources, target, missing='error'):
# we can immediately return true. If we fall through to the end
# of the loop, then 'target' is up-to-date and we return false.
from stat import ST_MTIME
+
target_mtime = os.stat(target)[ST_MTIME]
for source in sources:
if not os.path.exists(source):
- if missing == 'error': # blow up when we stat() the file
+ if missing == 'error': # blow up when we stat() the file
pass
- elif missing == 'ignore': # missing source dropped from
- continue # target's dependency list
- elif missing == 'newer': # missing source means target is
- return 1 # out-of-date
+ elif missing == 'ignore': # missing source dropped from
+ continue # target's dependency list
+ elif missing == 'newer': # missing source means target is
+ return 1 # out-of-date
source_mtime = os.stat(source)[ST_MTIME]
if source_mtime > target_mtime:
@@ -89,4 +92,5 @@ def newer_group (sources, target, missing='error'):
else:
return 0
+
# newer_group ()
diff --git a/setuptools/_distutils/dir_util.py b/setuptools/_distutils/dir_util.py
index d5cd8e3e..2c19b983 100644
--- a/setuptools/_distutils/dir_util.py
+++ b/setuptools/_distutils/dir_util.py
@@ -30,7 +30,8 @@ def mkpath(name, mode=0o777, verbose=1, dry_run=0):
# Detect a common bug -- name is None
if not isinstance(name, str):
raise DistutilsInternalError(
- "mkpath: 'name' must be a string (got %r)" % (name,))
+ "mkpath: 'name' must be a string (got %r)" % (name,)
+ )
# XXX what's the better way to handle verbosity? print as we create
# each directory in the path (the current behaviour), or only announce
@@ -45,17 +46,17 @@ def mkpath(name, mode=0o777, verbose=1, dry_run=0):
return created_dirs
(head, tail) = os.path.split(name)
- tails = [tail] # stack of lone dirs to create
+ tails = [tail] # stack of lone dirs to create
while head and tail and not os.path.isdir(head):
(head, tail) = os.path.split(head)
- tails.insert(0, tail) # push next higher dir onto stack
+ tails.insert(0, tail) # push next higher dir onto stack
# now 'head' contains the deepest directory that already exists
# (that is, the child of 'head' in 'name' is the highest directory
# that does *not* exist)
for d in tails:
- #print "head = %s, d = %s: " % (head, d),
+ # print "head = %s, d = %s: " % (head, d),
head = os.path.join(head, d)
abs_head = os.path.abspath(head)
@@ -71,12 +72,14 @@ def mkpath(name, mode=0o777, verbose=1, dry_run=0):
except OSError as exc:
if not (exc.errno == errno.EEXIST and os.path.isdir(head)):
raise DistutilsFileError(
- "could not create '%s': %s" % (head, exc.args[-1]))
+ "could not create '%s': %s" % (head, exc.args[-1])
+ )
created_dirs.append(head)
_path_created[abs_head] = 1
return created_dirs
+
def create_tree(base_dir, files, mode=0o777, verbose=1, dry_run=0):
"""Create all the empty directories under 'base_dir' needed to put 'files'
there.
@@ -96,8 +99,17 @@ def create_tree(base_dir, files, mode=0o777, verbose=1, dry_run=0):
for dir in sorted(need_dir):
mkpath(dir, mode, verbose=verbose, dry_run=dry_run)
-def copy_tree(src, dst, preserve_mode=1, preserve_times=1,
- preserve_symlinks=0, update=0, verbose=1, dry_run=0):
+
+def copy_tree(
+ src,
+ dst,
+ preserve_mode=1,
+ preserve_times=1,
+ preserve_symlinks=0,
+ update=0,
+ verbose=1,
+ dry_run=0,
+):
"""Copy an entire directory tree 'src' to a new location 'dst'.
Both 'src' and 'dst' must be directory names. If 'src' is not a
@@ -120,8 +132,7 @@ def copy_tree(src, dst, preserve_mode=1, preserve_times=1,
from distutils.file_util import copy_file
if not dry_run and not os.path.isdir(src):
- raise DistutilsFileError(
- "cannot copy tree '%s': not a directory" % src)
+ raise DistutilsFileError("cannot copy tree '%s': not a directory" % src)
try:
names = os.listdir(src)
except OSError as e:
@@ -129,7 +140,8 @@ def copy_tree(src, dst, preserve_mode=1, preserve_times=1,
names = []
else:
raise DistutilsFileError(
- "error listing files in '%s': %s" % (src, e.strerror))
+ "error listing files in '%s': %s" % (src, e.strerror)
+ )
if not dry_run:
mkpath(dst, verbose=verbose)
@@ -154,27 +166,43 @@ def copy_tree(src, dst, preserve_mode=1, preserve_times=1,
elif os.path.isdir(src_name):
outputs.extend(
- copy_tree(src_name, dst_name, preserve_mode,
- preserve_times, preserve_symlinks, update,
- verbose=verbose, dry_run=dry_run))
+ copy_tree(
+ src_name,
+ dst_name,
+ preserve_mode,
+ preserve_times,
+ preserve_symlinks,
+ update,
+ verbose=verbose,
+ dry_run=dry_run,
+ )
+ )
else:
- copy_file(src_name, dst_name, preserve_mode,
- preserve_times, update, verbose=verbose,
- dry_run=dry_run)
+ copy_file(
+ src_name,
+ dst_name,
+ preserve_mode,
+ preserve_times,
+ update,
+ verbose=verbose,
+ dry_run=dry_run,
+ )
outputs.append(dst_name)
return outputs
+
def _build_cmdtuple(path, cmdtuples):
"""Helper for remove_tree()."""
for f in os.listdir(path):
- real_f = os.path.join(path,f)
+ real_f = os.path.join(path, f)
if os.path.isdir(real_f) and not os.path.islink(real_f):
_build_cmdtuple(real_f, cmdtuples)
else:
cmdtuples.append((os.remove, real_f))
cmdtuples.append((os.rmdir, path))
+
def remove_tree(directory, verbose=1, dry_run=0):
"""Recursively remove an entire directory tree.
@@ -199,6 +227,7 @@ def remove_tree(directory, verbose=1, dry_run=0):
except OSError as exc:
log.warn("error removing %s: %s", directory, exc)
+
def ensure_relative(path):
"""Take the full path 'path', and make it a relative path.
diff --git a/setuptools/_distutils/dist.py b/setuptools/_distutils/dist.py
index 37db4d6c..82e3684d 100644
--- a/setuptools/_distutils/dist.py
+++ b/setuptools/_distutils/dist.py
@@ -69,8 +69,7 @@ class Distribution:
('quiet', 'q', "run quietly (turns verbosity off)"),
('dry-run', 'n', "don't actually do anything"),
('help', 'h', "show detailed help message"),
- ('no-user-cfg', None,
- 'ignore pydistutils.cfg in your home directory'),
+ ('no-user-cfg', None, 'ignore pydistutils.cfg in your home directory'),
]
# 'common_usage' is a short (2-3 line) string describing the common
@@ -84,49 +83,32 @@ Common commands: (see '--help-commands' for more)
# options that are not propagated to the commands
display_options = [
- ('help-commands', None,
- "list all available commands"),
- ('name', None,
- "print package name"),
- ('version', 'V',
- "print package version"),
- ('fullname', None,
- "print <package name>-<version>"),
- ('author', None,
- "print the author's name"),
- ('author-email', None,
- "print the author's email address"),
- ('maintainer', None,
- "print the maintainer's name"),
- ('maintainer-email', None,
- "print the maintainer's email address"),
- ('contact', None,
- "print the maintainer's name if known, else the author's"),
- ('contact-email', None,
- "print the maintainer's email address if known, else the author's"),
- ('url', None,
- "print the URL for this package"),
- ('license', None,
- "print the license of the package"),
- ('licence', None,
- "alias for --license"),
- ('description', None,
- "print the package description"),
- ('long-description', None,
- "print the long package description"),
- ('platforms', None,
- "print the list of platforms"),
- ('classifiers', None,
- "print the list of classifiers"),
- ('keywords', None,
- "print the list of keywords"),
- ('provides', None,
- "print the list of packages/modules provided"),
- ('requires', None,
- "print the list of packages/modules required"),
- ('obsoletes', None,
- "print the list of packages/modules made obsolete")
- ]
+ ('help-commands', None, "list all available commands"),
+ ('name', None, "print package name"),
+ ('version', 'V', "print package version"),
+ ('fullname', None, "print <package name>-<version>"),
+ ('author', None, "print the author's name"),
+ ('author-email', None, "print the author's email address"),
+ ('maintainer', None, "print the maintainer's name"),
+ ('maintainer-email', None, "print the maintainer's email address"),
+ ('contact', None, "print the maintainer's name if known, else the author's"),
+ (
+ 'contact-email',
+ None,
+ "print the maintainer's email address if known, else the author's",
+ ),
+ ('url', None, "print the URL for this package"),
+ ('license', None, "print the license of the package"),
+ ('licence', None, "alias for --license"),
+ ('description', None, "print the package description"),
+ ('long-description', None, "print the long package description"),
+ ('platforms', None, "print the list of platforms"),
+ ('classifiers', None, "print the list of classifiers"),
+ ('keywords', None, "print the list of keywords"),
+ ('provides', None, "print the list of packages/modules provided"),
+ ('requires', None, "print the list of packages/modules required"),
+ ('obsoletes', None, "print the list of packages/modules made obsolete"),
+ ]
display_option_names = [translate_longopt(x[0]) for x in display_options]
# negative options are options that exclude other options
@@ -306,7 +288,7 @@ Common commands: (see '--help-commands' for more)
def dump_option_dicts(self, header=None, commands=None, indent=""):
from pprint import pformat
- if commands is None: # dump all command option dicts
+ if commands is None: # dump all command option dicts
commands = sorted(self.command_options.keys())
if header is not None:
@@ -320,11 +302,9 @@ Common commands: (see '--help-commands' for more)
for cmd_name in commands:
opt_dict = self.command_options.get(cmd_name)
if opt_dict is None:
- self.announce(indent +
- "no option dict for '%s' command" % cmd_name)
+ self.announce(indent + "no option dict for '%s' command" % cmd_name)
else:
- self.announce(indent +
- "option dict for '%s' command:" % cmd_name)
+ self.announce(indent + "option dict for '%s' command:" % cmd_name)
out = pformat(opt_dict)
for line in out.split('\n'):
self.announce(indent + " " + line)
@@ -385,10 +365,20 @@ Common commands: (see '--help-commands' for more)
# Ignore install directory options if we have a venv
if sys.prefix != sys.base_prefix:
ignore_options = [
- 'install-base', 'install-platbase', 'install-lib',
- 'install-platlib', 'install-purelib', 'install-headers',
- 'install-scripts', 'install-data', 'prefix', 'exec-prefix',
- 'home', 'user', 'root']
+ 'install-base',
+ 'install-platbase',
+ 'install-lib',
+ 'install-platlib',
+ 'install-purelib',
+ 'install-headers',
+ 'install-scripts',
+ 'install-data',
+ 'prefix',
+ 'exec-prefix',
+ 'home',
+ 'user',
+ 'root',
+ ]
else:
ignore_options = []
@@ -411,7 +401,7 @@ Common commands: (see '--help-commands' for more)
for opt in options:
if opt != '__name__' and opt not in ignore_options:
- val = parser.get(section,opt)
+ val = parser.get(section, opt)
opt = opt.replace('-', '_')
opt_dict[opt] = (filename, val)
@@ -428,7 +418,7 @@ Common commands: (see '--help-commands' for more)
try:
if alias:
setattr(self, alias, not strtobool(val))
- elif opt in ('verbose', 'dry_run'): # ugh!
+ elif opt in ('verbose', 'dry_run'): # ugh!
setattr(self, opt, strtobool(val))
else:
setattr(self, opt, val)
@@ -482,7 +472,7 @@ Common commands: (see '--help-commands' for more)
return
while args:
args = self._parse_command_opts(parser, args)
- if args is None: # user asked for help (and got it)
+ if args is None: # user asked for help (and got it)
return
# Handle the cases of --help as a "global" option, ie.
@@ -492,9 +482,9 @@ Common commands: (see '--help-commands' for more)
# latter, we omit the display-only options and show help for
# each command listed on the command line.
if self.help:
- self._show_help(parser,
- display_options=len(self.commands) == 0,
- commands=self.commands)
+ self._show_help(
+ parser, display_options=len(self.commands) == 0, commands=self.commands
+ )
return
# Oops, no commands found -- an end-user error
@@ -511,9 +501,12 @@ Common commands: (see '--help-commands' for more)
level as well as options recognized for commands.
"""
return self.global_options + [
- ("command-packages=", None,
- "list of packages that provide distutils commands"),
- ]
+ (
+ "command-packages=",
+ None,
+ "list of packages that provide distutils commands",
+ ),
+ ]
def _parse_command_opts(self, parser, args):
"""Parse the command-line options for a single command.
@@ -545,14 +538,19 @@ Common commands: (see '--help-commands' for more)
# to be sure that the basic "command" interface is implemented.
if not issubclass(cmd_class, Command):
raise DistutilsClassError(
- "command class %s must subclass Command" % cmd_class)
+ "command class %s must subclass Command" % cmd_class
+ )
# Also make sure that the command object provides a list of its
# known options.
- if not (hasattr(cmd_class, 'user_options') and
- isinstance(cmd_class.user_options, list)):
- msg = ("command class %s must provide "
- "'user_options' attribute (a list of tuples)")
+ if not (
+ hasattr(cmd_class, 'user_options')
+ and isinstance(cmd_class.user_options, list)
+ ):
+ msg = (
+ "command class %s must provide "
+ "'user_options' attribute (a list of tuples)"
+ )
raise DistutilsClassError(msg % cmd_class)
# If the command class has a list of negative alias options,
@@ -564,36 +562,39 @@ Common commands: (see '--help-commands' for more)
# Check for help_options in command class. They have a different
# format (tuple of four) so we need to preprocess them here.
- if (hasattr(cmd_class, 'help_options') and
- isinstance(cmd_class.help_options, list)):
+ if hasattr(cmd_class, 'help_options') and isinstance(
+ cmd_class.help_options, list
+ ):
help_options = fix_help_options(cmd_class.help_options)
else:
help_options = []
# All commands support the global options too, just by adding
# in 'global_options'.
- parser.set_option_table(self.global_options +
- cmd_class.user_options +
- help_options)
+ parser.set_option_table(
+ self.global_options + cmd_class.user_options + help_options
+ )
parser.set_negative_aliases(negative_opt)
(args, opts) = parser.getopt(args[1:])
if hasattr(opts, 'help') and opts.help:
self._show_help(parser, display_options=0, commands=[cmd_class])
return
- if (hasattr(cmd_class, 'help_options') and
- isinstance(cmd_class.help_options, list)):
- help_option_found=0
+ if hasattr(cmd_class, 'help_options') and isinstance(
+ cmd_class.help_options, list
+ ):
+ help_option_found = 0
for (help_option, short, desc, func) in cmd_class.help_options:
if hasattr(opts, parser.get_attr_name(help_option)):
- help_option_found=1
+ help_option_found = 1
if callable(func):
func()
else:
raise DistutilsClassError(
"invalid help function %r for help option '%s': "
"must be a callable object (function, etc.)"
- % (func, help_option))
+ % (func, help_option)
+ )
if help_option_found:
return
@@ -619,8 +620,7 @@ Common commands: (see '--help-commands' for more)
value = [elm.strip() for elm in value.split(',')]
setattr(self.metadata, attr, value)
- def _show_help(self, parser, global_options=1, display_options=1,
- commands=[]):
+ def _show_help(self, parser, global_options=1, display_options=1, commands=[]):
"""Show help for the setup script command-line in the form of
several lists of command-line options. 'parser' should be a
FancyGetopt instance; do not expect it to be returned in the
@@ -649,8 +649,9 @@ Common commands: (see '--help-commands' for more)
if display_options:
parser.set_option_table(self.display_options)
parser.print_help(
- "Information display options (just display " +
- "information, ignore any commands)")
+ "Information display options (just display "
+ + "information, ignore any commands)"
+ )
print('')
for command in self.commands:
@@ -658,10 +659,10 @@ Common commands: (see '--help-commands' for more)
klass = command
else:
klass = self.get_command_class(command)
- if (hasattr(klass, 'help_options') and
- isinstance(klass.help_options, list)):
- parser.set_option_table(klass.user_options +
- fix_help_options(klass.help_options))
+ if hasattr(klass, 'help_options') and isinstance(klass.help_options, list):
+ parser.set_option_table(
+ klass.user_options + fix_help_options(klass.help_options)
+ )
else:
parser.set_option_table(klass.user_options)
parser.print_help("Options for '%s' command:" % klass.__name__)
@@ -697,11 +698,10 @@ Common commands: (see '--help-commands' for more)
for (opt, val) in option_order:
if val and is_display_option.get(opt):
opt = translate_longopt(opt)
- value = getattr(self.metadata, "get_"+opt)()
+ value = getattr(self.metadata, "get_" + opt)()
if opt in ['keywords', 'platforms']:
print(','.join(value))
- elif opt in ('classifiers', 'provides', 'requires',
- 'obsoletes'):
+ elif opt in ('classifiers', 'provides', 'requires', 'obsoletes'):
print('\n'.join(value))
else:
print(value)
@@ -735,6 +735,7 @@ Common commands: (see '--help-commands' for more)
'description'.
"""
import distutils.command
+
std_commands = distutils.command.__all__
is_std = {}
for cmd in std_commands:
@@ -746,18 +747,14 @@ Common commands: (see '--help-commands' for more)
extra_commands.append(cmd)
max_length = 0
- for cmd in (std_commands + extra_commands):
+ for cmd in std_commands + extra_commands:
if len(cmd) > max_length:
max_length = len(cmd)
- self.print_command_list(std_commands,
- "Standard commands",
- max_length)
+ self.print_command_list(std_commands, "Standard commands", max_length)
if extra_commands:
print()
- self.print_command_list(extra_commands,
- "Extra commands",
- max_length)
+ self.print_command_list(extra_commands, "Extra commands", max_length)
def get_command_list(self):
"""Get a list of (command, description) tuples.
@@ -769,6 +766,7 @@ Common commands: (see '--help-commands' for more)
# Currently this is only used on Mac OS, for the Mac-only GUI
# Distutils interface (by Jack Jansen)
import distutils.command
+
std_commands = distutils.command.__all__
is_std = {}
for cmd in std_commands:
@@ -780,7 +778,7 @@ Common commands: (see '--help-commands' for more)
extra_commands.append(cmd)
rv = []
- for cmd in (std_commands + extra_commands):
+ for cmd in std_commands + extra_commands:
klass = self.cmdclass.get(cmd)
if not klass:
klass = self.get_command_class(cmd)
@@ -836,7 +834,8 @@ Common commands: (see '--help-commands' for more)
except AttributeError:
raise DistutilsModuleError(
"invalid command '%s' (no class '%s' in module '%s')"
- % (command, klass_name, module_name))
+ % (command, klass_name, module_name)
+ )
self.cmdclass[command] = klass
return klass
@@ -852,8 +851,10 @@ Common commands: (see '--help-commands' for more)
cmd_obj = self.command_obj.get(command)
if not cmd_obj and create:
if DEBUG:
- self.announce("Distribution.get_command_obj(): "
- "creating '%s' command object" % command)
+ self.announce(
+ "Distribution.get_command_obj(): "
+ "creating '%s' command object" % command
+ )
klass = self.get_command_class(command)
cmd_obj = self.command_obj[command] = klass(self)
@@ -887,11 +888,9 @@ Common commands: (see '--help-commands' for more)
self.announce(" setting options for '%s' command:" % command_name)
for (option, (source, value)) in option_dict.items():
if DEBUG:
- self.announce(" %s = %s (from %s)" % (option, value,
- source))
+ self.announce(" %s = %s (from %s)" % (option, value, source))
try:
- bool_opts = [translate_longopt(o)
- for o in command_obj.boolean_options]
+ bool_opts = [translate_longopt(o) for o in command_obj.boolean_options]
except AttributeError:
bool_opts = []
try:
@@ -910,7 +909,8 @@ Common commands: (see '--help-commands' for more)
else:
raise DistutilsOptionError(
"error in %s: command '%s' has no such option '%s'"
- % (source, command_name, option))
+ % (source, command_name, option)
+ )
except ValueError as msg:
raise DistutilsOptionError(msg)
@@ -934,6 +934,7 @@ Common commands: (see '--help-commands' for more)
Returns the reinitialized command object.
"""
from distutils.cmd import Command
+
if not isinstance(command, Command):
command_name = command
command = self.get_command_obj(command_name)
@@ -1010,9 +1011,11 @@ Common commands: (see '--help-commands' for more)
return self.data_files and len(self.data_files) > 0
def is_pure(self):
- return (self.has_pure_modules() and
- not self.has_ext_modules() and
- not self.has_c_libraries())
+ return (
+ self.has_pure_modules()
+ and not self.has_ext_modules()
+ and not self.has_c_libraries()
+ )
# -- Metadata query methods ----------------------------------------
@@ -1021,19 +1024,35 @@ Common commands: (see '--help-commands' for more)
# to self.metadata.get_XXX. The actual code is in the
# DistributionMetadata class, below.
+
class DistributionMetadata:
"""Dummy class to hold the distribution meta-data: name, version,
author, and so forth.
"""
- _METHOD_BASENAMES = ("name", "version", "author", "author_email",
- "maintainer", "maintainer_email", "url",
- "license", "description", "long_description",
- "keywords", "platforms", "fullname", "contact",
- "contact_email", "classifiers", "download_url",
- # PEP 314
- "provides", "requires", "obsoletes",
- )
+ _METHOD_BASENAMES = (
+ "name",
+ "version",
+ "author",
+ "author_email",
+ "maintainer",
+ "maintainer_email",
+ "url",
+ "license",
+ "description",
+ "long_description",
+ "keywords",
+ "platforms",
+ "fullname",
+ "contact",
+ "contact_email",
+ "classifiers",
+ "download_url",
+ # PEP 314
+ "provides",
+ "requires",
+ "obsoletes",
+ )
def __init__(self, path=None):
if path is not None:
@@ -1064,9 +1083,8 @@ class DistributionMetadata:
def _read_field(name):
value = msg[name]
- if value == 'UNKNOWN':
- return None
- return value
+ if value and value != "UNKNOWN":
+ return value
def _read_list(name):
values = msg.get_all(name, None)
@@ -1111,37 +1129,42 @@ class DistributionMetadata:
self.obsoletes = None
def write_pkg_info(self, base_dir):
- """Write the PKG-INFO file into the release tree.
- """
- with open(os.path.join(base_dir, 'PKG-INFO'), 'w',
- encoding='UTF-8') as pkg_info:
+ """Write the PKG-INFO file into the release tree."""
+ with open(
+ os.path.join(base_dir, 'PKG-INFO'), 'w', encoding='UTF-8'
+ ) as pkg_info:
self.write_pkg_file(pkg_info)
def write_pkg_file(self, file):
- """Write the PKG-INFO format data to a file object.
- """
+ """Write the PKG-INFO format data to a file object."""
version = '1.0'
- if (self.provides or self.requires or self.obsoletes or
- self.classifiers or self.download_url):
+ if (
+ self.provides
+ or self.requires
+ or self.obsoletes
+ or self.classifiers
+ or self.download_url
+ ):
version = '1.1'
+ # required fields
file.write('Metadata-Version: %s\n' % version)
file.write('Name: %s\n' % self.get_name())
file.write('Version: %s\n' % self.get_version())
- file.write('Summary: %s\n' % self.get_description())
- file.write('Home-page: %s\n' % self.get_url())
- file.write('Author: %s\n' % self.get_contact())
- file.write('Author-email: %s\n' % self.get_contact_email())
- file.write('License: %s\n' % self.get_license())
- if self.download_url:
- file.write('Download-URL: %s\n' % self.download_url)
- long_desc = rfc822_escape(self.get_long_description())
- file.write('Description: %s\n' % long_desc)
+ def maybe_write(header, val):
+ if val:
+ file.write("{}: {}\n".format(header, val))
- keywords = ','.join(self.get_keywords())
- if keywords:
- file.write('Keywords: %s\n' % keywords)
+ # optional fields
+ maybe_write("Summary", self.get_description())
+ maybe_write("Home-page", self.get_url())
+ maybe_write("Author", self.get_contact())
+ maybe_write("Author-email", self.get_contact_email())
+ maybe_write("License", self.get_license())
+ maybe_write("Download-URL", self.download_url)
+ maybe_write("Description", rfc822_escape(self.get_long_description() or ""))
+ maybe_write("Keywords", ",".join(self.get_keywords()))
self._write_list(file, 'Platform', self.get_platforms())
self._write_list(file, 'Classifier', self.get_classifiers())
@@ -1152,6 +1175,7 @@ class DistributionMetadata:
self._write_list(file, 'Obsoletes', self.get_obsoletes())
def _write_list(self, file, name, values):
+ values = values or []
for value in values:
file.write('%s: %s\n' % (name, value))
@@ -1167,35 +1191,36 @@ class DistributionMetadata:
return "%s-%s" % (self.get_name(), self.get_version())
def get_author(self):
- return self.author or "UNKNOWN"
+ return self.author
def get_author_email(self):
- return self.author_email or "UNKNOWN"
+ return self.author_email
def get_maintainer(self):
- return self.maintainer or "UNKNOWN"
+ return self.maintainer
def get_maintainer_email(self):
- return self.maintainer_email or "UNKNOWN"
+ return self.maintainer_email
def get_contact(self):
- return self.maintainer or self.author or "UNKNOWN"
+ return self.maintainer or self.author
def get_contact_email(self):
- return self.maintainer_email or self.author_email or "UNKNOWN"
+ return self.maintainer_email or self.author_email
def get_url(self):
- return self.url or "UNKNOWN"
+ return self.url
def get_license(self):
- return self.license or "UNKNOWN"
+ return self.license
+
get_licence = get_license
def get_description(self):
- return self.description or "UNKNOWN"
+ return self.description
def get_long_description(self):
- return self.long_description or "UNKNOWN"
+ return self.long_description
def get_keywords(self):
return self.keywords or []
@@ -1204,7 +1229,7 @@ class DistributionMetadata:
self.keywords = _ensure_list(value, 'keywords')
def get_platforms(self):
- return self.platforms or ["UNKNOWN"]
+ return self.platforms
def set_platforms(self, value):
self.platforms = _ensure_list(value, 'platforms')
@@ -1216,7 +1241,7 @@ class DistributionMetadata:
self.classifiers = _ensure_list(value, 'classifiers')
def get_download_url(self):
- return self.download_url or "UNKNOWN"
+ return self.download_url
# PEP 314
def get_requires(self):
@@ -1224,6 +1249,7 @@ class DistributionMetadata:
def set_requires(self, value):
import distutils.versionpredicate
+
for v in value:
distutils.versionpredicate.VersionPredicate(v)
self.requires = list(value)
@@ -1235,6 +1261,7 @@ class DistributionMetadata:
value = [v.strip() for v in value]
for v in value:
import distutils.versionpredicate
+
distutils.versionpredicate.split_provision(v)
self.provides = value
@@ -1243,10 +1270,12 @@ class DistributionMetadata:
def set_obsoletes(self, value):
import distutils.versionpredicate
+
for v in value:
distutils.versionpredicate.VersionPredicate(v)
self.obsoletes = list(value)
+
def fix_help_options(options):
"""Convert a 4-tuple 'help_options' list as found in various command
classes to the 3-tuple form required by FancyGetopt.
diff --git a/setuptools/_distutils/errors.py b/setuptools/_distutils/errors.py
index 8b93059e..626254c3 100644
--- a/setuptools/_distutils/errors.py
+++ b/setuptools/_distutils/errors.py
@@ -8,90 +8,120 @@ usually raised for errors that are obviously the end-user's fault
This module is safe to use in "from ... import *" mode; it only exports
symbols whose names start with "Distutils" and end with "Error"."""
-class DistutilsError (Exception):
+
+class DistutilsError(Exception):
"""The root of all Distutils evil."""
+
pass
-class DistutilsModuleError (DistutilsError):
+
+class DistutilsModuleError(DistutilsError):
"""Unable to load an expected module, or to find an expected class
within some module (in particular, command modules and classes)."""
+
pass
-class DistutilsClassError (DistutilsError):
+
+class DistutilsClassError(DistutilsError):
"""Some command class (or possibly distribution class, if anyone
feels a need to subclass Distribution) is found not to be holding
up its end of the bargain, ie. implementing some part of the
"command "interface."""
+
pass
-class DistutilsGetoptError (DistutilsError):
+
+class DistutilsGetoptError(DistutilsError):
"""The option table provided to 'fancy_getopt()' is bogus."""
+
pass
-class DistutilsArgError (DistutilsError):
+
+class DistutilsArgError(DistutilsError):
"""Raised by fancy_getopt in response to getopt.error -- ie. an
error in the command line usage."""
+
pass
-class DistutilsFileError (DistutilsError):
+
+class DistutilsFileError(DistutilsError):
"""Any problems in the filesystem: expected file not found, etc.
Typically this is for problems that we detect before OSError
could be raised."""
+
pass
-class DistutilsOptionError (DistutilsError):
+
+class DistutilsOptionError(DistutilsError):
"""Syntactic/semantic errors in command options, such as use of
mutually conflicting options, or inconsistent options,
badly-spelled values, etc. No distinction is made between option
values originating in the setup script, the command line, config
files, or what-have-you -- but if we *know* something originated in
the setup script, we'll raise DistutilsSetupError instead."""
+
pass
-class DistutilsSetupError (DistutilsError):
+
+class DistutilsSetupError(DistutilsError):
"""For errors that can be definitely blamed on the setup script,
such as invalid keyword arguments to 'setup()'."""
+
pass
-class DistutilsPlatformError (DistutilsError):
+
+class DistutilsPlatformError(DistutilsError):
"""We don't know how to do something on the current platform (but
we do know how to do it on some platform) -- eg. trying to compile
C files on a platform not supported by a CCompiler subclass."""
+
pass
-class DistutilsExecError (DistutilsError):
+
+class DistutilsExecError(DistutilsError):
"""Any problems executing an external program (such as the C
compiler, when compiling C files)."""
+
pass
-class DistutilsInternalError (DistutilsError):
+
+class DistutilsInternalError(DistutilsError):
"""Internal inconsistencies or impossibilities (obviously, this
should never be seen if the code is working!)."""
+
pass
-class DistutilsTemplateError (DistutilsError):
+
+class DistutilsTemplateError(DistutilsError):
"""Syntax error in a file list template."""
+
class DistutilsByteCompileError(DistutilsError):
"""Byte compile error."""
+
# Exception classes used by the CCompiler implementation classes
-class CCompilerError (Exception):
+class CCompilerError(Exception):
"""Some compile/link operation failed."""
-class PreprocessError (CCompilerError):
+
+class PreprocessError(CCompilerError):
"""Failure to preprocess one or more C/C++ files."""
-class CompileError (CCompilerError):
+
+class CompileError(CCompilerError):
"""Failure to compile one or more C/C++ source files."""
-class LibError (CCompilerError):
+
+class LibError(CCompilerError):
"""Failure to create a static library from one or more C/C++ object
files."""
-class LinkError (CCompilerError):
+
+class LinkError(CCompilerError):
"""Failure to link one or more C/C++ object files into an executable
or shared library file."""
-class UnknownFileError (CCompilerError):
+
+class UnknownFileError(CCompilerError):
"""Attempt to process an unknown file type."""
diff --git a/setuptools/_distutils/extension.py b/setuptools/_distutils/extension.py
index c507da36..b05c5d90 100644
--- a/setuptools/_distutils/extension.py
+++ b/setuptools/_distutils/extension.py
@@ -16,6 +16,7 @@ import warnings
# import that large-ish module (indirectly, through distutils.core) in
# order to do anything.
+
class Extension:
"""Just a collection of attributes that describes an extension
module and everything needed to build it (hopefully in a portable
@@ -83,27 +84,29 @@ class Extension:
# When adding arguments to this constructor, be sure to update
# setup_keywords in core.py.
- def __init__(self, name, sources,
- include_dirs=None,
- define_macros=None,
- undef_macros=None,
- library_dirs=None,
- libraries=None,
- runtime_library_dirs=None,
- extra_objects=None,
- extra_compile_args=None,
- extra_link_args=None,
- export_symbols=None,
- swig_opts = None,
- depends=None,
- language=None,
- optional=None,
- **kw # To catch unknown keywords
- ):
+ def __init__(
+ self,
+ name,
+ sources,
+ include_dirs=None,
+ define_macros=None,
+ undef_macros=None,
+ library_dirs=None,
+ libraries=None,
+ runtime_library_dirs=None,
+ extra_objects=None,
+ extra_compile_args=None,
+ extra_link_args=None,
+ export_symbols=None,
+ swig_opts=None,
+ depends=None,
+ language=None,
+ optional=None,
+ **kw # To catch unknown keywords
+ ):
if not isinstance(name, str):
raise AssertionError("'name' must be a string")
- if not (isinstance(sources, list) and
- all(isinstance(v, str) for v in sources)):
+ if not (isinstance(sources, list) and all(isinstance(v, str) for v in sources)):
raise AssertionError("'sources' must be a list of strings")
self.name = name
@@ -135,13 +138,13 @@ class Extension:
self.__class__.__module__,
self.__class__.__qualname__,
self.name,
- id(self))
+ id(self),
+ )
def read_setup_file(filename):
"""Reads a Setup file and returns Extension instances."""
- from distutils.sysconfig import (parse_makefile, expand_makefile_vars,
- _variable_rx)
+ from distutils.sysconfig import parse_makefile, expand_makefile_vars, _variable_rx
from distutils.text_file import TextFile
from distutils.util import split_quoted
@@ -151,17 +154,22 @@ def read_setup_file(filename):
# Second pass to gobble up the real content: lines of the form
# <module> ... [<sourcefile> ...] [<cpparg> ...] [<library> ...]
- file = TextFile(filename,
- strip_comments=1, skip_blanks=1, join_lines=1,
- lstrip_ws=1, rstrip_ws=1)
+ file = TextFile(
+ filename,
+ strip_comments=1,
+ skip_blanks=1,
+ join_lines=1,
+ lstrip_ws=1,
+ rstrip_ws=1,
+ )
try:
extensions = []
while True:
line = file.readline()
- if line is None: # eof
+ if line is None: # eof
break
- if _variable_rx.match(line): # VAR=VALUE, handled in first pass
+ if _variable_rx.match(line): # VAR=VALUE, handled in first pass
continue
if line[0] == line[-1] == "*":
@@ -188,7 +196,8 @@ def read_setup_file(filename):
continue
suffix = os.path.splitext(word)[1]
- switch = word[0:2] ; value = word[2:]
+ switch = word[0:2]
+ value = word[2:]
if suffix in (".c", ".cc", ".cpp", ".cxx", ".c++", ".m", ".mm"):
# hmm, should we do something about C vs. C++ sources?
@@ -199,14 +208,13 @@ def read_setup_file(filename):
ext.include_dirs.append(value)
elif switch == "-D":
equals = value.find("=")
- if equals == -1: # bare "-DFOO" -- no value
+ if equals == -1: # bare "-DFOO" -- no value
ext.define_macros.append((value, None))
- else: # "-DFOO=blah"
- ext.define_macros.append((value[0:equals],
- value[equals+2:]))
+ else: # "-DFOO=blah"
+ ext.define_macros.append((value[0:equals], value[equals + 2 :]))
elif switch == "-U":
ext.undef_macros.append(value)
- elif switch == "-C": # only here 'cause makesetup has it!
+ elif switch == "-C": # only here 'cause makesetup has it!
ext.extra_compile_args.append(word)
elif switch == "-l":
ext.libraries.append(value)
diff --git a/setuptools/_distutils/fancy_getopt.py b/setuptools/_distutils/fancy_getopt.py
index 7d170dd2..b9b21766 100644
--- a/setuptools/_distutils/fancy_getopt.py
+++ b/setuptools/_distutils/fancy_getopt.py
@@ -26,6 +26,7 @@ neg_alias_re = re.compile("^(%s)=!(%s)$" % (longopt_pat, longopt_pat))
# (for use as attributes of some object).
longopt_xlate = str.maketrans('-', '_')
+
class FancyGetopt:
"""Wrapper around the standard 'getopt()' module that provides some
handy extra functionality:
@@ -90,7 +91,8 @@ class FancyGetopt:
def add_option(self, long_option, short_option=None, help_string=None):
if long_option in self.option_index:
raise DistutilsGetoptError(
- "option conflict: already an option '%s'" % long_option)
+ "option conflict: already an option '%s'" % long_option
+ )
else:
option = (long_option, short_option, help_string)
self.option_table.append(option)
@@ -111,11 +113,15 @@ class FancyGetopt:
assert isinstance(aliases, dict)
for (alias, opt) in aliases.items():
if alias not in self.option_index:
- raise DistutilsGetoptError(("invalid %s '%s': "
- "option '%s' not defined") % (what, alias, alias))
+ raise DistutilsGetoptError(
+ ("invalid %s '%s': " "option '%s' not defined")
+ % (what, alias, alias)
+ )
if opt not in self.option_index:
- raise DistutilsGetoptError(("invalid %s '%s': "
- "aliased option '%s' not defined") % (what, alias, opt))
+ raise DistutilsGetoptError(
+ ("invalid %s '%s': " "aliased option '%s' not defined")
+ % (what, alias, opt)
+ )
def set_aliases(self, alias):
"""Set the aliases for this option parser."""
@@ -153,19 +159,23 @@ class FancyGetopt:
# Type- and value-check the option names
if not isinstance(long, str) or len(long) < 2:
- raise DistutilsGetoptError(("invalid long option '%s': "
- "must be a string of length >= 2") % long)
+ raise DistutilsGetoptError(
+ ("invalid long option '%s': " "must be a string of length >= 2")
+ % long
+ )
- if (not ((short is None) or
- (isinstance(short, str) and len(short) == 1))):
- raise DistutilsGetoptError("invalid short option '%s': "
- "must a single character or None" % short)
+ if not ((short is None) or (isinstance(short, str) and len(short) == 1)):
+ raise DistutilsGetoptError(
+ "invalid short option '%s': "
+ "must a single character or None" % short
+ )
self.repeat[long] = repeat
self.long_opts.append(long)
- if long[-1] == '=': # option takes an argument?
- if short: short = short + ':'
+ if long[-1] == '=': # option takes an argument?
+ if short:
+ short = short + ':'
long = long[0:-1]
self.takes_arg[long] = 1
else:
@@ -175,11 +185,11 @@ class FancyGetopt:
if alias_to is not None:
if self.takes_arg[alias_to]:
raise DistutilsGetoptError(
- "invalid negative alias '%s': "
- "aliased option '%s' takes a value"
- % (long, alias_to))
+ "invalid negative alias '%s': "
+ "aliased option '%s' takes a value" % (long, alias_to)
+ )
- self.long_opts[-1] = long # XXX redundant?!
+ self.long_opts[-1] = long # XXX redundant?!
self.takes_arg[long] = 0
# If this is an alias option, make sure its "takes arg" flag is
@@ -188,10 +198,10 @@ class FancyGetopt:
if alias_to is not None:
if self.takes_arg[long] != self.takes_arg[alias_to]:
raise DistutilsGetoptError(
- "invalid alias '%s': inconsistent with "
- "aliased option '%s' (one of them takes a value, "
- "the other doesn't"
- % (long, alias_to))
+ "invalid alias '%s': inconsistent with "
+ "aliased option '%s' (one of them takes a value, "
+ "the other doesn't" % (long, alias_to)
+ )
# Now enforce some bondage on the long option name, so we can
# later translate it to an attribute name on some object. Have
@@ -199,8 +209,9 @@ class FancyGetopt:
# '='.
if not longopt_re.match(long):
raise DistutilsGetoptError(
- "invalid long option name '%s' "
- "(must be letters, numbers, hyphens only" % long)
+ "invalid long option name '%s' "
+ "(must be letters, numbers, hyphens only" % long
+ )
self.attr_name[long] = self.get_attr_name(long)
if short:
@@ -235,7 +246,7 @@ class FancyGetopt:
raise DistutilsArgError(msg)
for opt, val in opts:
- if len(opt) == 2 and opt[0] == '-': # it's a short option
+ if len(opt) == 2 and opt[0] == '-': # it's a short option
opt = self.short2long[opt[1]]
else:
assert len(opt) > 2 and opt[:2] == '--'
@@ -245,7 +256,7 @@ class FancyGetopt:
if alias:
opt = alias
- if not self.takes_arg[opt]: # boolean option?
+ if not self.takes_arg[opt]: # boolean option?
assert val == '', "boolean option can't have value"
alias = self.negative_alias.get(opt)
if alias:
@@ -294,11 +305,11 @@ class FancyGetopt:
if long[-1] == '=':
l = l - 1
if short is not None:
- l = l + 5 # " (-x)" where short == 'x'
+ l = l + 5 # " (-x)" where short == 'x'
if l > max_opt:
max_opt = l
- opt_width = max_opt + 2 + 2 + 2 # room for indent + dashes + gutter
+ opt_width = max_opt + 2 + 2 + 2 # room for indent + dashes + gutter
# Typical help block looks like this:
# --foo controls foonabulation
@@ -348,8 +359,7 @@ class FancyGetopt:
else:
opt_names = "%s (-%s)" % (long, short)
if text:
- lines.append(" --%-*s %s" %
- (max_opt, opt_names, text[0]))
+ lines.append(" --%-*s %s" % (max_opt, opt_names, text[0]))
else:
lines.append(" --%-*s" % opt_names)
@@ -370,7 +380,8 @@ def fancy_getopt(options, negative_opt, object, args):
return parser.getopt(args, object)
-WS_TRANS = {ord(_wschar) : ' ' for _wschar in string.whitespace}
+WS_TRANS = {ord(_wschar): ' ' for _wschar in string.whitespace}
+
def wrap_text(text, width):
"""wrap_text(text : string, width : int) -> [string]
@@ -386,26 +397,26 @@ def wrap_text(text, width):
text = text.expandtabs()
text = text.translate(WS_TRANS)
chunks = re.split(r'( +|-+)', text)
- chunks = [ch for ch in chunks if ch] # ' - ' results in empty strings
+ chunks = [ch for ch in chunks if ch] # ' - ' results in empty strings
lines = []
while chunks:
- cur_line = [] # list of chunks (to-be-joined)
- cur_len = 0 # length of current line
+ cur_line = [] # list of chunks (to-be-joined)
+ cur_len = 0 # length of current line
while chunks:
l = len(chunks[0])
- if cur_len + l <= width: # can squeeze (at least) this chunk in
+ if cur_len + l <= width: # can squeeze (at least) this chunk in
cur_line.append(chunks[0])
del chunks[0]
cur_len = cur_len + l
- else: # this line is full
+ else: # this line is full
# drop last chunk if all space
if cur_line and cur_line[-1][0] == ' ':
del cur_line[-1]
break
- if chunks: # any chunks left to process?
+ if chunks: # any chunks left to process?
# if the current line is still empty, then we had a single
# chunk that's too big too fit on a line -- so we break
# down and break it up at the line width
diff --git a/setuptools/_distutils/file_util.py b/setuptools/_distutils/file_util.py
index b3fee35a..4ff2230c 100644
--- a/setuptools/_distutils/file_util.py
+++ b/setuptools/_distutils/file_util.py
@@ -8,12 +8,10 @@ from distutils.errors import DistutilsFileError
from distutils import log
# for generating verbose output in 'copy_file()'
-_copy_action = { None: 'copying',
- 'hard': 'hard linking',
- 'sym': 'symbolically linking' }
+_copy_action = {None: 'copying', 'hard': 'hard linking', 'sym': 'symbolically linking'}
-def _copy_file_contents(src, dst, buffer_size=16*1024):
+def _copy_file_contents(src, dst, buffer_size=16 * 1024):
"""Copy the file 'src' to 'dst'; both must be filenames. Any error
opening either file, reading from 'src', or writing to 'dst', raises
DistutilsFileError. Data is read/written in chunks of 'buffer_size'
@@ -35,20 +33,21 @@ def _copy_file_contents(src, dst, buffer_size=16*1024):
os.unlink(dst)
except OSError as e:
raise DistutilsFileError(
- "could not delete '%s': %s" % (dst, e.strerror))
+ "could not delete '%s': %s" % (dst, e.strerror)
+ )
try:
fdst = open(dst, 'wb')
except OSError as e:
- raise DistutilsFileError(
- "could not create '%s': %s" % (dst, e.strerror))
+ raise DistutilsFileError("could not create '%s': %s" % (dst, e.strerror))
while True:
try:
buf = fsrc.read(buffer_size)
except OSError as e:
raise DistutilsFileError(
- "could not read from '%s': %s" % (src, e.strerror))
+ "could not read from '%s': %s" % (src, e.strerror)
+ )
if not buf:
break
@@ -57,15 +56,25 @@ def _copy_file_contents(src, dst, buffer_size=16*1024):
fdst.write(buf)
except OSError as e:
raise DistutilsFileError(
- "could not write to '%s': %s" % (dst, e.strerror))
+ "could not write to '%s': %s" % (dst, e.strerror)
+ )
finally:
if fdst:
fdst.close()
if fsrc:
fsrc.close()
-def copy_file(src, dst, preserve_mode=1, preserve_times=1, update=0,
- link=None, verbose=1, dry_run=0):
+
+def copy_file(
+ src,
+ dst,
+ preserve_mode=1,
+ preserve_times=1,
+ update=0,
+ link=None,
+ verbose=1,
+ dry_run=0,
+):
"""Copy a file 'src' to 'dst'. If 'dst' is a directory, then 'src' is
copied there with the same name; otherwise, it must be a filename. (If
the file exists, it will be ruthlessly clobbered.) If 'preserve_mode'
@@ -102,7 +111,8 @@ def copy_file(src, dst, preserve_mode=1, preserve_times=1, update=0,
if not os.path.isfile(src):
raise DistutilsFileError(
- "can't copy '%s': doesn't exist or not a regular file" % src)
+ "can't copy '%s': doesn't exist or not a regular file" % src
+ )
if os.path.isdir(dst):
dir = dst
@@ -163,9 +173,7 @@ def copy_file(src, dst, preserve_mode=1, preserve_times=1, update=0,
# XXX I suspect this is Unix-specific -- need porting help!
-def move_file (src, dst,
- verbose=1,
- dry_run=0):
+def move_file(src, dst, verbose=1, dry_run=0):
"""Move a file 'src' to 'dst'. If 'dst' is a directory, the file will
be moved into it with the same name; otherwise, 'src' is just renamed
@@ -190,13 +198,13 @@ def move_file (src, dst,
dst = os.path.join(dst, basename(src))
elif exists(dst):
raise DistutilsFileError(
- "can't move '%s': destination '%s' already exists" %
- (src, dst))
+ "can't move '%s': destination '%s' already exists" % (src, dst)
+ )
if not isdir(dirname(dst)):
raise DistutilsFileError(
- "can't move '%s': destination '%s' not a valid path" %
- (src, dst))
+ "can't move '%s': destination '%s' not a valid path" % (src, dst)
+ )
copy_it = False
try:
@@ -206,8 +214,7 @@ def move_file (src, dst,
if num == errno.EXDEV:
copy_it = True
else:
- raise DistutilsFileError(
- "couldn't move '%s' to '%s': %s" % (src, dst, msg))
+ raise DistutilsFileError("couldn't move '%s' to '%s': %s" % (src, dst, msg))
if copy_it:
copy_file(src, dst, verbose=verbose)
@@ -220,13 +227,13 @@ def move_file (src, dst,
except OSError:
pass
raise DistutilsFileError(
- "couldn't move '%s' to '%s' by copy/delete: "
- "delete '%s' failed: %s"
- % (src, dst, src, msg))
+ "couldn't move '%s' to '%s' by copy/delete: "
+ "delete '%s' failed: %s" % (src, dst, src, msg)
+ )
return dst
-def write_file (filename, contents):
+def write_file(filename, contents):
"""Create a file with the specified name and write 'contents' (a
sequence of strings without line terminators) to it.
"""
diff --git a/setuptools/_distutils/filelist.py b/setuptools/_distutils/filelist.py
index 82a77384..37ab341e 100644
--- a/setuptools/_distutils/filelist.py
+++ b/setuptools/_distutils/filelist.py
@@ -46,6 +46,7 @@ class FileList:
DISTUTILS_DEBUG environment variable) flag is true.
"""
from distutils.debug import DEBUG
+
if DEBUG:
print(msg)
@@ -80,22 +81,24 @@ class FileList:
patterns = dir = dir_pattern = None
- if action in ('include', 'exclude',
- 'global-include', 'global-exclude'):
+ if action in ('include', 'exclude', 'global-include', 'global-exclude'):
if len(words) < 2:
raise DistutilsTemplateError(
- "'%s' expects <pattern1> <pattern2> ..." % action)
+ "'%s' expects <pattern1> <pattern2> ..." % action
+ )
patterns = [convert_path(w) for w in words[1:]]
elif action in ('recursive-include', 'recursive-exclude'):
if len(words) < 3:
raise DistutilsTemplateError(
- "'%s' expects <dir> <pattern1> <pattern2> ..." % action)
+ "'%s' expects <dir> <pattern1> <pattern2> ..." % action
+ )
dir = convert_path(words[1])
patterns = [convert_path(w) for w in words[2:]]
elif action in ('graft', 'prune'):
if len(words) != 2:
raise DistutilsTemplateError(
- "'%s' expects a single <dir_pattern>" % action)
+ "'%s' expects a single <dir_pattern>" % action
+ )
dir_pattern = convert_path(words[1])
else:
raise DistutilsTemplateError("unknown action '%s'" % action)
@@ -117,65 +120,82 @@ class FileList:
self.debug_print("include " + ' '.join(patterns))
for pattern in patterns:
if not self.include_pattern(pattern, anchor=1):
- log.warn("warning: no files found matching '%s'",
- pattern)
+ log.warn("warning: no files found matching '%s'", pattern)
elif action == 'exclude':
self.debug_print("exclude " + ' '.join(patterns))
for pattern in patterns:
if not self.exclude_pattern(pattern, anchor=1):
- log.warn(("warning: no previously-included files "
- "found matching '%s'"), pattern)
+ log.warn(
+ (
+ "warning: no previously-included files "
+ "found matching '%s'"
+ ),
+ pattern,
+ )
elif action == 'global-include':
self.debug_print("global-include " + ' '.join(patterns))
for pattern in patterns:
if not self.include_pattern(pattern, anchor=0):
- log.warn(("warning: no files found matching '%s' "
- "anywhere in distribution"), pattern)
+ log.warn(
+ (
+ "warning: no files found matching '%s' "
+ "anywhere in distribution"
+ ),
+ pattern,
+ )
elif action == 'global-exclude':
self.debug_print("global-exclude " + ' '.join(patterns))
for pattern in patterns:
if not self.exclude_pattern(pattern, anchor=0):
- log.warn(("warning: no previously-included files matching "
- "'%s' found anywhere in distribution"),
- pattern)
+ log.warn(
+ (
+ "warning: no previously-included files matching "
+ "'%s' found anywhere in distribution"
+ ),
+ pattern,
+ )
elif action == 'recursive-include':
- self.debug_print("recursive-include %s %s" %
- (dir, ' '.join(patterns)))
+ self.debug_print("recursive-include %s %s" % (dir, ' '.join(patterns)))
for pattern in patterns:
if not self.include_pattern(pattern, prefix=dir):
msg = (
- "warning: no files found matching '%s' "
- "under directory '%s'"
+ "warning: no files found matching '%s' " "under directory '%s'"
)
log.warn(msg, pattern, dir)
elif action == 'recursive-exclude':
- self.debug_print("recursive-exclude %s %s" %
- (dir, ' '.join(patterns)))
+ self.debug_print("recursive-exclude %s %s" % (dir, ' '.join(patterns)))
for pattern in patterns:
if not self.exclude_pattern(pattern, prefix=dir):
- log.warn(("warning: no previously-included files matching "
- "'%s' found under directory '%s'"),
- pattern, dir)
+ log.warn(
+ (
+ "warning: no previously-included files matching "
+ "'%s' found under directory '%s'"
+ ),
+ pattern,
+ dir,
+ )
elif action == 'graft':
self.debug_print("graft " + dir_pattern)
if not self.include_pattern(None, prefix=dir_pattern):
- log.warn("warning: no directories found matching '%s'",
- dir_pattern)
+ log.warn("warning: no directories found matching '%s'", dir_pattern)
elif action == 'prune':
self.debug_print("prune " + dir_pattern)
if not self.exclude_pattern(None, prefix=dir_pattern):
- log.warn(("no previously-included directories found "
- "matching '%s'"), dir_pattern)
+ log.warn(
+ ("no previously-included directories found " "matching '%s'"),
+ dir_pattern,
+ )
else:
raise DistutilsInternalError(
- "this cannot happen: invalid action '%s'" % action)
+ "this cannot happen: invalid action '%s'" % action
+ )
# Filtering/selection methods
@@ -207,8 +227,7 @@ class FileList:
# XXX docstring lying about what the special chars are?
files_found = False
pattern_re = translate_pattern(pattern, anchor, prefix, is_regex)
- self.debug_print("include_pattern: applying regex r'%s'" %
- pattern_re.pattern)
+ self.debug_print("include_pattern: applying regex r'%s'" % pattern_re.pattern)
# delayed loading of allfiles list
if self.allfiles is None:
@@ -221,8 +240,7 @@ class FileList:
files_found = True
return files_found
- def exclude_pattern(
- self, pattern, anchor=1, prefix=None, is_regex=0):
+ def exclude_pattern(self, pattern, anchor=1, prefix=None, is_regex=0):
"""Remove strings (presumably filenames) from 'files' that match
'pattern'. Other parameters are the same as for
'include_pattern()', above.
@@ -231,9 +249,8 @@ class FileList:
"""
files_found = False
pattern_re = translate_pattern(pattern, anchor, prefix, is_regex)
- self.debug_print("exclude_pattern: applying regex r'%s'" %
- pattern_re.pattern)
- for i in range(len(self.files)-1, -1, -1):
+ self.debug_print("exclude_pattern: applying regex r'%s'" % pattern_re.pattern)
+ for i in range(len(self.files) - 1, -1, -1):
if pattern_re.search(self.files[i]):
self.debug_print(" removing " + self.files[i])
del self.files[i]
@@ -243,15 +260,14 @@ class FileList:
# Utility functions
+
def _find_all_simple(path):
"""
Find all files under 'path'
"""
all_unique = _UniqueDirs.filter(os.walk(path, followlinks=True))
results = (
- os.path.join(base, file)
- for base, dirs, files in all_unique
- for file in files
+ os.path.join(base, file) for base, dirs, files in all_unique for file in files
)
return filter(os.path.isfile, results)
@@ -262,6 +278,7 @@ class _UniqueDirs(set):
avoiding infinite recursion.
Ref https://bugs.python.org/issue44497.
"""
+
def __call__(self, walk_item):
"""
Given an item from an os.walk result, determine
@@ -341,15 +358,14 @@ def translate_pattern(pattern, anchor=1, prefix=None, is_regex=0):
if prefix is not None:
prefix_re = glob_to_re(prefix)
assert prefix_re.startswith(start) and prefix_re.endswith(end)
- prefix_re = prefix_re[len(start): len(prefix_re) - len(end)]
+ prefix_re = prefix_re[len(start) : len(prefix_re) - len(end)]
sep = os.sep
if os.sep == '\\':
sep = r'\\'
- pattern_re = pattern_re[len(start): len(pattern_re) - len(end)]
- pattern_re = r'%s\A%s%s.*%s%s' % (
- start, prefix_re, sep, pattern_re, end)
- else: # no prefix -- respect anchor flag
+ pattern_re = pattern_re[len(start) : len(pattern_re) - len(end)]
+ pattern_re = r'%s\A%s%s.*%s%s' % (start, prefix_re, sep, pattern_re, end)
+ else: # no prefix -- respect anchor flag
if anchor:
- pattern_re = r'%s\A%s' % (start, pattern_re[len(start):])
+ pattern_re = r'%s\A%s' % (start, pattern_re[len(start) :])
return re.compile(pattern_re)
diff --git a/setuptools/_distutils/log.py b/setuptools/_distutils/log.py
index a68b156b..be25f6ca 100644
--- a/setuptools/_distutils/log.py
+++ b/setuptools/_distutils/log.py
@@ -13,7 +13,6 @@ FATAL = 5
class Log:
-
def __init__(self, threshold=WARN):
self.threshold = threshold
diff --git a/setuptools/_distutils/msvc9compiler.py b/setuptools/_distutils/msvc9compiler.py
index 6b627383..225f1a2f 100644
--- a/setuptools/_distutils/msvc9compiler.py
+++ b/setuptools/_distutils/msvc9compiler.py
@@ -17,8 +17,13 @@ import subprocess
import sys
import re
-from distutils.errors import DistutilsExecError, DistutilsPlatformError, \
- CompileError, LibError, LinkError
+from distutils.errors import (
+ DistutilsExecError,
+ DistutilsPlatformError,
+ CompileError,
+ LibError,
+ LinkError,
+)
from distutils.ccompiler import CCompiler, gen_lib_options
from distutils import log
from distutils.util import get_platform
@@ -30,12 +35,14 @@ RegEnumKey = winreg.EnumKey
RegEnumValue = winreg.EnumValue
RegError = winreg.error
-HKEYS = (winreg.HKEY_USERS,
- winreg.HKEY_CURRENT_USER,
- winreg.HKEY_LOCAL_MACHINE,
- winreg.HKEY_CLASSES_ROOT)
+HKEYS = (
+ winreg.HKEY_USERS,
+ winreg.HKEY_CURRENT_USER,
+ winreg.HKEY_LOCAL_MACHINE,
+ winreg.HKEY_CLASSES_ROOT,
+)
-NATIVE_WIN64 = (sys.platform == 'win32' and sys.maxsize > 2**32)
+NATIVE_WIN64 = sys.platform == 'win32' and sys.maxsize > 2**32
if NATIVE_WIN64:
# Visual C++ is a 32-bit application, so we need to look in
# the corresponding registry branch, if we're running a
@@ -52,13 +59,13 @@ else:
# 'vcvarsall.bat'. Note a cross-compile may combine these (eg, 'x86_amd64' is
# the param to cross-compile on x86 targeting amd64.)
PLAT_TO_VCVARS = {
- 'win32' : 'x86',
- 'win-amd64' : 'amd64',
+ 'win32': 'x86',
+ 'win-amd64': 'amd64',
}
+
class Reg:
- """Helper class to read values from the registry
- """
+ """Helper class to read values from the registry"""
def get_value(cls, path, key):
for base in HKEYS:
@@ -66,6 +73,7 @@ class Reg:
if d and key in d:
return d[key]
raise KeyError(key)
+
get_value = classmethod(get_value)
def read_keys(cls, base, key):
@@ -84,6 +92,7 @@ class Reg:
L.append(k)
i += 1
return L
+
read_keys = classmethod(read_keys)
def read_values(cls, base, key):
@@ -106,6 +115,7 @@ class Reg:
d[cls.convert_mbcs(name)] = cls.convert_mbcs(value)
i += 1
return d
+
read_values = classmethod(read_values)
def convert_mbcs(s):
@@ -116,10 +126,11 @@ class Reg:
except UnicodeError:
pass
return s
+
convert_mbcs = staticmethod(convert_mbcs)
-class MacroExpander:
+class MacroExpander:
def __init__(self, version):
self.macros = {}
self.vsbase = VS_BASE % version
@@ -134,16 +145,16 @@ class MacroExpander:
self.set_macro("FrameworkDir", NET_BASE, "installroot")
try:
if version >= 8.0:
- self.set_macro("FrameworkSDKDir", NET_BASE,
- "sdkinstallrootv2.0")
+ self.set_macro("FrameworkSDKDir", NET_BASE, "sdkinstallrootv2.0")
else:
raise KeyError("sdkinstallrootv2.0")
except KeyError:
raise DistutilsPlatformError(
- """Python was built with Visual Studio 2008;
+ """Python was built with Visual Studio 2008;
extensions must be built with a compiler than can generate compatible binaries.
Visual Studio 2008 was not found on this system. If you have Cygwin installed,
-you can try compiling with MingW32, by passing "-c mingw32" to setup.py.""")
+you can try compiling with MingW32, by passing "-c mingw32" to setup.py."""
+ )
if version >= 9.0:
self.set_macro("FrameworkVersion", self.vsbase, "clr version")
@@ -164,6 +175,7 @@ you can try compiling with MingW32, by passing "-c mingw32" to setup.py.""")
s = s.replace(k, v)
return s
+
def get_build_version():
"""Return the version of MSVC that was used to build Python.
@@ -189,6 +201,7 @@ def get_build_version():
# else we don't know what version of the compiler this is
return None
+
def normalize_and_reduce_paths(paths):
"""Return a list of normalized paths with duplicates removed.
@@ -203,9 +216,9 @@ def normalize_and_reduce_paths(paths):
reduced_paths.append(np)
return reduced_paths
+
def removeDuplicates(variable):
- """Remove duplicate values of an environment variable.
- """
+ """Remove duplicate values of an environment variable."""
oldList = variable.split(os.pathsep)
newList = []
for i in oldList:
@@ -214,6 +227,7 @@ def removeDuplicates(variable):
newVariable = os.pathsep.join(newList)
return newVariable
+
def find_vcvarsall(version):
"""Find the vcvarsall.bat file
@@ -222,8 +236,7 @@ def find_vcvarsall(version):
"""
vsbase = VS_BASE % version
try:
- productdir = Reg.get_value(r"%s\Setup\VC" % vsbase,
- "productdir")
+ productdir = Reg.get_value(r"%s\Setup\VC" % vsbase, "productdir")
except KeyError:
log.debug("Unable to find productdir in registry")
productdir = None
@@ -249,9 +262,9 @@ def find_vcvarsall(version):
log.debug("Unable to find vcvarsall.bat")
return None
+
def query_vcvarsall(version, arch="x86"):
- """Launch vcvarsall.bat and read the settings from its environment
- """
+ """Launch vcvarsall.bat and read the settings from its environment"""
vcvarsall = find_vcvarsall(version)
interesting = {"include", "lib", "libpath", "path"}
result = {}
@@ -259,9 +272,11 @@ def query_vcvarsall(version, arch="x86"):
if vcvarsall is None:
raise DistutilsPlatformError("Unable to find vcvarsall.bat")
log.debug("Calling 'vcvarsall.bat %s' (version=%s)", arch, version)
- popen = subprocess.Popen('"%s" %s & set' % (vcvarsall, arch),
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE)
+ popen = subprocess.Popen(
+ '"%s" %s & set' % (vcvarsall, arch),
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ )
try:
stdout, stderr = popen.communicate()
if popen.wait() != 0:
@@ -289,13 +304,15 @@ def query_vcvarsall(version, arch="x86"):
return result
+
# More globals
VERSION = get_build_version()
# MACROS = MacroExpander(VERSION)
-class MSVCCompiler(CCompiler) :
+
+class MSVCCompiler(CCompiler):
"""Concrete class that implements an interface to Microsoft Visual C++,
- as defined by the CCompiler abstract class."""
+ as defined by the CCompiler abstract class."""
compiler_type = 'msvc'
@@ -314,8 +331,7 @@ class MSVCCompiler(CCompiler) :
# Needed for the filename generation methods provided by the
# base class, CCompiler.
- src_extensions = (_c_extensions + _cpp_extensions +
- _rc_extensions + _mc_extensions)
+ src_extensions = _c_extensions + _cpp_extensions + _rc_extensions + _mc_extensions
res_extension = '.res'
obj_extension = '.obj'
static_lib_extension = '.lib'
@@ -331,23 +347,28 @@ class MSVCCompiler(CCompiler) :
self.__paths = []
# target platform (.plat_name is consistent with 'bdist')
self.plat_name = None
- self.__arch = None # deprecated name
+ self.__arch = None # deprecated name
self.initialized = False
def initialize(self, plat_name=None):
# multi-init means we would need to check platform same each time...
assert not self.initialized, "don't init multiple times"
if self.__version < 8.0:
- raise DistutilsPlatformError("VC %0.1f is not supported by this module" % self.__version)
+ raise DistutilsPlatformError(
+ "VC %0.1f is not supported by this module" % self.__version
+ )
if plat_name is None:
plat_name = get_platform()
# sanity check for platforms to prevent obscure errors later.
ok_plats = 'win32', 'win-amd64'
if plat_name not in ok_plats:
- raise DistutilsPlatformError("--plat-name must be one of %s" %
- (ok_plats,))
+ raise DistutilsPlatformError("--plat-name must be one of %s" % (ok_plats,))
- if "DISTUTILS_USE_SDK" in os.environ and "MSSdk" in os.environ and self.find_exe("cl.exe"):
+ if (
+ "DISTUTILS_USE_SDK" in os.environ
+ and "MSSdk" in os.environ
+ and self.find_exe("cl.exe")
+ ):
# Assume that the SDK set up everything alright; don't try to be
# smarter
self.cc = "cl.exe"
@@ -365,8 +386,9 @@ class MSVCCompiler(CCompiler) :
plat_spec = PLAT_TO_VCVARS[plat_name]
else:
# cross compile from win32 -> some 64bit
- plat_spec = PLAT_TO_VCVARS[get_platform()] + '_' + \
- PLAT_TO_VCVARS[plat_name]
+ plat_spec = (
+ PLAT_TO_VCVARS[get_platform()] + '_' + PLAT_TO_VCVARS[plat_name]
+ )
vc_env = query_vcvarsall(VERSION, plat_spec)
@@ -375,18 +397,19 @@ class MSVCCompiler(CCompiler) :
os.environ['include'] = vc_env['include']
if len(self.__paths) == 0:
- raise DistutilsPlatformError("Python was built with %s, "
- "and extensions need to be built with the same "
- "version of the compiler, but it isn't installed."
- % self.__product)
+ raise DistutilsPlatformError(
+ "Python was built with %s, "
+ "and extensions need to be built with the same "
+ "version of the compiler, but it isn't installed." % self.__product
+ )
self.cc = self.find_exe("cl.exe")
self.linker = self.find_exe("link.exe")
self.lib = self.find_exe("lib.exe")
- self.rc = self.find_exe("rc.exe") # resource compiler
- self.mc = self.find_exe("mc.exe") # message compiler
- #self.set_path_env_var('lib')
- #self.set_path_env_var('include')
+ self.rc = self.find_exe("rc.exe") # resource compiler
+ self.mc = self.find_exe("mc.exe") # message compiler
+ # self.set_path_env_var('lib')
+ # self.set_path_env_var('include')
# extend the MSVC path with the current path
try:
@@ -399,71 +422,83 @@ class MSVCCompiler(CCompiler) :
self.preprocess_options = None
if self.__arch == "x86":
- self.compile_options = [ '/nologo', '/O2', '/MD', '/W3',
- '/DNDEBUG']
- self.compile_options_debug = ['/nologo', '/Od', '/MDd', '/W3',
- '/Z7', '/D_DEBUG']
+ self.compile_options = ['/nologo', '/O2', '/MD', '/W3', '/DNDEBUG']
+ self.compile_options_debug = [
+ '/nologo',
+ '/Od',
+ '/MDd',
+ '/W3',
+ '/Z7',
+ '/D_DEBUG',
+ ]
else:
# Win64
- self.compile_options = [ '/nologo', '/O2', '/MD', '/W3', '/GS-' ,
- '/DNDEBUG']
- self.compile_options_debug = ['/nologo', '/Od', '/MDd', '/W3', '/GS-',
- '/Z7', '/D_DEBUG']
+ self.compile_options = ['/nologo', '/O2', '/MD', '/W3', '/GS-', '/DNDEBUG']
+ self.compile_options_debug = [
+ '/nologo',
+ '/Od',
+ '/MDd',
+ '/W3',
+ '/GS-',
+ '/Z7',
+ '/D_DEBUG',
+ ]
self.ldflags_shared = ['/DLL', '/nologo', '/INCREMENTAL:NO']
if self.__version >= 7:
- self.ldflags_shared_debug = [
- '/DLL', '/nologo', '/INCREMENTAL:no', '/DEBUG'
- ]
- self.ldflags_static = [ '/nologo']
+ self.ldflags_shared_debug = ['/DLL', '/nologo', '/INCREMENTAL:no', '/DEBUG']
+ self.ldflags_static = ['/nologo']
self.initialized = True
# -- Worker methods ------------------------------------------------
- def object_filenames(self,
- source_filenames,
- strip_dir=0,
- output_dir=''):
+ def object_filenames(self, source_filenames, strip_dir=0, output_dir=''):
# Copied from ccompiler.py, extended to return .res as 'object'-file
# for .rc input file
- if output_dir is None: output_dir = ''
+ if output_dir is None:
+ output_dir = ''
obj_names = []
for src_name in source_filenames:
- (base, ext) = os.path.splitext (src_name)
- base = os.path.splitdrive(base)[1] # Chop off the drive
- base = base[os.path.isabs(base):] # If abs, chop off leading /
+ (base, ext) = os.path.splitext(src_name)
+ base = os.path.splitdrive(base)[1] # Chop off the drive
+ base = base[os.path.isabs(base) :] # If abs, chop off leading /
if ext not in self.src_extensions:
# Better to raise an exception instead of silently continuing
# and later complain about sources and targets having
# different lengths
- raise CompileError ("Don't know how to compile %s" % src_name)
+ raise CompileError("Don't know how to compile %s" % src_name)
if strip_dir:
- base = os.path.basename (base)
+ base = os.path.basename(base)
if ext in self._rc_extensions:
- obj_names.append (os.path.join (output_dir,
- base + self.res_extension))
+ obj_names.append(os.path.join(output_dir, base + self.res_extension))
elif ext in self._mc_extensions:
- obj_names.append (os.path.join (output_dir,
- base + self.res_extension))
+ obj_names.append(os.path.join(output_dir, base + self.res_extension))
else:
- obj_names.append (os.path.join (output_dir,
- base + self.obj_extension))
+ obj_names.append(os.path.join(output_dir, base + self.obj_extension))
return obj_names
-
- def compile(self, sources,
- output_dir=None, macros=None, include_dirs=None, debug=0,
- extra_preargs=None, extra_postargs=None, depends=None):
+ def compile(
+ self,
+ sources,
+ output_dir=None,
+ macros=None,
+ include_dirs=None,
+ debug=0,
+ extra_preargs=None,
+ extra_postargs=None,
+ depends=None,
+ ):
if not self.initialized:
self.initialize()
- compile_info = self._setup_compile(output_dir, macros, include_dirs,
- sources, depends, extra_postargs)
+ compile_info = self._setup_compile(
+ output_dir, macros, include_dirs, sources, depends, extra_postargs
+ )
macros, objects, extra_postargs, pp_opts, build = compile_info
compile_opts = extra_preargs or []
- compile_opts.append ('/c')
+ compile_opts.append('/c')
if debug:
compile_opts.extend(self.compile_options_debug)
else:
@@ -489,8 +524,7 @@ class MSVCCompiler(CCompiler) :
input_opt = src
output_opt = "/fo" + obj
try:
- self.spawn([self.rc] + pp_opts +
- [output_opt] + [input_opt])
+ self.spawn([self.rc] + pp_opts + [output_opt] + [input_opt])
except DistutilsExecError as msg:
raise CompileError(msg)
continue
@@ -510,50 +544,46 @@ class MSVCCompiler(CCompiler) :
rc_dir = os.path.dirname(obj)
try:
# first compile .MC to .RC and .H file
- self.spawn([self.mc] +
- ['-h', h_dir, '-r', rc_dir] + [src])
- base, _ = os.path.splitext (os.path.basename (src))
- rc_file = os.path.join (rc_dir, base + '.rc')
+ self.spawn([self.mc] + ['-h', h_dir, '-r', rc_dir] + [src])
+ base, _ = os.path.splitext(os.path.basename(src))
+ rc_file = os.path.join(rc_dir, base + '.rc')
# then compile .RC to .RES file
- self.spawn([self.rc] +
- ["/fo" + obj] + [rc_file])
+ self.spawn([self.rc] + ["/fo" + obj] + [rc_file])
except DistutilsExecError as msg:
raise CompileError(msg)
continue
else:
# how to handle this file?
- raise CompileError("Don't know how to compile %s to %s"
- % (src, obj))
+ raise CompileError("Don't know how to compile %s to %s" % (src, obj))
output_opt = "/Fo" + obj
try:
- self.spawn([self.cc] + compile_opts + pp_opts +
- [input_opt, output_opt] +
- extra_postargs)
+ self.spawn(
+ [self.cc]
+ + compile_opts
+ + pp_opts
+ + [input_opt, output_opt]
+ + extra_postargs
+ )
except DistutilsExecError as msg:
raise CompileError(msg)
return objects
-
- def create_static_lib(self,
- objects,
- output_libname,
- output_dir=None,
- debug=0,
- target_lang=None):
+ def create_static_lib(
+ self, objects, output_libname, output_dir=None, debug=0, target_lang=None
+ ):
if not self.initialized:
self.initialize()
(objects, output_dir) = self._fix_object_args(objects, output_dir)
- output_filename = self.library_filename(output_libname,
- output_dir=output_dir)
+ output_filename = self.library_filename(output_libname, output_dir=output_dir)
if self._need_link(objects, output_filename):
lib_args = objects + ['/OUT:' + output_filename]
if debug:
- pass # XXX what goes here?
+ pass # XXX what goes here?
try:
self.spawn([self.lib] + lib_args)
except DistutilsExecError as msg:
@@ -561,36 +591,36 @@ class MSVCCompiler(CCompiler) :
else:
log.debug("skipping %s (up-to-date)", output_filename)
-
- def link(self,
- target_desc,
- objects,
- output_filename,
- output_dir=None,
- libraries=None,
- library_dirs=None,
- runtime_library_dirs=None,
- export_symbols=None,
- debug=0,
- extra_preargs=None,
- extra_postargs=None,
- build_temp=None,
- target_lang=None):
+ def link(
+ self,
+ target_desc,
+ objects,
+ output_filename,
+ output_dir=None,
+ libraries=None,
+ library_dirs=None,
+ runtime_library_dirs=None,
+ export_symbols=None,
+ debug=0,
+ extra_preargs=None,
+ extra_postargs=None,
+ build_temp=None,
+ target_lang=None,
+ ):
if not self.initialized:
self.initialize()
(objects, output_dir) = self._fix_object_args(objects, output_dir)
- fixed_args = self._fix_lib_args(libraries, library_dirs,
- runtime_library_dirs)
+ fixed_args = self._fix_lib_args(libraries, library_dirs, runtime_library_dirs)
(libraries, library_dirs, runtime_library_dirs) = fixed_args
if runtime_library_dirs:
- self.warn ("I don't know what to do with 'runtime_library_dirs': "
- + str (runtime_library_dirs))
+ self.warn(
+ "I don't know what to do with 'runtime_library_dirs': "
+ + str(runtime_library_dirs)
+ )
- lib_opts = gen_lib_options(self,
- library_dirs, runtime_library_dirs,
- libraries)
+ lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, libraries)
if output_dir is not None:
output_filename = os.path.join(output_dir, output_filename)
@@ -607,11 +637,12 @@ class MSVCCompiler(CCompiler) :
ldflags = self.ldflags_shared
export_opts = []
- for sym in (export_symbols or []):
+ for sym in export_symbols or []:
export_opts.append("/EXPORT:" + sym)
- ld_args = (ldflags + lib_opts + export_opts +
- objects + ['/OUT:' + output_filename])
+ ld_args = (
+ ldflags + lib_opts + export_opts + objects + ['/OUT:' + output_filename]
+ )
# The MSVC linker generates .lib and .exp files, which cannot be
# suppressed by any linker switches. The .lib files may even be
@@ -621,11 +652,10 @@ class MSVCCompiler(CCompiler) :
build_temp = os.path.dirname(objects[0])
if export_symbols is not None:
(dll_name, dll_ext) = os.path.splitext(
- os.path.basename(output_filename))
- implib_file = os.path.join(
- build_temp,
- self.library_filename(dll_name))
- ld_args.append ('/IMPLIB:' + implib_file)
+ os.path.basename(output_filename)
+ )
+ implib_file = os.path.join(build_temp, self.library_filename(dll_name))
+ ld_args.append('/IMPLIB:' + implib_file)
self.manifest_setup_ldargs(output_filename, build_temp, ld_args)
@@ -650,8 +680,7 @@ class MSVCCompiler(CCompiler) :
mffilename, mfid = mfinfo
out_arg = '-outputresource:%s;%s' % (output_filename, mfid)
try:
- self.spawn(['mt.exe', '-nologo', '-manifest',
- mffilename, out_arg])
+ self.spawn(['mt.exe', '-nologo', '-manifest', mffilename, out_arg])
except DistutilsExecError as msg:
raise LinkError(msg)
else:
@@ -665,8 +694,8 @@ class MSVCCompiler(CCompiler) :
# Ask the linker to generate the manifest in the temp dir, so
# we can check it, and possibly embed it, later.
temp_manifest = os.path.join(
- build_temp,
- os.path.basename(output_filename) + ".manifest")
+ build_temp, os.path.basename(output_filename) + ".manifest"
+ )
ld_args.append('/MANIFESTFILE:' + temp_manifest)
def manifest_get_embed_info(self, target_desc, ld_args):
@@ -709,9 +738,10 @@ class MSVCCompiler(CCompiler) :
finally:
manifest_f.close()
pattern = re.compile(
- r"""<assemblyIdentity.*?name=("|')Microsoft\."""\
+ r"""<assemblyIdentity.*?name=("|')Microsoft\."""
r"""VC\d{2}\.CRT("|').*?(/>|</assemblyIdentity>)""",
- re.DOTALL)
+ re.DOTALL,
+ )
manifest_buf = re.sub(pattern, "", manifest_buf)
pattern = r"<dependentAssembly>\s*</dependentAssembly>"
manifest_buf = re.sub(pattern, "", manifest_buf)
@@ -719,7 +749,9 @@ class MSVCCompiler(CCompiler) :
# don't want a manifest embedded.
pattern = re.compile(
r"""<assemblyIdentity.*?name=(?:"|')(.+?)(?:"|')"""
- r""".*?(?:/>|</assemblyIdentity>)""", re.DOTALL)
+ r""".*?(?:/>|</assemblyIdentity>)""",
+ re.DOTALL,
+ )
if re.search(pattern, manifest_buf) is None:
return None
@@ -741,12 +773,12 @@ class MSVCCompiler(CCompiler) :
def runtime_library_dir_option(self, dir):
raise DistutilsPlatformError(
- "don't know how to set runtime library search path for MSVC++")
+ "don't know how to set runtime library search path for MSVC++"
+ )
def library_option(self, lib):
return self.library_filename(lib)
-
def find_library_file(self, dirs, lib, debug=0):
# Prefer a debugging library if found (and requested), but deal
# with it if we don't have one.
@@ -756,7 +788,7 @@ class MSVCCompiler(CCompiler) :
try_names = [lib]
for dir in dirs:
for name in try_names:
- libfile = os.path.join(dir, self.library_filename (name))
+ libfile = os.path.join(dir, self.library_filename(name))
if os.path.exists(libfile):
return libfile
else:
@@ -781,7 +813,7 @@ class MSVCCompiler(CCompiler) :
# didn't find it; try existing path
for p in os.environ['Path'].split(';'):
- fn = os.path.join(os.path.abspath(p),exe)
+ fn = os.path.join(os.path.abspath(p), exe)
if os.path.isfile(fn):
return fn
diff --git a/setuptools/_distutils/msvccompiler.py b/setuptools/_distutils/msvccompiler.py
index e1367b89..00c630be 100644
--- a/setuptools/_distutils/msvccompiler.py
+++ b/setuptools/_distutils/msvccompiler.py
@@ -9,11 +9,14 @@ for the Microsoft Visual Studio.
# finding DevStudio (through the registry)
import sys, os
-from distutils.errors import \
- DistutilsExecError, DistutilsPlatformError, \
- CompileError, LibError, LinkError
-from distutils.ccompiler import \
- CCompiler, gen_lib_options
+from distutils.errors import (
+ DistutilsExecError,
+ DistutilsPlatformError,
+ CompileError,
+ LibError,
+ LinkError,
+)
+from distutils.ccompiler import CCompiler, gen_lib_options
from distutils import log
_can_read_reg = False
@@ -32,6 +35,7 @@ except ImportError:
try:
import win32api
import win32con
+
_can_read_reg = True
hkey_mod = win32con
@@ -40,17 +44,22 @@ except ImportError:
RegEnumValue = win32api.RegEnumValue
RegError = win32api.error
except ImportError:
- log.info("Warning: Can't read registry to find the "
- "necessary compiler setting\n"
- "Make sure that Python modules winreg, "
- "win32api or win32con are installed.")
+ log.info(
+ "Warning: Can't read registry to find the "
+ "necessary compiler setting\n"
+ "Make sure that Python modules winreg, "
+ "win32api or win32con are installed."
+ )
pass
if _can_read_reg:
- HKEYS = (hkey_mod.HKEY_USERS,
- hkey_mod.HKEY_CURRENT_USER,
- hkey_mod.HKEY_LOCAL_MACHINE,
- hkey_mod.HKEY_CLASSES_ROOT)
+ HKEYS = (
+ hkey_mod.HKEY_USERS,
+ hkey_mod.HKEY_CURRENT_USER,
+ hkey_mod.HKEY_LOCAL_MACHINE,
+ hkey_mod.HKEY_CLASSES_ROOT,
+ )
+
def read_keys(base, key):
"""Return list of registry keys."""
@@ -69,6 +78,7 @@ def read_keys(base, key):
i += 1
return L
+
def read_values(base, key):
"""Return dict of registry keys and values.
@@ -90,6 +100,7 @@ def read_values(base, key):
i += 1
return d
+
def convert_mbcs(s):
dec = getattr(s, "decode", None)
if dec is not None:
@@ -99,6 +110,7 @@ def convert_mbcs(s):
pass
return s
+
class MacroExpander:
def __init__(self, version):
self.macros = {}
@@ -122,12 +134,13 @@ class MacroExpander:
self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv1.1")
else:
self.set_macro("FrameworkSDKDir", net, "sdkinstallroot")
- except KeyError as exc: #
+ except KeyError as exc: #
raise DistutilsPlatformError(
- """Python was built with Visual Studio 2003;
+ """Python was built with Visual Studio 2003;
extensions must be built with a compiler than can generate compatible binaries.
Visual Studio 2003 was not found on this system. If you have Cygwin installed,
-you can try compiling with MingW32, by passing "-c mingw32" to setup.py.""")
+you can try compiling with MingW32, by passing "-c mingw32" to setup.py."""
+ )
p = r"Software\Microsoft\NET Framework Setup\Product"
for base in HKEYS:
@@ -144,6 +157,7 @@ you can try compiling with MingW32, by passing "-c mingw32" to setup.py.""")
s = s.replace(k, v)
return s
+
def get_build_version():
"""Return the version of MSVC that was used to build Python.
@@ -169,6 +183,7 @@ def get_build_version():
# else we don't know what version of the compiler this is
return None
+
def get_build_architecture():
"""Return the processor architecture.
@@ -180,7 +195,8 @@ def get_build_architecture():
if i == -1:
return "Intel"
j = sys.version.find(")", i)
- return sys.version[i+len(prefix):j]
+ return sys.version[i + len(prefix) : j]
+
def normalize_and_reduce_paths(paths):
"""Return a list of normalized paths with duplicates removed.
@@ -197,9 +213,9 @@ def normalize_and_reduce_paths(paths):
return reduced_paths
-class MSVCCompiler(CCompiler) :
+class MSVCCompiler(CCompiler):
"""Concrete class that implements an interface to Microsoft Visual C++,
- as defined by the CCompiler abstract class."""
+ as defined by the CCompiler abstract class."""
compiler_type = 'msvc'
@@ -218,8 +234,7 @@ class MSVCCompiler(CCompiler) :
# Needed for the filename generation methods provided by the
# base class, CCompiler.
- src_extensions = (_c_extensions + _cpp_extensions +
- _rc_extensions + _mc_extensions)
+ src_extensions = _c_extensions + _cpp_extensions + _rc_extensions + _mc_extensions
res_extension = '.res'
obj_extension = '.obj'
static_lib_extension = '.lib'
@@ -247,7 +262,11 @@ class MSVCCompiler(CCompiler) :
def initialize(self):
self.__paths = []
- if "DISTUTILS_USE_SDK" in os.environ and "MSSdk" in os.environ and self.find_exe("cl.exe"):
+ if (
+ "DISTUTILS_USE_SDK" in os.environ
+ and "MSSdk" in os.environ
+ and self.find_exe("cl.exe")
+ ):
# Assume that the SDK set up everything alright; don't try to be
# smarter
self.cc = "cl.exe"
@@ -259,16 +278,17 @@ class MSVCCompiler(CCompiler) :
self.__paths = self.get_msvc_paths("path")
if len(self.__paths) == 0:
- raise DistutilsPlatformError("Python was built with %s, "
- "and extensions need to be built with the same "
- "version of the compiler, but it isn't installed."
- % self.__product)
+ raise DistutilsPlatformError(
+ "Python was built with %s, "
+ "and extensions need to be built with the same "
+ "version of the compiler, but it isn't installed." % self.__product
+ )
self.cc = self.find_exe("cl.exe")
self.linker = self.find_exe("link.exe")
self.lib = self.find_exe("lib.exe")
- self.rc = self.find_exe("rc.exe") # resource compiler
- self.mc = self.find_exe("mc.exe") # message compiler
+ self.rc = self.find_exe("rc.exe") # resource compiler
+ self.mc = self.find_exe("mc.exe") # message compiler
self.set_path_env_var('lib')
self.set_path_env_var('include')
@@ -283,75 +303,92 @@ class MSVCCompiler(CCompiler) :
self.preprocess_options = None
if self.__arch == "Intel":
- self.compile_options = [ '/nologo', '/O2', '/MD', '/W3', '/GX' ,
- '/DNDEBUG']
- self.compile_options_debug = ['/nologo', '/Od', '/MDd', '/W3', '/GX',
- '/Z7', '/D_DEBUG']
+ self.compile_options = ['/nologo', '/O2', '/MD', '/W3', '/GX', '/DNDEBUG']
+ self.compile_options_debug = [
+ '/nologo',
+ '/Od',
+ '/MDd',
+ '/W3',
+ '/GX',
+ '/Z7',
+ '/D_DEBUG',
+ ]
else:
# Win64
- self.compile_options = [ '/nologo', '/O2', '/MD', '/W3', '/GS-' ,
- '/DNDEBUG']
- self.compile_options_debug = ['/nologo', '/Od', '/MDd', '/W3', '/GS-',
- '/Z7', '/D_DEBUG']
+ self.compile_options = ['/nologo', '/O2', '/MD', '/W3', '/GS-', '/DNDEBUG']
+ self.compile_options_debug = [
+ '/nologo',
+ '/Od',
+ '/MDd',
+ '/W3',
+ '/GS-',
+ '/Z7',
+ '/D_DEBUG',
+ ]
self.ldflags_shared = ['/DLL', '/nologo', '/INCREMENTAL:NO']
if self.__version >= 7:
- self.ldflags_shared_debug = [
- '/DLL', '/nologo', '/INCREMENTAL:no', '/DEBUG'
- ]
+ self.ldflags_shared_debug = ['/DLL', '/nologo', '/INCREMENTAL:no', '/DEBUG']
else:
self.ldflags_shared_debug = [
- '/DLL', '/nologo', '/INCREMENTAL:no', '/pdb:None', '/DEBUG'
- ]
- self.ldflags_static = [ '/nologo']
+ '/DLL',
+ '/nologo',
+ '/INCREMENTAL:no',
+ '/pdb:None',
+ '/DEBUG',
+ ]
+ self.ldflags_static = ['/nologo']
self.initialized = True
# -- Worker methods ------------------------------------------------
- def object_filenames(self,
- source_filenames,
- strip_dir=0,
- output_dir=''):
+ def object_filenames(self, source_filenames, strip_dir=0, output_dir=''):
# Copied from ccompiler.py, extended to return .res as 'object'-file
# for .rc input file
- if output_dir is None: output_dir = ''
+ if output_dir is None:
+ output_dir = ''
obj_names = []
for src_name in source_filenames:
- (base, ext) = os.path.splitext (src_name)
- base = os.path.splitdrive(base)[1] # Chop off the drive
- base = base[os.path.isabs(base):] # If abs, chop off leading /
+ (base, ext) = os.path.splitext(src_name)
+ base = os.path.splitdrive(base)[1] # Chop off the drive
+ base = base[os.path.isabs(base) :] # If abs, chop off leading /
if ext not in self.src_extensions:
# Better to raise an exception instead of silently continuing
# and later complain about sources and targets having
# different lengths
- raise CompileError ("Don't know how to compile %s" % src_name)
+ raise CompileError("Don't know how to compile %s" % src_name)
if strip_dir:
- base = os.path.basename (base)
+ base = os.path.basename(base)
if ext in self._rc_extensions:
- obj_names.append (os.path.join (output_dir,
- base + self.res_extension))
+ obj_names.append(os.path.join(output_dir, base + self.res_extension))
elif ext in self._mc_extensions:
- obj_names.append (os.path.join (output_dir,
- base + self.res_extension))
+ obj_names.append(os.path.join(output_dir, base + self.res_extension))
else:
- obj_names.append (os.path.join (output_dir,
- base + self.obj_extension))
+ obj_names.append(os.path.join(output_dir, base + self.obj_extension))
return obj_names
-
- def compile(self, sources,
- output_dir=None, macros=None, include_dirs=None, debug=0,
- extra_preargs=None, extra_postargs=None, depends=None):
+ def compile(
+ self,
+ sources,
+ output_dir=None,
+ macros=None,
+ include_dirs=None,
+ debug=0,
+ extra_preargs=None,
+ extra_postargs=None,
+ depends=None,
+ ):
if not self.initialized:
self.initialize()
- compile_info = self._setup_compile(output_dir, macros, include_dirs,
- sources, depends, extra_postargs)
+ compile_info = self._setup_compile(
+ output_dir, macros, include_dirs, sources, depends, extra_postargs
+ )
macros, objects, extra_postargs, pp_opts, build = compile_info
compile_opts = extra_preargs or []
- compile_opts.append ('/c')
+ compile_opts.append('/c')
if debug:
compile_opts.extend(self.compile_options_debug)
else:
@@ -377,8 +414,7 @@ class MSVCCompiler(CCompiler) :
input_opt = src
output_opt = "/fo" + obj
try:
- self.spawn([self.rc] + pp_opts +
- [output_opt] + [input_opt])
+ self.spawn([self.rc] + pp_opts + [output_opt] + [input_opt])
except DistutilsExecError as msg:
raise CompileError(msg)
continue
@@ -398,50 +434,46 @@ class MSVCCompiler(CCompiler) :
rc_dir = os.path.dirname(obj)
try:
# first compile .MC to .RC and .H file
- self.spawn([self.mc] +
- ['-h', h_dir, '-r', rc_dir] + [src])
- base, _ = os.path.splitext (os.path.basename (src))
- rc_file = os.path.join (rc_dir, base + '.rc')
+ self.spawn([self.mc] + ['-h', h_dir, '-r', rc_dir] + [src])
+ base, _ = os.path.splitext(os.path.basename(src))
+ rc_file = os.path.join(rc_dir, base + '.rc')
# then compile .RC to .RES file
- self.spawn([self.rc] +
- ["/fo" + obj] + [rc_file])
+ self.spawn([self.rc] + ["/fo" + obj] + [rc_file])
except DistutilsExecError as msg:
raise CompileError(msg)
continue
else:
# how to handle this file?
- raise CompileError("Don't know how to compile %s to %s"
- % (src, obj))
+ raise CompileError("Don't know how to compile %s to %s" % (src, obj))
output_opt = "/Fo" + obj
try:
- self.spawn([self.cc] + compile_opts + pp_opts +
- [input_opt, output_opt] +
- extra_postargs)
+ self.spawn(
+ [self.cc]
+ + compile_opts
+ + pp_opts
+ + [input_opt, output_opt]
+ + extra_postargs
+ )
except DistutilsExecError as msg:
raise CompileError(msg)
return objects
-
- def create_static_lib(self,
- objects,
- output_libname,
- output_dir=None,
- debug=0,
- target_lang=None):
+ def create_static_lib(
+ self, objects, output_libname, output_dir=None, debug=0, target_lang=None
+ ):
if not self.initialized:
self.initialize()
(objects, output_dir) = self._fix_object_args(objects, output_dir)
- output_filename = self.library_filename(output_libname,
- output_dir=output_dir)
+ output_filename = self.library_filename(output_libname, output_dir=output_dir)
if self._need_link(objects, output_filename):
lib_args = objects + ['/OUT:' + output_filename]
if debug:
- pass # XXX what goes here?
+ pass # XXX what goes here?
try:
self.spawn([self.lib] + lib_args)
except DistutilsExecError as msg:
@@ -449,36 +481,36 @@ class MSVCCompiler(CCompiler) :
else:
log.debug("skipping %s (up-to-date)", output_filename)
-
- def link(self,
- target_desc,
- objects,
- output_filename,
- output_dir=None,
- libraries=None,
- library_dirs=None,
- runtime_library_dirs=None,
- export_symbols=None,
- debug=0,
- extra_preargs=None,
- extra_postargs=None,
- build_temp=None,
- target_lang=None):
+ def link(
+ self,
+ target_desc,
+ objects,
+ output_filename,
+ output_dir=None,
+ libraries=None,
+ library_dirs=None,
+ runtime_library_dirs=None,
+ export_symbols=None,
+ debug=0,
+ extra_preargs=None,
+ extra_postargs=None,
+ build_temp=None,
+ target_lang=None,
+ ):
if not self.initialized:
self.initialize()
(objects, output_dir) = self._fix_object_args(objects, output_dir)
- fixed_args = self._fix_lib_args(libraries, library_dirs,
- runtime_library_dirs)
+ fixed_args = self._fix_lib_args(libraries, library_dirs, runtime_library_dirs)
(libraries, library_dirs, runtime_library_dirs) = fixed_args
if runtime_library_dirs:
- self.warn ("I don't know what to do with 'runtime_library_dirs': "
- + str (runtime_library_dirs))
+ self.warn(
+ "I don't know what to do with 'runtime_library_dirs': "
+ + str(runtime_library_dirs)
+ )
- lib_opts = gen_lib_options(self,
- library_dirs, runtime_library_dirs,
- libraries)
+ lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, libraries)
if output_dir is not None:
output_filename = os.path.join(output_dir, output_filename)
@@ -495,11 +527,12 @@ class MSVCCompiler(CCompiler) :
ldflags = self.ldflags_shared
export_opts = []
- for sym in (export_symbols or []):
+ for sym in export_symbols or []:
export_opts.append("/EXPORT:" + sym)
- ld_args = (ldflags + lib_opts + export_opts +
- objects + ['/OUT:' + output_filename])
+ ld_args = (
+ ldflags + lib_opts + export_opts + objects + ['/OUT:' + output_filename]
+ )
# The MSVC linker generates .lib and .exp files, which cannot be
# suppressed by any linker switches. The .lib files may even be
@@ -508,11 +541,12 @@ class MSVCCompiler(CCompiler) :
# builds, they can go into the same directory.
if export_symbols is not None:
(dll_name, dll_ext) = os.path.splitext(
- os.path.basename(output_filename))
+ os.path.basename(output_filename)
+ )
implib_file = os.path.join(
- os.path.dirname(objects[0]),
- self.library_filename(dll_name))
- ld_args.append ('/IMPLIB:' + implib_file)
+ os.path.dirname(objects[0]), self.library_filename(dll_name)
+ )
+ ld_args.append('/IMPLIB:' + implib_file)
if extra_preargs:
ld_args[:0] = extra_preargs
@@ -528,7 +562,6 @@ class MSVCCompiler(CCompiler) :
else:
log.debug("skipping %s (up-to-date)", output_filename)
-
# -- Miscellaneous methods -----------------------------------------
# These are all used by the 'gen_lib_options() function, in
# ccompiler.py.
@@ -538,12 +571,12 @@ class MSVCCompiler(CCompiler) :
def runtime_library_dir_option(self, dir):
raise DistutilsPlatformError(
- "don't know how to set runtime library search path for MSVC++")
+ "don't know how to set runtime library search path for MSVC++"
+ )
def library_option(self, lib):
return self.library_filename(lib)
-
def find_library_file(self, dirs, lib, debug=0):
# Prefer a debugging library if found (and requested), but deal
# with it if we don't have one.
@@ -553,7 +586,7 @@ class MSVCCompiler(CCompiler) :
try_names = [lib]
for dir in dirs:
for name in try_names:
- libfile = os.path.join(dir, self.library_filename (name))
+ libfile = os.path.join(dir, self.library_filename(name))
if os.path.exists(libfile):
return libfile
else:
@@ -578,7 +611,7 @@ class MSVCCompiler(CCompiler) :
# didn't find it; try existing path
for p in os.environ['Path'].split(';'):
- fn = os.path.join(os.path.abspath(p),exe)
+ fn = os.path.join(os.path.abspath(p), exe)
if os.path.isfile(fn):
return fn
@@ -595,11 +628,15 @@ class MSVCCompiler(CCompiler) :
path = path + " dirs"
if self.__version >= 7:
- key = (r"%s\%0.1f\VC\VC_OBJECTS_PLATFORM_INFO\Win32\Directories"
- % (self.__root, self.__version))
+ key = r"%s\%0.1f\VC\VC_OBJECTS_PLATFORM_INFO\Win32\Directories" % (
+ self.__root,
+ self.__version,
+ )
else:
- key = (r"%s\6.0\Build System\Components\Platforms"
- r"\Win32 (%s)\Directories" % (self.__root, platform))
+ key = (
+ r"%s\6.0\Build System\Components\Platforms"
+ r"\Win32 (%s)\Directories" % (self.__root, platform)
+ )
for base in HKEYS:
d = read_values(base, key)
@@ -613,10 +650,12 @@ class MSVCCompiler(CCompiler) :
if self.__version == 6:
for base in HKEYS:
if read_values(base, r"%s\6.0" % self.__root) is not None:
- self.warn("It seems you have Visual Studio 6 installed, "
+ self.warn(
+ "It seems you have Visual Studio 6 installed, "
"but the expected registry settings are not present.\n"
"You must at least run the Visual Studio GUI once "
- "so that these entries are created.")
+ "so that these entries are created."
+ )
break
return []
@@ -639,5 +678,6 @@ if get_build_version() >= 8.0:
log.debug("Importing new compiler from distutils.msvc9compiler")
OldMSVCCompiler = MSVCCompiler
from distutils.msvc9compiler import MSVCCompiler
+
# get_build_architecture not really relevant now we support cross-compile
from distutils.msvc9compiler import MacroExpander
diff --git a/setuptools/_distutils/py35compat.py b/setuptools/_distutils/py35compat.py
deleted file mode 100644
index 79b2e7f3..00000000
--- a/setuptools/_distutils/py35compat.py
+++ /dev/null
@@ -1,19 +0,0 @@
-import sys
-import subprocess
-
-
-def __optim_args_from_interpreter_flags():
- """Return a list of command-line arguments reproducing the current
- optimization settings in sys.flags."""
- args = []
- value = sys.flags.optimize
- if value > 0:
- args.append("-" + "O" * value)
- return args
-
-
-_optim_args_from_interpreter_flags = getattr(
- subprocess,
- "_optim_args_from_interpreter_flags",
- __optim_args_from_interpreter_flags,
-)
diff --git a/setuptools/_distutils/py38compat.py b/setuptools/_distutils/py38compat.py
index 7dbe8cef..e556b69e 100644
--- a/setuptools/_distutils/py38compat.py
+++ b/setuptools/_distutils/py38compat.py
@@ -1,6 +1,7 @@
def aix_platform(osname, version, release):
try:
import _aix_support
+
return _aix_support.aix_platform()
except ImportError:
pass
diff --git a/setuptools/_distutils/py39compat.py b/setuptools/_distutils/py39compat.py
index 9de95013..c43e5f10 100644
--- a/setuptools/_distutils/py39compat.py
+++ b/setuptools/_distutils/py39compat.py
@@ -7,6 +7,7 @@ def add_ext_suffix_39(vars):
Ensure vars contains 'EXT_SUFFIX'. pypa/distutils#130
"""
import _imp
+
ext_suffix = _imp.extension_suffixes()[0]
vars.update(
EXT_SUFFIX=ext_suffix,
diff --git a/setuptools/_distutils/spawn.py b/setuptools/_distutils/spawn.py
index b2d10e39..acd20148 100644
--- a/setuptools/_distutils/spawn.py
+++ b/setuptools/_distutils/spawn.py
@@ -48,6 +48,7 @@ def spawn(cmd, search_path=1, verbose=0, dry_run=0, env=None):
if sys.platform == 'darwin':
from distutils.util import MACOSX_VERSION_VAR, get_macosx_target_ver
+
macosx_target_ver = get_macosx_target_ver()
if macosx_target_ver:
env[MACOSX_VERSION_VAR] = macosx_target_ver
@@ -59,14 +60,14 @@ def spawn(cmd, search_path=1, verbose=0, dry_run=0, env=None):
except OSError as exc:
if not DEBUG:
cmd = cmd[0]
- raise DistutilsExecError(
- "command %r failed: %s" % (cmd, exc.args[-1])) from exc
+ raise DistutilsExecError("command %r failed: %s" % (cmd, exc.args[-1])) from exc
if exitcode:
if not DEBUG:
cmd = cmd[0]
raise DistutilsExecError(
- "command %r failed with exit code %s" % (cmd, exitcode))
+ "command %r failed with exit code %s" % (cmd, exitcode)
+ )
def find_executable(executable, path=None):
diff --git a/setuptools/_distutils/sysconfig.py b/setuptools/_distutils/sysconfig.py
index 55a42e16..e41d51ee 100644
--- a/setuptools/_distutils/sysconfig.py
+++ b/setuptools/_distutils/sysconfig.py
@@ -16,6 +16,7 @@ import sysconfig
from .errors import DistutilsPlatformError
from . import py39compat
+from ._functools import pass_none
IS_PYPY = '__pypy__' in sys.builtin_module_names
@@ -51,12 +52,27 @@ def _is_python_source_dir(d):
_sys_home = getattr(sys, '_home', None)
+
+def _is_parent(dir_a, dir_b):
+ """
+ Return True if a is a parent of b.
+ """
+ return os.path.normcase(dir_a).startswith(os.path.normcase(dir_b))
+
+
if os.name == 'nt':
+
+ @pass_none
def _fix_pcbuild(d):
- if d and os.path.normcase(d).startswith(
- os.path.normcase(os.path.join(PREFIX, "PCbuild"))):
- return PREFIX
- return d
+ # In a venv, sys._home will be inside BASE_PREFIX rather than PREFIX.
+ prefixes = PREFIX, BASE_PREFIX
+ matched = (
+ prefix
+ for prefix in prefixes
+ if _is_parent(d, os.path.join(prefix, "PCbuild"))
+ )
+ return next(matched, d)
+
project_base = _fix_pcbuild(project_base)
_sys_home = _fix_pcbuild(_sys_home)
@@ -102,36 +118,74 @@ def get_python_inc(plat_specific=0, prefix=None):
If 'prefix' is supplied, use it instead of sys.base_prefix or
sys.base_exec_prefix -- i.e., ignore 'plat_specific'.
"""
- if prefix is None:
- prefix = plat_specific and BASE_EXEC_PREFIX or BASE_PREFIX
- if os.name == "posix":
- if IS_PYPY and sys.version_info < (3, 8):
- return os.path.join(prefix, 'include')
- if python_build:
- # Assume the executable is in the build directory. The
- # pyconfig.h file should be in the same directory. Since
- # the build directory may not be the source directory, we
- # must use "srcdir" from the makefile to find the "Include"
- # directory.
- if plat_specific:
- return _sys_home or project_base
- else:
- incdir = os.path.join(get_config_var('srcdir'), 'Include')
- return os.path.normpath(incdir)
- implementation = 'pypy' if IS_PYPY else 'python'
- python_dir = implementation + get_python_version() + build_flags
- return os.path.join(prefix, "include", python_dir)
- elif os.name == "nt":
- if python_build:
- # Include both the include and PC dir to ensure we can find
- # pyconfig.h
- return (os.path.join(prefix, "include") + os.path.pathsep +
- os.path.join(prefix, "PC"))
- return os.path.join(prefix, "include")
- else:
+ default_prefix = BASE_EXEC_PREFIX if plat_specific else BASE_PREFIX
+ resolved_prefix = prefix if prefix is not None else default_prefix
+ try:
+ getter = globals()[f'_get_python_inc_{os.name}']
+ except KeyError:
raise DistutilsPlatformError(
"I don't know where Python installs its C header files "
- "on platform '%s'" % os.name)
+ "on platform '%s'" % os.name
+ )
+ return getter(resolved_prefix, prefix, plat_specific)
+
+
+def _get_python_inc_posix(prefix, spec_prefix, plat_specific):
+ if IS_PYPY and sys.version_info < (3, 8):
+ return os.path.join(prefix, 'include')
+ return (
+ _get_python_inc_posix_python(plat_specific)
+ or _get_python_inc_from_config(plat_specific, spec_prefix)
+ or _get_python_inc_posix_prefix(prefix)
+ )
+
+
+def _get_python_inc_posix_python(plat_specific):
+ """
+ Assume the executable is in the build directory. The
+ pyconfig.h file should be in the same directory. Since
+ the build directory may not be the source directory,
+ use "srcdir" from the makefile to find the "Include"
+ directory.
+ """
+ if not python_build:
+ return
+ if plat_specific:
+ return _sys_home or project_base
+ incdir = os.path.join(get_config_var('srcdir'), 'Include')
+ return os.path.normpath(incdir)
+
+
+def _get_python_inc_from_config(plat_specific, spec_prefix):
+ """
+ If no prefix was explicitly specified, provide the include
+ directory from the config vars. Useful when
+ cross-compiling, since the config vars may come from
+ the host
+ platform Python installation, while the current Python
+ executable is from the build platform installation.
+ """
+ if not spec_prefix:
+ return
+ return get_config_var('CONF' * plat_specific + 'INCLUDEPY')
+
+
+def _get_python_inc_posix_prefix(prefix):
+ implementation = 'pypy' if IS_PYPY else 'python'
+ python_dir = implementation + get_python_version() + build_flags
+ return os.path.join(prefix, "include", python_dir)
+
+
+def _get_python_inc_nt(prefix, spec_prefix, plat_specific):
+ if python_build:
+ # Include both the include and PC dir to ensure we can find
+ # pyconfig.h
+ return (
+ os.path.join(prefix, "include")
+ + os.path.pathsep
+ + os.path.join(prefix, "PC")
+ )
+ return os.path.join(prefix, "include")
# allow this behavior to be monkey-patched. Ref pypa/distutils#2.
@@ -182,8 +236,7 @@ def get_python_lib(plat_specific=0, standard_lib=0, prefix=None):
# Pure Python
libdir = "lib"
implementation = 'pypy' if IS_PYPY else 'python'
- libpython = os.path.join(prefix, libdir,
- implementation + get_python_version())
+ libpython = os.path.join(prefix, libdir, implementation + get_python_version())
return _posix_lib(standard_lib, libpython, early_prefix, prefix)
elif os.name == "nt":
if standard_lib:
@@ -193,7 +246,8 @@ def get_python_lib(plat_specific=0, standard_lib=0, prefix=None):
else:
raise DistutilsPlatformError(
"I don't know where Python installs its library "
- "on platform '%s'" % os.name)
+ "on platform '%s'" % os.name
+ )
def customize_compiler(compiler):
@@ -216,21 +270,36 @@ def customize_compiler(compiler):
# Use get_config_var() to ensure _config_vars is initialized.
if not get_config_var('CUSTOMIZED_OSX_COMPILER'):
import _osx_support
+
_osx_support.customize_compiler(_config_vars)
_config_vars['CUSTOMIZED_OSX_COMPILER'] = 'True'
- (cc, cxx, cflags, ccshared, ldshared, shlib_suffix, ar, ar_flags) = \
- get_config_vars(
- 'CC', 'CXX', 'CFLAGS',
- 'CCSHARED', 'LDSHARED', 'SHLIB_SUFFIX', 'AR', 'ARFLAGS')
+ (
+ cc,
+ cxx,
+ cflags,
+ ccshared,
+ ldshared,
+ shlib_suffix,
+ ar,
+ ar_flags,
+ ) = get_config_vars(
+ 'CC',
+ 'CXX',
+ 'CFLAGS',
+ 'CCSHARED',
+ 'LDSHARED',
+ 'SHLIB_SUFFIX',
+ 'AR',
+ 'ARFLAGS',
+ )
if 'CC' in os.environ:
newcc = os.environ['CC']
- if('LDSHARED' not in os.environ
- and ldshared.startswith(cc)):
+ if 'LDSHARED' not in os.environ and ldshared.startswith(cc):
# If CC is overridden, use that as the default
# command for LDSHARED as well
- ldshared = newcc + ldshared[len(cc):]
+ ldshared = newcc + ldshared[len(cc) :]
cc = newcc
if 'CXX' in os.environ:
cxx = os.environ['CXX']
@@ -239,7 +308,7 @@ def customize_compiler(compiler):
if 'CPP' in os.environ:
cpp = os.environ['CPP']
else:
- cpp = cc + " -E" # not always
+ cpp = cc + " -E" # not always
if 'LDFLAGS' in os.environ:
ldshared = ldshared + ' ' + os.environ['LDFLAGS']
if 'CFLAGS' in os.environ:
@@ -264,7 +333,8 @@ def customize_compiler(compiler):
compiler_cxx=cxx,
linker_so=ldshared,
linker_exe=cc,
- archiver=archiver)
+ archiver=archiver,
+ )
if 'RANLIB' in os.environ and compiler.executables.get('ranlib', None):
compiler.set_executables(ranlib=os.environ['RANLIB'])
@@ -314,9 +384,10 @@ def parse_makefile(fn, g=None):
used instead of a new dictionary.
"""
from distutils.text_file import TextFile
+
fp = TextFile(
- fn, strip_comments=1, skip_blanks=1, join_lines=1,
- errors="surrogateescape")
+ fn, strip_comments=1, skip_blanks=1, join_lines=1, errors="surrogateescape"
+ )
if g is None:
g = {}
@@ -369,8 +440,7 @@ def parse_makefile(fn, g=None):
item = os.environ[n]
elif n in renamed_variables:
- if name.startswith('PY_') and \
- name[3:] in renamed_variables:
+ if name.startswith('PY_') and name[3:] in renamed_variables:
item = ""
elif 'PY_' + n in notdone:
@@ -381,8 +451,8 @@ def parse_makefile(fn, g=None):
else:
done[n] = item = ""
if found:
- after = value[m.end():]
- value = value[:m.start()] + item + after
+ after = value[m.end() :]
+ value = value[: m.start()] + item + after
if "$" in after:
notdone[name] = value
else:
@@ -394,8 +464,7 @@ def parse_makefile(fn, g=None):
done[name] = value
del notdone[name]
- if name.startswith('PY_') \
- and name[3:] in renamed_variables:
+ if name.startswith('PY_') and name[3:] in renamed_variables:
name = name[3:]
if name not in done:
@@ -475,6 +544,6 @@ def get_config_var(name):
"""
if name == 'SO':
import warnings
- warnings.warn(
- 'SO is deprecated, use EXT_SUFFIX', DeprecationWarning, 2)
+
+ warnings.warn('SO is deprecated, use EXT_SUFFIX', DeprecationWarning, 2)
return get_config_vars().get(name)
diff --git a/setuptools/_distutils/tests/py35compat.py b/setuptools/_distutils/tests/py35compat.py
deleted file mode 100644
index 0c755261..00000000
--- a/setuptools/_distutils/tests/py35compat.py
+++ /dev/null
@@ -1,77 +0,0 @@
-"""
-Backward compatibility support for Python 3.5
-"""
-
-import sys
-import test.support
-import subprocess
-
-
-# copied from Python 3.9 test.support module
-def _missing_compiler_executable(cmd_names=[]):
- """Check if the compiler components used to build the interpreter exist.
-
- Check for the existence of the compiler executables whose names are listed
- in 'cmd_names' or all the compiler executables when 'cmd_names' is empty
- and return the first missing executable or None when none is found
- missing.
-
- """
- from distutils import ccompiler, sysconfig, spawn
- compiler = ccompiler.new_compiler()
- sysconfig.customize_compiler(compiler)
- for name in compiler.executables:
- if cmd_names and name not in cmd_names:
- continue
- cmd = getattr(compiler, name)
- if cmd_names:
- assert cmd is not None, \
- "the '%s' executable is not configured" % name
- elif not cmd:
- continue
- if spawn.find_executable(cmd[0]) is None:
- return cmd[0]
-
-
-missing_compiler_executable = vars(test.support).setdefault(
- 'missing_compiler_executable',
- _missing_compiler_executable,
-)
-
-
-try:
- from test.support import unix_shell
-except ImportError:
- # Adapted from Python 3.9 test.support module
- is_android = hasattr(sys, 'getandroidapilevel')
- unix_shell = (
- None if sys.platform == 'win32' else
- '/system/bin/sh' if is_android else
- '/bin/sh'
- )
-
-
-# copied from Python 3.9 subprocess module
-def _optim_args_from_interpreter_flags():
- """Return a list of command-line arguments reproducing the current
- optimization settings in sys.flags."""
- args = []
- value = sys.flags.optimize
- if value > 0:
- args.append('-' + 'O' * value)
- return args
-
-
-vars(subprocess).setdefault(
- '_optim_args_from_interpreter_flags',
- _optim_args_from_interpreter_flags,
-)
-
-
-def adapt_glob(regex):
- """
- Supply legacy expectation on Python 3.5
- """
- if sys.version_info > (3, 6):
- return regex
- return regex.replace('(?s:', '').replace(r')\Z', r'\Z(?ms)')
diff --git a/setuptools/_distutils/tests/support.py b/setuptools/_distutils/tests/support.py
index b4410fc9..3085468a 100644
--- a/setuptools/_distutils/tests/support.py
+++ b/setuptools/_distutils/tests/support.py
@@ -15,7 +15,6 @@ from distutils.core import Distribution
class LoggingSilencer(object):
-
def setUp(self):
super().setUp()
self.threshold = log.set_threshold(log.FATAL)
@@ -35,13 +34,11 @@ class LoggingSilencer(object):
if level not in (DEBUG, INFO, WARN, ERROR, FATAL):
raise ValueError('%s wrong log level' % str(level))
if not isinstance(msg, str):
- raise TypeError("msg should be str, not '%.200s'"
- % (type(msg).__name__))
+ raise TypeError("msg should be str, not '%.200s'" % (type(msg).__name__))
self.logs.append((level, msg, args))
def get_logs(self, *levels):
- return [msg % args for level, msg, args
- in self.logs if level in levels]
+ return [msg % args for level, msg, args in self.logs if level in levels]
def clear_logs(self):
self.logs = []
@@ -120,7 +117,6 @@ class DummyCommand:
class EnvironGuard(object):
-
def setUp(self):
super(EnvironGuard, self).setUp()
self.old_environ = deepcopy(os.environ)
@@ -151,8 +147,9 @@ def copy_xxmodule_c(directory):
"""
filename = _get_xxmodule_path()
if filename is None:
- raise unittest.SkipTest('cannot find xxmodule.c (test must run in '
- 'the python build dir)')
+ raise unittest.SkipTest(
+ 'cannot find xxmodule.c (test must run in ' 'the python build dir)'
+ )
shutil.copy(filename, directory)
diff --git a/setuptools/_distutils/tests/test_archive_util.py b/setuptools/_distutils/tests/test_archive_util.py
index 800b9018..8fb95744 100644
--- a/setuptools/_distutils/tests/test_archive_util.py
+++ b/setuptools/_distutils/tests/test_archive_util.py
@@ -8,9 +8,13 @@ from os.path import splitdrive
import warnings
from distutils import archive_util
-from distutils.archive_util import (check_archive_formats, make_tarball,
- make_zipfile, make_archive,
- ARCHIVE_FORMATS)
+from distutils.archive_util import (
+ check_archive_formats,
+ make_tarball,
+ make_zipfile,
+ make_archive,
+ ARCHIVE_FORMATS,
+)
from distutils.spawn import find_executable, spawn
from distutils.tests import support
from test.support import run_unittest, patch
@@ -22,12 +26,14 @@ from .py38compat import check_warnings
try:
import zipfile
+
ZIP_SUPPORT = True
except ImportError:
ZIP_SUPPORT = find_executable('zip')
try:
import zlib
+
ZLIB_SUPPORT = True
except ImportError:
ZLIB_SUPPORT = False
@@ -42,6 +48,7 @@ try:
except ImportError:
lzma = None
+
def can_fs_encode(filename):
"""
Return True if the filename can be saved in the file system.
@@ -55,10 +62,9 @@ def can_fs_encode(filename):
return True
-class ArchiveUtilTestCase(support.TempdirManager,
- support.LoggingSilencer,
- unittest.TestCase):
-
+class ArchiveUtilTestCase(
+ support.TempdirManager, support.LoggingSilencer, unittest.TestCase
+):
@unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run')
def test_make_tarball(self, name='archive'):
# creating something to tar
@@ -82,27 +88,31 @@ class ArchiveUtilTestCase(support.TempdirManager,
tmpdir = self._create_files()
self._make_tarball(tmpdir, 'archive', '.tar.xz', compress='xz')
- @unittest.skipUnless(can_fs_encode('årchiv'),
- 'File system cannot handle this filename')
+ @unittest.skipUnless(
+ can_fs_encode('årchiv'), 'File system cannot handle this filename'
+ )
def test_make_tarball_latin1(self):
"""
Mirror test_make_tarball, except filename contains latin characters.
"""
- self.test_make_tarball('årchiv') # note this isn't a real word
+ self.test_make_tarball('årchiv') # note this isn't a real word
- @unittest.skipUnless(can_fs_encode('のアーカイブ'),
- 'File system cannot handle this filename')
+ @unittest.skipUnless(
+ can_fs_encode('のアーカイブ'), 'File system cannot handle this filename'
+ )
def test_make_tarball_extended(self):
"""
Mirror test_make_tarball, except filename contains extended
characters outside the latin charset.
"""
- self.test_make_tarball('のアーカイブ') # japanese for archive
+ self.test_make_tarball('のアーカイブ') # japanese for archive
def _make_tarball(self, tmpdir, target_name, suffix, **kwargs):
tmpdir2 = self.mkdtemp()
- unittest.skipUnless(splitdrive(tmpdir)[0] == splitdrive(tmpdir2)[0],
- "source and target should be on same drive")
+ unittest.skipUnless(
+ splitdrive(tmpdir)[0] == splitdrive(tmpdir2)[0],
+ "source and target should be on same drive",
+ )
base_name = os.path.join(tmpdir2, target_name)
@@ -124,8 +134,14 @@ class ArchiveUtilTestCase(support.TempdirManager,
finally:
tar.close()
- _zip_created_files = ['dist/', 'dist/file1', 'dist/file2',
- 'dist/sub/', 'dist/sub/file3', 'dist/sub2/']
+ _zip_created_files = [
+ 'dist/',
+ 'dist/file1',
+ 'dist/file2',
+ 'dist/sub/',
+ 'dist/sub/file3',
+ 'dist/sub2/',
+ ]
_created_files = [p.rstrip('/') for p in _zip_created_files]
def _create_files(self):
@@ -140,11 +156,12 @@ class ArchiveUtilTestCase(support.TempdirManager,
os.mkdir(os.path.join(dist, 'sub2'))
return tmpdir
- @unittest.skipUnless(find_executable('tar') and find_executable('gzip')
- and ZLIB_SUPPORT,
- 'Need the tar, gzip and zlib command to run')
+ @unittest.skipUnless(
+ find_executable('tar') and find_executable('gzip') and ZLIB_SUPPORT,
+ 'Need the tar, gzip and zlib command to run',
+ )
def test_tarfile_vs_tar(self):
- tmpdir = self._create_files()
+ tmpdir = self._create_files()
tmpdir2 = self.mkdtemp()
base_name = os.path.join(tmpdir2, 'archive')
old_dir = os.getcwd()
@@ -197,10 +214,11 @@ class ArchiveUtilTestCase(support.TempdirManager,
tarball = base_name + '.tar'
self.assertTrue(os.path.exists(tarball))
- @unittest.skipUnless(find_executable('compress'),
- 'The compress program is required')
+ @unittest.skipUnless(
+ find_executable('compress'), 'The compress program is required'
+ )
def test_compress_deprecated(self):
- tmpdir = self._create_files()
+ tmpdir = self._create_files()
base_name = os.path.join(self.mkdtemp(), 'archive')
# using compress and testing the PendingDeprecationWarning
@@ -223,15 +241,15 @@ class ArchiveUtilTestCase(support.TempdirManager,
try:
with check_warnings() as w:
warnings.simplefilter("always")
- make_tarball(base_name, 'dist', compress='compress',
- dry_run=True)
+ make_tarball(base_name, 'dist', compress='compress', dry_run=True)
finally:
os.chdir(old_dir)
self.assertFalse(os.path.exists(tarball))
self.assertEqual(len(w.warnings), 1)
- @unittest.skipUnless(ZIP_SUPPORT and ZLIB_SUPPORT,
- 'Need zip and zlib support to run')
+ @unittest.skipUnless(
+ ZIP_SUPPORT and ZLIB_SUPPORT, 'Need zip and zlib support to run'
+ )
def test_make_zipfile(self):
# creating something to tar
tmpdir = self._create_files()
@@ -251,6 +269,7 @@ class ArchiveUtilTestCase(support.TempdirManager,
called = []
zipfile_class = zipfile.ZipFile
+
def fake_zipfile(*a, **kw):
if kw.get('compression', None) == zipfile.ZIP_STORED:
called.append((a, kw))
@@ -265,17 +284,18 @@ class ArchiveUtilTestCase(support.TempdirManager,
make_zipfile(base_name, 'dist')
tarball = base_name + '.zip'
- self.assertEqual(called,
- [((tarball, "w"), {'compression': zipfile.ZIP_STORED})])
+ self.assertEqual(
+ called, [((tarball, "w"), {'compression': zipfile.ZIP_STORED})]
+ )
self.assertTrue(os.path.exists(tarball))
with zipfile.ZipFile(tarball) as zf:
self.assertEqual(sorted(zf.namelist()), self._zip_created_files)
def test_check_archive_formats(self):
- self.assertEqual(check_archive_formats(['gztar', 'xxx', 'zip']),
- 'xxx')
- self.assertIsNone(check_archive_formats(['gztar', 'bztar', 'xztar',
- 'ztar', 'tar', 'zip']))
+ self.assertEqual(check_archive_formats(['gztar', 'xxx', 'zip']), 'xxx')
+ self.assertIsNone(
+ check_archive_formats(['gztar', 'bztar', 'xztar', 'ztar', 'tar', 'zip'])
+ )
def test_make_archive(self):
tmpdir = self.mkdtemp()
@@ -284,8 +304,10 @@ class ArchiveUtilTestCase(support.TempdirManager,
def test_make_archive_cwd(self):
current_dir = os.getcwd()
+
def _breaks(*args, **kw):
raise RuntimeError()
+
ARCHIVE_FORMATS['xxx'] = (_breaks, [], 'xxx file')
try:
try:
@@ -297,8 +319,8 @@ class ArchiveUtilTestCase(support.TempdirManager,
del ARCHIVE_FORMATS['xxx']
def test_make_archive_tar(self):
- base_dir = self._create_files()
- base_name = os.path.join(self.mkdtemp() , 'archive')
+ base_dir = self._create_files()
+ base_name = os.path.join(self.mkdtemp(), 'archive')
res = make_archive(base_name, 'tar', base_dir, 'dist')
self.assertTrue(os.path.exists(res))
self.assertEqual(os.path.basename(res), 'archive.tar')
@@ -306,8 +328,8 @@ class ArchiveUtilTestCase(support.TempdirManager,
@unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run')
def test_make_archive_gztar(self):
- base_dir = self._create_files()
- base_name = os.path.join(self.mkdtemp() , 'archive')
+ base_dir = self._create_files()
+ base_name = os.path.join(self.mkdtemp(), 'archive')
res = make_archive(base_name, 'gztar', base_dir, 'dist')
self.assertTrue(os.path.exists(res))
self.assertEqual(os.path.basename(res), 'archive.tar.gz')
@@ -315,8 +337,8 @@ class ArchiveUtilTestCase(support.TempdirManager,
@unittest.skipUnless(bz2, 'Need bz2 support to run')
def test_make_archive_bztar(self):
- base_dir = self._create_files()
- base_name = os.path.join(self.mkdtemp() , 'archive')
+ base_dir = self._create_files()
+ base_name = os.path.join(self.mkdtemp(), 'archive')
res = make_archive(base_name, 'bztar', base_dir, 'dist')
self.assertTrue(os.path.exists(res))
self.assertEqual(os.path.basename(res), 'archive.tar.bz2')
@@ -324,8 +346,8 @@ class ArchiveUtilTestCase(support.TempdirManager,
@unittest.skipUnless(lzma, 'Need xz support to run')
def test_make_archive_xztar(self):
- base_dir = self._create_files()
- base_name = os.path.join(self.mkdtemp() , 'archive')
+ base_dir = self._create_files()
+ base_name = os.path.join(self.mkdtemp(), 'archive')
res = make_archive(base_name, 'xztar', base_dir, 'dist')
self.assertTrue(os.path.exists(res))
self.assertEqual(os.path.basename(res), 'archive.tar.xz')
@@ -340,37 +362,41 @@ class ArchiveUtilTestCase(support.TempdirManager,
else:
group = owner = 'root'
- base_dir = self._create_files()
+ base_dir = self._create_files()
root_dir = self.mkdtemp()
- base_name = os.path.join(self.mkdtemp() , 'archive')
- res = make_archive(base_name, 'zip', root_dir, base_dir, owner=owner,
- group=group)
+ base_name = os.path.join(self.mkdtemp(), 'archive')
+ res = make_archive(
+ base_name, 'zip', root_dir, base_dir, owner=owner, group=group
+ )
self.assertTrue(os.path.exists(res))
res = make_archive(base_name, 'zip', root_dir, base_dir)
self.assertTrue(os.path.exists(res))
- res = make_archive(base_name, 'tar', root_dir, base_dir,
- owner=owner, group=group)
+ res = make_archive(
+ base_name, 'tar', root_dir, base_dir, owner=owner, group=group
+ )
self.assertTrue(os.path.exists(res))
- res = make_archive(base_name, 'tar', root_dir, base_dir,
- owner='kjhkjhkjg', group='oihohoh')
+ res = make_archive(
+ base_name, 'tar', root_dir, base_dir, owner='kjhkjhkjg', group='oihohoh'
+ )
self.assertTrue(os.path.exists(res))
@unittest.skipUnless(ZLIB_SUPPORT, "Requires zlib")
@require_unix_id
@require_uid_0
def test_tarfile_root_owner(self):
- tmpdir = self._create_files()
+ tmpdir = self._create_files()
base_name = os.path.join(self.mkdtemp(), 'archive')
old_dir = os.getcwd()
os.chdir(tmpdir)
group = grp.getgrgid(0)[0]
owner = pwd.getpwuid(0)[0]
try:
- archive_name = make_tarball(base_name, 'dist', compress=None,
- owner=owner, group=group)
+ archive_name = make_tarball(
+ base_name, 'dist', compress=None, owner=owner, group=group
+ )
finally:
os.chdir(old_dir)
@@ -386,8 +412,10 @@ class ArchiveUtilTestCase(support.TempdirManager,
finally:
archive.close()
+
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(ArchiveUtilTestCase)
+
if __name__ == "__main__":
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_bdist.py b/setuptools/_distutils/tests/test_bdist.py
index 8b7498e3..2d0bb95b 100644
--- a/setuptools/_distutils/tests/test_bdist.py
+++ b/setuptools/_distutils/tests/test_bdist.py
@@ -8,9 +8,7 @@ from distutils.command.bdist import bdist
from distutils.tests import support
-class BuildTestCase(support.TempdirManager,
- unittest.TestCase):
-
+class BuildTestCase(support.TempdirManager, unittest.TestCase):
def test_formats(self):
# let's create a command and make sure
# we can set the format
@@ -21,8 +19,17 @@ class BuildTestCase(support.TempdirManager,
self.assertEqual(cmd.formats, ['msi'])
# what formats does bdist offer?
- formats = ['bztar', 'gztar', 'msi', 'rpm', 'tar',
- 'wininst', 'xztar', 'zip', 'ztar']
+ formats = [
+ 'bztar',
+ 'gztar',
+ 'msi',
+ 'rpm',
+ 'tar',
+ 'wininst',
+ 'xztar',
+ 'zip',
+ 'ztar',
+ ]
found = sorted(cmd.format_command)
self.assertEqual(found, formats)
@@ -34,24 +41,30 @@ class BuildTestCase(support.TempdirManager,
cmd.ensure_finalized()
dist.command_obj['bdist'] = cmd
- names = ['bdist_dumb', 'bdist_wininst'] # bdist_rpm does not support --skip-build
+ names = [
+ 'bdist_dumb',
+ 'bdist_wininst',
+ ] # bdist_rpm does not support --skip-build
if os.name == 'nt':
names.append('bdist_msi')
for name in names:
with warnings.catch_warnings():
- warnings.filterwarnings('ignore', 'bdist_wininst command is deprecated',
- DeprecationWarning)
+ warnings.filterwarnings(
+ 'ignore', 'bdist_wininst command is deprecated', DeprecationWarning
+ )
subcmd = cmd.get_finalized_command(name)
if getattr(subcmd, '_unsupported', False):
# command is not supported on this build
continue
- self.assertTrue(subcmd.skip_build,
- '%s should take --skip-build from bdist' % name)
+ self.assertTrue(
+ subcmd.skip_build, '%s should take --skip-build from bdist' % name
+ )
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(BuildTestCase)
+
if __name__ == '__main__':
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_bdist_dumb.py b/setuptools/_distutils/tests/test_bdist_dumb.py
index bb860c8a..83ab217d 100644
--- a/setuptools/_distutils/tests/test_bdist_dumb.py
+++ b/setuptools/_distutils/tests/test_bdist_dumb.py
@@ -21,16 +21,18 @@ setup(name='foo', version='0.1', py_modules=['foo'],
try:
import zlib
+
ZLIB_SUPPORT = True
except ImportError:
ZLIB_SUPPORT = False
-class BuildDumbTestCase(support.TempdirManager,
- support.LoggingSilencer,
- support.EnvironGuard,
- unittest.TestCase):
-
+class BuildDumbTestCase(
+ support.TempdirManager,
+ support.LoggingSilencer,
+ support.EnvironGuard,
+ unittest.TestCase,
+):
def setUp(self):
super(BuildDumbTestCase, self).setUp()
self.old_location = os.getcwd()
@@ -54,10 +56,16 @@ class BuildDumbTestCase(support.TempdirManager,
self.write_file((pkg_dir, 'MANIFEST.in'), 'include foo.py')
self.write_file((pkg_dir, 'README'), '')
- dist = Distribution({'name': 'foo', 'version': '0.1',
- 'py_modules': ['foo'],
- 'url': 'xxx', 'author': 'xxx',
- 'author_email': 'xxx'})
+ dist = Distribution(
+ {
+ 'name': 'foo',
+ 'version': '0.1',
+ 'py_modules': ['foo'],
+ 'url': 'xxx',
+ 'author': 'xxx',
+ 'author_email': 'xxx',
+ }
+ )
dist.script_name = 'setup.py'
os.chdir(pkg_dir)
@@ -90,8 +98,10 @@ class BuildDumbTestCase(support.TempdirManager,
wanted.append('foo.%s.pyc' % sys.implementation.cache_tag)
self.assertEqual(contents, sorted(wanted))
+
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(BuildDumbTestCase)
+
if __name__ == '__main__':
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_bdist_msi.py b/setuptools/_distutils/tests/test_bdist_msi.py
index b1831ef2..a9f3dbb5 100644
--- a/setuptools/_distutils/tests/test_bdist_msi.py
+++ b/setuptools/_distutils/tests/test_bdist_msi.py
@@ -8,13 +8,13 @@ from .py38compat import check_warnings
@unittest.skipUnless(sys.platform == 'win32', 'these tests require Windows')
-class BDistMSITestCase(support.TempdirManager,
- support.LoggingSilencer,
- unittest.TestCase):
-
+class BDistMSITestCase(
+ support.TempdirManager, support.LoggingSilencer, unittest.TestCase
+):
def test_minimal(self):
# minimal test XXX need more tests
from distutils.command.bdist_msi import bdist_msi
+
project_dir, dist = self.create_dist()
with check_warnings(("", DeprecationWarning)):
cmd = bdist_msi(dist)
@@ -24,5 +24,6 @@ class BDistMSITestCase(support.TempdirManager,
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(BDistMSITestCase)
+
if __name__ == '__main__':
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_bdist_rpm.py b/setuptools/_distutils/tests/test_bdist_rpm.py
index 08a7cb46..f60a582a 100644
--- a/setuptools/_distutils/tests/test_bdist_rpm.py
+++ b/setuptools/_distutils/tests/test_bdist_rpm.py
@@ -22,11 +22,13 @@ setup(name='foo', version='0.1', py_modules=['foo'],
"""
-class BuildRpmTestCase(support.TempdirManager,
- support.EnvironGuard,
- support.LoggingSilencer,
- unittest.TestCase):
+class BuildRpmTestCase(
+ support.TempdirManager,
+ support.EnvironGuard,
+ support.LoggingSilencer,
+ unittest.TestCase,
+):
def setUp(self):
try:
sys.executable.encode("UTF-8")
@@ -45,17 +47,18 @@ class BuildRpmTestCase(support.TempdirManager,
# XXX I am unable yet to make this test work without
# spurious sdtout/stderr output under Mac OS X
- @unittest.skipUnless(sys.platform.startswith('linux'),
- 'spurious sdtout/stderr output under Mac OS X')
+ @unittest.skipUnless(
+ sys.platform.startswith('linux'), 'spurious sdtout/stderr output under Mac OS X'
+ )
@requires_zlib()
- @unittest.skipIf(find_executable('rpm') is None,
- 'the rpm command is not found')
- @unittest.skipIf(find_executable('rpmbuild') is None,
- 'the rpmbuild command is not found')
+ @unittest.skipIf(find_executable('rpm') is None, 'the rpm command is not found')
+ @unittest.skipIf(
+ find_executable('rpmbuild') is None, 'the rpmbuild command is not found'
+ )
def test_quiet(self):
# let's create a package
tmp_dir = self.mkdtemp()
- os.environ['HOME'] = tmp_dir # to confine dir '.rpmdb' creation
+ os.environ['HOME'] = tmp_dir # to confine dir '.rpmdb' creation
pkg_dir = os.path.join(tmp_dir, 'foo')
os.mkdir(pkg_dir)
self.write_file((pkg_dir, 'setup.py'), SETUP_PY)
@@ -63,10 +66,16 @@ class BuildRpmTestCase(support.TempdirManager,
self.write_file((pkg_dir, 'MANIFEST.in'), 'include foo.py')
self.write_file((pkg_dir, 'README'), '')
- dist = Distribution({'name': 'foo', 'version': '0.1',
- 'py_modules': ['foo'],
- 'url': 'xxx', 'author': 'xxx',
- 'author_email': 'xxx'})
+ dist = Distribution(
+ {
+ 'name': 'foo',
+ 'version': '0.1',
+ 'py_modules': ['foo'],
+ 'url': 'xxx',
+ 'author': 'xxx',
+ 'author_email': 'xxx',
+ }
+ )
dist.script_name = 'setup.py'
os.chdir(pkg_dir)
@@ -84,22 +93,25 @@ class BuildRpmTestCase(support.TempdirManager,
# bug #2945: upload ignores bdist_rpm files
self.assertIn(('bdist_rpm', 'any', 'dist/foo-0.1-1.src.rpm'), dist.dist_files)
- self.assertIn(('bdist_rpm', 'any', 'dist/foo-0.1-1.noarch.rpm'), dist.dist_files)
+ self.assertIn(
+ ('bdist_rpm', 'any', 'dist/foo-0.1-1.noarch.rpm'), dist.dist_files
+ )
# XXX I am unable yet to make this test work without
# spurious sdtout/stderr output under Mac OS X
- @unittest.skipUnless(sys.platform.startswith('linux'),
- 'spurious sdtout/stderr output under Mac OS X')
+ @unittest.skipUnless(
+ sys.platform.startswith('linux'), 'spurious sdtout/stderr output under Mac OS X'
+ )
@requires_zlib()
# http://bugs.python.org/issue1533164
- @unittest.skipIf(find_executable('rpm') is None,
- 'the rpm command is not found')
- @unittest.skipIf(find_executable('rpmbuild') is None,
- 'the rpmbuild command is not found')
+ @unittest.skipIf(find_executable('rpm') is None, 'the rpm command is not found')
+ @unittest.skipIf(
+ find_executable('rpmbuild') is None, 'the rpmbuild command is not found'
+ )
def test_no_optimize_flag(self):
# let's create a package that breaks bdist_rpm
tmp_dir = self.mkdtemp()
- os.environ['HOME'] = tmp_dir # to confine dir '.rpmdb' creation
+ os.environ['HOME'] = tmp_dir # to confine dir '.rpmdb' creation
pkg_dir = os.path.join(tmp_dir, 'foo')
os.mkdir(pkg_dir)
self.write_file((pkg_dir, 'setup.py'), SETUP_PY)
@@ -107,10 +119,16 @@ class BuildRpmTestCase(support.TempdirManager,
self.write_file((pkg_dir, 'MANIFEST.in'), 'include foo.py')
self.write_file((pkg_dir, 'README'), '')
- dist = Distribution({'name': 'foo', 'version': '0.1',
- 'py_modules': ['foo'],
- 'url': 'xxx', 'author': 'xxx',
- 'author_email': 'xxx'})
+ dist = Distribution(
+ {
+ 'name': 'foo',
+ 'version': '0.1',
+ 'py_modules': ['foo'],
+ 'url': 'xxx',
+ 'author': 'xxx',
+ 'author_email': 'xxx',
+ }
+ )
dist.script_name = 'setup.py'
os.chdir(pkg_dir)
@@ -127,12 +145,16 @@ class BuildRpmTestCase(support.TempdirManager,
# bug #2945: upload ignores bdist_rpm files
self.assertIn(('bdist_rpm', 'any', 'dist/foo-0.1-1.src.rpm'), dist.dist_files)
- self.assertIn(('bdist_rpm', 'any', 'dist/foo-0.1-1.noarch.rpm'), dist.dist_files)
+ self.assertIn(
+ ('bdist_rpm', 'any', 'dist/foo-0.1-1.noarch.rpm'), dist.dist_files
+ )
os.remove(os.path.join(pkg_dir, 'dist', 'foo-0.1-1.noarch.rpm'))
+
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(BuildRpmTestCase)
+
if __name__ == '__main__':
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_bdist_wininst.py b/setuptools/_distutils/tests/test_bdist_wininst.py
index 59f25167..c103a63b 100644
--- a/setuptools/_distutils/tests/test_bdist_wininst.py
+++ b/setuptools/_distutils/tests/test_bdist_wininst.py
@@ -9,14 +9,18 @@ from .py38compat import check_warnings
from distutils.command.bdist_wininst import bdist_wininst
from distutils.tests import support
-@unittest.skipIf(sys.platform == 'win32' and platform.machine() == 'ARM64',
- 'bdist_wininst is not supported in this install')
-@unittest.skipIf(getattr(bdist_wininst, '_unsupported', False),
- 'bdist_wininst is not supported in this install')
-class BuildWinInstTestCase(support.TempdirManager,
- support.LoggingSilencer,
- unittest.TestCase):
+@unittest.skipIf(
+ sys.platform == 'win32' and platform.machine() == 'ARM64',
+ 'bdist_wininst is not supported in this install',
+)
+@unittest.skipIf(
+ getattr(bdist_wininst, '_unsupported', False),
+ 'bdist_wininst is not supported in this install',
+)
+class BuildWinInstTestCase(
+ support.TempdirManager, support.LoggingSilencer, unittest.TestCase
+):
def test_get_exe_bytes(self):
# issue5731: command was broken on non-windows platforms
@@ -33,8 +37,10 @@ class BuildWinInstTestCase(support.TempdirManager,
exe_file = cmd.get_exe_bytes()
self.assertGreater(len(exe_file), 10)
+
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(BuildWinInstTestCase)
+
if __name__ == '__main__':
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_build.py b/setuptools/_distutils/tests/test_build.py
index 93724419..190bbdfd 100644
--- a/setuptools/_distutils/tests/test_build.py
+++ b/setuptools/_distutils/tests/test_build.py
@@ -8,10 +8,8 @@ from distutils.command.build import build
from distutils.tests import support
from sysconfig import get_platform
-class BuildTestCase(support.TempdirManager,
- support.LoggingSilencer,
- unittest.TestCase):
+class BuildTestCase(support.TempdirManager, support.LoggingSilencer, unittest.TestCase):
def test_finalize_options(self):
pkg_dir, dist = self.create_dist()
cmd = build(dist)
@@ -42,15 +40,16 @@ class BuildTestCase(support.TempdirManager,
self.assertEqual(cmd.build_temp, wanted)
# build_scripts is build/scripts-x.x
- wanted = os.path.join(cmd.build_base,
- 'scripts-%d.%d' % sys.version_info[:2])
+ wanted = os.path.join(cmd.build_base, 'scripts-%d.%d' % sys.version_info[:2])
self.assertEqual(cmd.build_scripts, wanted)
# executable is os.path.normpath(sys.executable)
self.assertEqual(cmd.executable, os.path.normpath(sys.executable))
+
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(BuildTestCase)
+
if __name__ == "__main__":
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_build_clib.py b/setuptools/_distutils/tests/test_build_clib.py
index d50ead7c..24c74787 100644
--- a/setuptools/_distutils/tests/test_build_clib.py
+++ b/setuptools/_distutils/tests/test_build_clib.py
@@ -3,18 +3,16 @@ import unittest
import os
import sys
-from test.support import run_unittest
-
-from .py35compat import missing_compiler_executable
+from test.support import run_unittest, missing_compiler_executable
from distutils.command.build_clib import build_clib
from distutils.errors import DistutilsSetupError
from distutils.tests import support
-class BuildCLibTestCase(support.TempdirManager,
- support.LoggingSilencer,
- unittest.TestCase):
+class BuildCLibTestCase(
+ support.TempdirManager, support.LoggingSilencer, unittest.TestCase
+):
def test_check_library_dist(self):
pkg_dir, dist = self.create_dist()
cmd = build_clib(dist)
@@ -23,23 +21,27 @@ class BuildCLibTestCase(support.TempdirManager,
self.assertRaises(DistutilsSetupError, cmd.check_library_list, 'foo')
# each element of 'libraries' must a 2-tuple
- self.assertRaises(DistutilsSetupError, cmd.check_library_list,
- ['foo1', 'foo2'])
+ self.assertRaises(DistutilsSetupError, cmd.check_library_list, ['foo1', 'foo2'])
# first element of each tuple in 'libraries'
# must be a string (the library name)
- self.assertRaises(DistutilsSetupError, cmd.check_library_list,
- [(1, 'foo1'), ('name', 'foo2')])
+ self.assertRaises(
+ DistutilsSetupError, cmd.check_library_list, [(1, 'foo1'), ('name', 'foo2')]
+ )
# library name may not contain directory separators
- self.assertRaises(DistutilsSetupError, cmd.check_library_list,
- [('name', 'foo1'),
- ('another/name', 'foo2')])
+ self.assertRaises(
+ DistutilsSetupError,
+ cmd.check_library_list,
+ [('name', 'foo1'), ('another/name', 'foo2')],
+ )
# second element of each tuple must be a dictionary (build info)
- self.assertRaises(DistutilsSetupError, cmd.check_library_list,
- [('name', {}),
- ('another', 'foo2')])
+ self.assertRaises(
+ DistutilsSetupError,
+ cmd.check_library_list,
+ [('name', {}), ('another', 'foo2')],
+ )
# those work
libs = [('name', {}), ('name', {'ok': 'good'})]
@@ -63,17 +65,21 @@ class BuildCLibTestCase(support.TempdirManager,
cmd.libraries = [('name', {'sources': ('a', 'b')})]
self.assertEqual(cmd.get_source_files(), ['a', 'b'])
- cmd.libraries = [('name', {'sources': ('a', 'b')}),
- ('name2', {'sources': ['c', 'd']})]
+ cmd.libraries = [
+ ('name', {'sources': ('a', 'b')}),
+ ('name2', {'sources': ['c', 'd']}),
+ ]
self.assertEqual(cmd.get_source_files(), ['a', 'b', 'c', 'd'])
def test_build_libraries(self):
pkg_dir, dist = self.create_dist()
cmd = build_clib(dist)
+
class FakeCompiler:
def compile(*args, **kw):
pass
+
create_static_lib = compile
cmd.compiler = FakeCompiler()
@@ -129,8 +135,10 @@ class BuildCLibTestCase(support.TempdirManager,
# let's check the result
self.assertIn('libfoo.a', os.listdir(build_temp))
+
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(BuildCLibTestCase)
+
if __name__ == "__main__":
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_build_ext.py b/setuptools/_distutils/tests/test_build_ext.py
index 920e4dc8..c42ceabd 100644
--- a/setuptools/_distutils/tests/test_build_ext.py
+++ b/setuptools/_distutils/tests/test_build_ext.py
@@ -6,12 +6,19 @@ import textwrap
from distutils.core import Distribution
from distutils.command.build_ext import build_ext
from distutils import sysconfig
-from distutils.tests.support import (TempdirManager, LoggingSilencer,
- copy_xxmodule_c, fixup_build_ext)
+from distutils.tests.support import (
+ TempdirManager,
+ LoggingSilencer,
+ copy_xxmodule_c,
+ fixup_build_ext,
+)
from distutils.extension import Extension
from distutils.errors import (
- CompileError, DistutilsPlatformError, DistutilsSetupError,
- UnknownFileError)
+ CompileError,
+ DistutilsPlatformError,
+ DistutilsSetupError,
+ UnknownFileError,
+)
import unittest
from test import support
@@ -23,17 +30,17 @@ from test.support.script_helper import assert_python_ok
ALREADY_TESTED = False
-class BuildExtTestCase(TempdirManager,
- LoggingSilencer,
- unittest.TestCase):
+class BuildExtTestCase(TempdirManager, LoggingSilencer, unittest.TestCase):
def setUp(self):
# Create a simple test environment
super(BuildExtTestCase, self).setUp()
self.tmp_dir = self.mkdtemp()
import site
+
self.old_user_base = site.USER_BASE
site.USER_BASE = self.mkdtemp()
from distutils.command import build_ext
+
build_ext.USER_BASE = site.USER_BASE
# bpo-30132: On Windows, a .pdb file may be created in the current
@@ -45,8 +52,10 @@ class BuildExtTestCase(TempdirManager,
def tearDown(self):
import site
+
site.USER_BASE = self.old_user_base
from distutils.command import build_ext
+
build_ext.USER_BASE = self.old_user_base
super(BuildExtTestCase, self).tearDown()
@@ -83,7 +92,8 @@ class BuildExtTestCase(TempdirManager,
else:
ALREADY_TESTED = type(self).__name__
- code = textwrap.dedent("""
+ code = textwrap.dedent(
+ """
tmp_dir = {self.tmp_dir!r}
import sys
@@ -109,7 +119,10 @@ class BuildExtTestCase(TempdirManager,
unittest.main()
- """.format(**locals()))
+ """.format(
+ **locals()
+ )
+ )
assert_python_ok('-c', code)
def test_solaris_enable_shared(self):
@@ -117,8 +130,9 @@ class BuildExtTestCase(TempdirManager,
cmd = self.build_ext(dist)
old = sys.platform
- sys.platform = 'sunos' # fooling finalize_options
- from distutils.sysconfig import _config_vars
+ sys.platform = 'sunos' # fooling finalize_options
+ from distutils.sysconfig import _config_vars
+
old_var = _config_vars.get('Py_ENABLE_SHARED')
_config_vars['Py_ENABLE_SHARED'] = 1
try:
@@ -135,12 +149,12 @@ class BuildExtTestCase(TempdirManager,
def test_user_site(self):
import site
+
dist = Distribution({'name': 'xx'})
cmd = self.build_ext(dist)
# making sure the user option is there
- options = [name for name, short, lable in
- cmd.user_options]
+ options = [name for name, short, lable in cmd.user_options]
self.assertIn('user', options)
# setting a value
@@ -169,8 +183,9 @@ class BuildExtTestCase(TempdirManager,
dist = Distribution({'name': 'xx', 'ext_modules': modules})
cmd = self.build_ext(dist)
cmd.ensure_finalized()
- self.assertRaises((UnknownFileError, CompileError),
- cmd.run) # should raise an error
+ self.assertRaises(
+ (UnknownFileError, CompileError), cmd.run
+ ) # should raise an error
modules = [Extension('foo', ['xxx'], optional=True)]
dist = Distribution({'name': 'xx', 'ext_modules': modules})
@@ -256,8 +271,7 @@ class BuildExtTestCase(TempdirManager,
cmd.finalize_options()
#'extensions' option must be a list of Extension instances
- self.assertRaises(DistutilsSetupError,
- cmd.check_extensions_list, 'foo')
+ self.assertRaises(DistutilsSetupError, cmd.check_extensions_list, 'foo')
# each element of 'ext_modules' option must be an
# Extension instance or 2-tuple
@@ -276,8 +290,7 @@ class BuildExtTestCase(TempdirManager,
self.assertRaises(DistutilsSetupError, cmd.check_extensions_list, exts)
# ok this one should pass
- exts = [('foo.bar', {'sources': [''], 'libraries': 'foo',
- 'some': 'bar'})]
+ exts = [('foo.bar', {'sources': [''], 'libraries': 'foo', 'some': 'bar'})]
cmd.check_extensions_list(exts)
ext = exts[0]
self.assertIsInstance(ext, Extension)
@@ -289,8 +302,17 @@ class BuildExtTestCase(TempdirManager,
self.assertFalse(hasattr(ext, 'some'))
# 'macros' element of build info dict must be 1- or 2-tuple
- exts = [('foo.bar', {'sources': [''], 'libraries': 'foo',
- 'some': 'bar', 'macros': [('1', '2', '3'), 'foo']})]
+ exts = [
+ (
+ 'foo.bar',
+ {
+ 'sources': [''],
+ 'libraries': 'foo',
+ 'some': 'bar',
+ 'macros': [('1', '2', '3'), 'foo'],
+ },
+ )
+ ]
self.assertRaises(DistutilsSetupError, cmd.check_extensions_list, exts)
exts[0][1]['macros'] = [('1', '2'), ('3',)]
@@ -337,8 +359,7 @@ class BuildExtTestCase(TempdirManager,
c_file = os.path.join(tmp_dir, 'foo.c')
self.write_file(c_file, 'void PyInit_foo(void) {}\n')
ext = Extension('foo', [c_file], optional=False)
- dist = Distribution({'name': 'xx',
- 'ext_modules': [ext]})
+ dist = Distribution({'name': 'xx', 'ext_modules': [ext]})
cmd = self.build_ext(dist)
fixup_build_ext(cmd)
cmd.ensure_finalized()
@@ -398,9 +419,9 @@ class BuildExtTestCase(TempdirManager,
def test_ext_fullpath(self):
ext = sysconfig.get_config_var('EXT_SUFFIX')
# building lxml.etree inplace
- #etree_c = os.path.join(self.tmp_dir, 'lxml.etree.c')
- #etree_ext = Extension('lxml.etree', [etree_c])
- #dist = Distribution({'name': 'lxml', 'ext_modules': [etree_ext]})
+ # etree_c = os.path.join(self.tmp_dir, 'lxml.etree.c')
+ # etree_ext = Extension('lxml.etree', [etree_c])
+ # dist = Distribution({'name': 'lxml', 'ext_modules': [etree_ext]})
dist = Distribution()
cmd = self.build_ext(dist)
cmd.inplace = 1
@@ -423,8 +444,7 @@ class BuildExtTestCase(TempdirManager,
build_py.package_dir = {}
cmd.distribution.packages = ['twisted', 'twisted.runner.portmap']
path = cmd.get_ext_fullpath('twisted.runner.portmap')
- wanted = os.path.join(curdir, 'tmpdir', 'twisted', 'runner',
- 'portmap' + ext)
+ wanted = os.path.join(curdir, 'tmpdir', 'twisted', 'runner', 'portmap' + ext)
self.assertEqual(wanted, path)
# building twisted.runner.portmap inplace
@@ -433,7 +453,6 @@ class BuildExtTestCase(TempdirManager,
wanted = os.path.join(curdir, 'twisted', 'runner', 'portmap' + ext)
self.assertEqual(wanted, path)
-
@unittest.skipUnless(sys.platform == 'darwin', 'test only relevant for MacOSX')
def test_deployment_target_default(self):
# Issue 9516: Test that, in the absence of the environment variable,
@@ -445,8 +464,9 @@ class BuildExtTestCase(TempdirManager,
def test_deployment_target_too_low(self):
# Issue 9516: Test that an extension module is not allowed to be
# compiled with a deployment target less than that of the interpreter.
- self.assertRaises(DistutilsPlatformError,
- self._try_compile_deployment_target, '>', '10.1')
+ self.assertRaises(
+ DistutilsPlatformError, self._try_compile_deployment_target, '>', '10.1'
+ )
@unittest.skipUnless(sys.platform == 'darwin', 'test only relevant for MacOSX')
def test_deployment_target_higher_ok(self):
@@ -475,7 +495,9 @@ class BuildExtTestCase(TempdirManager,
deptarget_c = os.path.join(self.tmp_dir, 'deptargetmodule.c')
with open(deptarget_c, 'w') as fp:
- fp.write(textwrap.dedent('''\
+ fp.write(
+ textwrap.dedent(
+ '''\
#include <AvailabilityMacros.h>
int dummy;
@@ -485,7 +507,10 @@ class BuildExtTestCase(TempdirManager,
#error "Unexpected target"
#endif
- ''' % operator))
+ '''
+ % operator
+ )
+ )
# get the deployment target that the interpreter was built with
target = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET')
@@ -506,12 +531,9 @@ class BuildExtTestCase(TempdirManager,
deptarget_ext = Extension(
'deptarget',
[deptarget_c],
- extra_compile_args=['-DTARGET=%s'%(target,)],
+ extra_compile_args=['-DTARGET=%s' % (target,)],
)
- dist = Distribution({
- 'name': 'deptarget',
- 'ext_modules': [deptarget_ext]
- })
+ dist = Distribution({'name': 'deptarget', 'ext_modules': [deptarget_ext]})
dist.package_dir = self.tmp_dir
cmd = self.build_ext(dist)
cmd.build_lib = self.tmp_dir
@@ -533,7 +555,6 @@ class BuildExtTestCase(TempdirManager,
class ParallelBuildExtTestCase(BuildExtTestCase):
-
def build_ext(self, *args, **kwargs):
build_ext = super().build_ext(*args, **kwargs)
build_ext.parallel = True
@@ -546,5 +567,6 @@ def test_suite():
suite.addTest(unittest.TestLoader().loadTestsFromTestCase(ParallelBuildExtTestCase))
return suite
+
if __name__ == '__main__':
support.run_unittest(__name__)
diff --git a/setuptools/_distutils/tests/test_build_py.py b/setuptools/_distutils/tests/test_build_py.py
index a590a485..4585d799 100644
--- a/setuptools/_distutils/tests/test_build_py.py
+++ b/setuptools/_distutils/tests/test_build_py.py
@@ -12,10 +12,9 @@ from distutils.tests import support
from test.support import run_unittest
-class BuildPyTestCase(support.TempdirManager,
- support.LoggingSilencer,
- unittest.TestCase):
-
+class BuildPyTestCase(
+ support.TempdirManager, support.LoggingSilencer, unittest.TestCase
+):
def test_package_data(self):
sources = self.mkdtemp()
f = open(os.path.join(sources, "__init__.py"), "w")
@@ -31,13 +30,10 @@ class BuildPyTestCase(support.TempdirManager,
destination = self.mkdtemp()
- dist = Distribution({"packages": ["pkg"],
- "package_dir": {"pkg": sources}})
+ dist = Distribution({"packages": ["pkg"], "package_dir": {"pkg": sources}})
# script_name need not exist, it just need to be initialized
dist.script_name = os.path.join(sources, "setup.py")
- dist.command_obj["build"] = support.DummyCommand(
- force=0,
- build_lib=destination)
+ dist.command_obj["build"] = support.DummyCommand(force=0, build_lib=destination)
dist.packages = ["pkg"]
dist.package_data = {"pkg": ["README.txt"]}
dist.package_dir = {"pkg": sources}
@@ -62,8 +58,7 @@ class BuildPyTestCase(support.TempdirManager,
self.assertFalse(os.path.exists(pycache_dir))
else:
pyc_files = os.listdir(pycache_dir)
- self.assertIn("__init__.%s.pyc" % sys.implementation.cache_tag,
- pyc_files)
+ self.assertIn("__init__.%s.pyc" % sys.implementation.cache_tag, pyc_files)
def test_empty_package_dir(self):
# See bugs #1668596/#1720897
@@ -75,9 +70,13 @@ class BuildPyTestCase(support.TempdirManager,
open(os.path.join(testdir, "testfile"), "w").close()
os.chdir(sources)
- dist = Distribution({"packages": ["pkg"],
- "package_dir": {"pkg": ""},
- "package_data": {"pkg": ["doc/*"]}})
+ dist = Distribution(
+ {
+ "packages": ["pkg"],
+ "package_dir": {"pkg": ""},
+ "package_data": {"pkg": ["doc/*"]},
+ }
+ )
# script_name need not exist, it just need to be initialized
dist.script_name = os.path.join(sources, "setup.py")
dist.script_args = ["build"]
@@ -102,8 +101,7 @@ class BuildPyTestCase(support.TempdirManager,
found = os.listdir(cmd.build_lib)
self.assertEqual(sorted(found), ['__pycache__', 'boiledeggs.py'])
found = os.listdir(os.path.join(cmd.build_lib, '__pycache__'))
- self.assertEqual(found,
- ['boiledeggs.%s.pyc' % sys.implementation.cache_tag])
+ self.assertEqual(found, ['boiledeggs.%s.pyc' % sys.implementation.cache_tag])
@unittest.skipIf(sys.dont_write_bytecode, 'byte-compile disabled')
def test_byte_compile_optimized(self):
@@ -142,8 +140,7 @@ class BuildPyTestCase(support.TempdirManager,
os.mkdir(os.path.join(docdir, 'otherdir'))
os.chdir(sources)
- dist = Distribution({"packages": ["pkg"],
- "package_data": {"pkg": ["doc/*"]}})
+ dist = Distribution({"packages": ["pkg"], "package_data": {"pkg": ["doc/*"]}})
# script_name need not exist, it just need to be initialized
dist.script_name = os.path.join(sources, "setup.py")
dist.script_args = ["build"]
@@ -168,12 +165,12 @@ class BuildPyTestCase(support.TempdirManager,
finally:
sys.dont_write_bytecode = old_dont_write_bytecode
- self.assertIn('byte-compiling is disabled',
- self.logs[0][1] % self.logs[0][2])
+ self.assertIn('byte-compiling is disabled', self.logs[0][1] % self.logs[0][2])
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(BuildPyTestCase)
+
if __name__ == "__main__":
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_build_scripts.py b/setuptools/_distutils/tests/test_build_scripts.py
index f299e51e..8c7061d7 100644
--- a/setuptools/_distutils/tests/test_build_scripts.py
+++ b/setuptools/_distutils/tests/test_build_scripts.py
@@ -11,10 +11,9 @@ from distutils.tests import support
from test.support import run_unittest
-class BuildScriptsTestCase(support.TempdirManager,
- support.LoggingSilencer,
- unittest.TestCase):
-
+class BuildScriptsTestCase(
+ support.TempdirManager, support.LoggingSilencer, unittest.TestCase
+):
def test_default_settings(self):
cmd = self.get_build_scripts_cmd("/foo/bar", [])
self.assertFalse(cmd.force)
@@ -30,9 +29,9 @@ class BuildScriptsTestCase(support.TempdirManager,
target = self.mkdtemp()
expected = self.write_sample_scripts(source)
- cmd = self.get_build_scripts_cmd(target,
- [os.path.join(source, fn)
- for fn in expected])
+ cmd = self.get_build_scripts_cmd(
+ target, [os.path.join(source, fn) for fn in expected]
+ )
cmd.finalize_options()
cmd.run()
@@ -42,32 +41,38 @@ class BuildScriptsTestCase(support.TempdirManager,
def get_build_scripts_cmd(self, target, scripts):
import sys
+
dist = Distribution()
dist.scripts = scripts
dist.command_obj["build"] = support.DummyCommand(
- build_scripts=target,
- force=1,
- executable=sys.executable
- )
+ build_scripts=target, force=1, executable=sys.executable
+ )
return build_scripts(dist)
def write_sample_scripts(self, dir):
expected = []
expected.append("script1.py")
- self.write_script(dir, "script1.py",
- ("#! /usr/bin/env python2.3\n"
- "# bogus script w/ Python sh-bang\n"
- "pass\n"))
+ self.write_script(
+ dir,
+ "script1.py",
+ (
+ "#! /usr/bin/env python2.3\n"
+ "# bogus script w/ Python sh-bang\n"
+ "pass\n"
+ ),
+ )
expected.append("script2.py")
- self.write_script(dir, "script2.py",
- ("#!/usr/bin/python\n"
- "# bogus script w/ Python sh-bang\n"
- "pass\n"))
+ self.write_script(
+ dir,
+ "script2.py",
+ ("#!/usr/bin/python\n" "# bogus script w/ Python sh-bang\n" "pass\n"),
+ )
expected.append("shell.sh")
- self.write_script(dir, "shell.sh",
- ("#!/bin/sh\n"
- "# bogus shell script w/ sh-bang\n"
- "exit 0\n"))
+ self.write_script(
+ dir,
+ "shell.sh",
+ ("#!/bin/sh\n" "# bogus shell script w/ sh-bang\n" "exit 0\n"),
+ )
return expected
def write_script(self, dir, name, text):
@@ -82,10 +87,9 @@ class BuildScriptsTestCase(support.TempdirManager,
target = self.mkdtemp()
expected = self.write_sample_scripts(source)
-
- cmd = self.get_build_scripts_cmd(target,
- [os.path.join(source, fn)
- for fn in expected])
+ cmd = self.get_build_scripts_cmd(
+ target, [os.path.join(source, fn) for fn in expected]
+ )
cmd.finalize_options()
# http://bugs.python.org/issue4524
@@ -105,8 +109,10 @@ class BuildScriptsTestCase(support.TempdirManager,
for name in expected:
self.assertIn(name, built)
+
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(BuildScriptsTestCase)
+
if __name__ == "__main__":
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_check.py b/setuptools/_distutils/tests/test_check.py
index b41dba3d..424c5e08 100644
--- a/setuptools/_distutils/tests/test_check.py
+++ b/setuptools/_distutils/tests/test_check.py
@@ -17,10 +17,7 @@ except ImportError:
HERE = os.path.dirname(__file__)
-class CheckTestCase(support.LoggingSilencer,
- support.TempdirManager,
- unittest.TestCase):
-
+class CheckTestCase(support.LoggingSilencer, support.TempdirManager, unittest.TestCase):
def _run(self, metadata=None, cwd=None, **options):
if metadata is None:
metadata = {}
@@ -43,14 +40,18 @@ class CheckTestCase(support.LoggingSilencer,
# by default, check is checking the metadata
# should have some warnings
cmd = self._run()
- self.assertEqual(cmd._warnings, 2)
+ self.assertEqual(cmd._warnings, 1)
# now let's add the required fields
# and run it again, to make sure we don't get
# any warning anymore
- metadata = {'url': 'xxx', 'author': 'xxx',
- 'author_email': 'xxx',
- 'name': 'xxx', 'version': 'xxx'}
+ metadata = {
+ 'url': 'xxx',
+ 'author': 'xxx',
+ 'author_email': 'xxx',
+ 'name': 'xxx',
+ 'version': 'xxx',
+ }
cmd = self._run(metadata)
self.assertEqual(cmd._warnings, 0)
@@ -63,11 +64,15 @@ class CheckTestCase(support.LoggingSilencer,
self.assertEqual(cmd._warnings, 0)
# now a test with non-ASCII characters
- metadata = {'url': 'xxx', 'author': '\u00c9ric',
- 'author_email': 'xxx', 'name': 'xxx',
- 'version': 'xxx',
- 'description': 'Something about esszet \u00df',
- 'long_description': 'More things about esszet \u00df'}
+ metadata = {
+ 'url': 'xxx',
+ 'author': '\u00c9ric',
+ 'author_email': 'xxx',
+ 'name': 'xxx',
+ 'version': 'xxx',
+ 'description': 'Something about esszet \u00df',
+ 'long_description': 'More things about esszet \u00df',
+ }
cmd = self._run(metadata)
self.assertEqual(cmd._warnings, 0)
@@ -75,23 +80,25 @@ class CheckTestCase(support.LoggingSilencer,
for kind in ("author", "maintainer"):
# ensure no warning when author_email or maintainer_email is given
# (the spec allows these fields to take the form "Name <email>")
- metadata = {'url': 'xxx',
- kind + '_email': 'Name <name@email.com>',
- 'name': 'xxx', 'version': 'xxx'}
+ metadata = {
+ 'url': 'xxx',
+ kind + '_email': 'Name <name@email.com>',
+ 'name': 'xxx',
+ 'version': 'xxx',
+ }
cmd = self._run(metadata)
self.assertEqual(cmd._warnings, 0)
- # the check should warn if only email is given and it does not
- # contain the name
+ # the check should not warn if only email is given
metadata[kind + '_email'] = 'name@email.com'
cmd = self._run(metadata)
- self.assertEqual(cmd._warnings, 1)
+ self.assertEqual(cmd._warnings, 0)
- # the check should warn if only the name is given
+ # the check should not warn if only the name is given
metadata[kind] = "Name"
del metadata[kind + '_email']
cmd = self._run(metadata)
- self.assertEqual(cmd._warnings, 1)
+ self.assertEqual(cmd._warnings, 0)
@unittest.skipUnless(HAS_DOCUTILS, "won't test without docutils")
def test_check_document(self):
@@ -118,12 +125,20 @@ class CheckTestCase(support.LoggingSilencer,
self.assertEqual(cmd._warnings, 1)
# let's see if we have an error with strict=1
- metadata = {'url': 'xxx', 'author': 'xxx',
- 'author_email': 'xxx',
- 'name': 'xxx', 'version': 'xxx',
- 'long_description': broken_rest}
- self.assertRaises(DistutilsSetupError, self._run, metadata,
- **{'strict': 1, 'restructuredtext': 1})
+ metadata = {
+ 'url': 'xxx',
+ 'author': 'xxx',
+ 'author_email': 'xxx',
+ 'name': 'xxx',
+ 'version': 'xxx',
+ 'long_description': broken_rest,
+ }
+ self.assertRaises(
+ DistutilsSetupError,
+ self._run,
+ metadata,
+ **{'strict': 1, 'restructuredtext': 1}
+ )
# and non-broken rest, including a non-ASCII character to test #12114
metadata['long_description'] = 'title\n=====\n\ntest \u00df'
@@ -140,22 +155,30 @@ class CheckTestCase(support.LoggingSilencer,
# Don't fail if there is a `code` or `code-block` directive
example_rst_docs = []
- example_rst_docs.append(textwrap.dedent("""\
+ example_rst_docs.append(
+ textwrap.dedent(
+ """\
Here's some code:
.. code:: python
def foo():
pass
- """))
- example_rst_docs.append(textwrap.dedent("""\
+ """
+ )
+ )
+ example_rst_docs.append(
+ textwrap.dedent(
+ """\
Here's some code:
.. code-block:: python
def foo():
pass
- """))
+ """
+ )
+ )
for rest_with_code in example_rst_docs:
pkg_info, dist = self.create_dist(long_description=rest_with_code)
@@ -167,19 +190,20 @@ class CheckTestCase(support.LoggingSilencer,
else:
self.assertEqual(len(msgs), 1)
self.assertEqual(
- str(msgs[0][1]),
- 'Cannot analyze code. Pygments package not found.'
+ str(msgs[0][1]), 'Cannot analyze code. Pygments package not found.'
)
def test_check_all(self):
metadata = {'url': 'xxx', 'author': 'xxx'}
- self.assertRaises(DistutilsSetupError, self._run,
- {}, **{'strict': 1,
- 'restructuredtext': 1})
+ self.assertRaises(
+ DistutilsSetupError, self._run, {}, **{'strict': 1, 'restructuredtext': 1}
+ )
+
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(CheckTestCase)
+
if __name__ == "__main__":
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_clean.py b/setuptools/_distutils/tests/test_clean.py
index 92367499..92e58f78 100644
--- a/setuptools/_distutils/tests/test_clean.py
+++ b/setuptools/_distutils/tests/test_clean.py
@@ -6,18 +6,23 @@ from distutils.command.clean import clean
from distutils.tests import support
from test.support import run_unittest
-class cleanTestCase(support.TempdirManager,
- support.LoggingSilencer,
- unittest.TestCase):
+class cleanTestCase(support.TempdirManager, support.LoggingSilencer, unittest.TestCase):
def test_simple_run(self):
pkg_dir, dist = self.create_dist()
cmd = clean(dist)
# let's add some elements clean should remove
- dirs = [(d, os.path.join(pkg_dir, d))
- for d in ('build_temp', 'build_lib', 'bdist_base',
- 'build_scripts', 'build_base')]
+ dirs = [
+ (d, os.path.join(pkg_dir, d))
+ for d in (
+ 'build_temp',
+ 'build_lib',
+ 'bdist_base',
+ 'build_scripts',
+ 'build_base',
+ )
+ ]
for name, path in dirs:
os.mkdir(path)
@@ -34,16 +39,17 @@ class cleanTestCase(support.TempdirManager,
# make sure the files where removed
for name, path in dirs:
- self.assertFalse(os.path.exists(path),
- '%s was not removed' % path)
+ self.assertFalse(os.path.exists(path), '%s was not removed' % path)
# let's run the command again (should spit warnings but succeed)
cmd.all = 1
cmd.ensure_finalized()
cmd.run()
+
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(cleanTestCase)
+
if __name__ == "__main__":
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_cmd.py b/setuptools/_distutils/tests/test_cmd.py
index 2319214a..12a8a20c 100644
--- a/setuptools/_distutils/tests/test_cmd.py
+++ b/setuptools/_distutils/tests/test_cmd.py
@@ -8,12 +8,13 @@ from distutils.dist import Distribution
from distutils.errors import DistutilsOptionError
from distutils import debug
+
class MyCmd(Command):
def initialize_options(self):
pass
-class CommandTestCase(unittest.TestCase):
+class CommandTestCase(unittest.TestCase):
def setUp(self):
dist = Distribution()
self.cmd = MyCmd(dist)
@@ -28,11 +29,13 @@ class CommandTestCase(unittest.TestCase):
cmd.ensure_string_list('yes_string_list')
cmd.ensure_string_list('yes_string_list2')
- self.assertRaises(DistutilsOptionError,
- cmd.ensure_string_list, 'not_string_list')
+ self.assertRaises(
+ DistutilsOptionError, cmd.ensure_string_list, 'not_string_list'
+ )
- self.assertRaises(DistutilsOptionError,
- cmd.ensure_string_list, 'not_string_list2')
+ self.assertRaises(
+ DistutilsOptionError, cmd.ensure_string_list, 'not_string_list2'
+ )
cmd.option1 = 'ok,dok'
cmd.ensure_string_list('option1')
@@ -42,21 +45,21 @@ class CommandTestCase(unittest.TestCase):
cmd.ensure_string_list('option2')
cmd.option3 = ['ok', 2]
- self.assertRaises(DistutilsOptionError, cmd.ensure_string_list,
- 'option3')
-
+ self.assertRaises(DistutilsOptionError, cmd.ensure_string_list, 'option3')
def test_make_file(self):
cmd = self.cmd
# making sure it raises when infiles is not a string or a list/tuple
- self.assertRaises(TypeError, cmd.make_file,
- infiles=1, outfile='', func='func', args=())
+ self.assertRaises(
+ TypeError, cmd.make_file, infiles=1, outfile='', func='func', args=()
+ )
# making sure execute gets called properly
def _execute(func, args, exec_msg, level):
self.assertEqual(exec_msg, 'generating out from in')
+
cmd.force = True
cmd.execute = _execute
cmd.make_file(infiles='in', outfile='out', func='func', args=())
@@ -64,8 +67,10 @@ class CommandTestCase(unittest.TestCase):
def test_dump_options(self):
msgs = []
+
def _announce(msg, level):
msgs.append(msg)
+
cmd = self.cmd
cmd.announce = _announce
cmd.option1 = 1
@@ -73,8 +78,7 @@ class CommandTestCase(unittest.TestCase):
cmd.user_options = [('option1', '', ''), ('option2', '', '')]
cmd.dump_options()
- wanted = ["command options for 'MyCmd':", ' option1 = 1',
- ' option2 = 1']
+ wanted = ["command options for 'MyCmd':", ' option1 = 1', ' option2 = 1']
self.assertEqual(msgs, wanted)
def test_ensure_string(self):
@@ -119,8 +123,10 @@ class CommandTestCase(unittest.TestCase):
finally:
debug.DEBUG = False
+
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(CommandTestCase)
+
if __name__ == '__main__':
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_config.py b/setuptools/_distutils/tests/test_config.py
index 27bd9d44..a4b48509 100644
--- a/setuptools/_distutils/tests/test_config.py
+++ b/setuptools/_distutils/tests/test_config.py
@@ -50,11 +50,12 @@ password:xxx
"""
-class BasePyPIRCCommandTestCase(support.TempdirManager,
- support.LoggingSilencer,
- support.EnvironGuard,
- unittest.TestCase):
-
+class BasePyPIRCCommandTestCase(
+ support.TempdirManager,
+ support.LoggingSilencer,
+ support.EnvironGuard,
+ unittest.TestCase,
+):
def setUp(self):
"""Patches the environment."""
super(BasePyPIRCCommandTestCase, self).setUp()
@@ -67,8 +68,10 @@ class BasePyPIRCCommandTestCase(support.TempdirManager,
class command(PyPIRCCommand):
def __init__(self, dist):
super().__init__(dist)
+
def initialize_options(self):
pass
+
finalize_options = initialize_options
self._cmd = command
@@ -81,7 +84,6 @@ class BasePyPIRCCommandTestCase(support.TempdirManager,
class PyPIRCCommandTestCase(BasePyPIRCCommandTestCase):
-
def test_server_registration(self):
# This test makes sure PyPIRCCommand knows how to:
# 1. handle several sections in .pypirc
@@ -93,18 +95,26 @@ class PyPIRCCommandTestCase(BasePyPIRCCommandTestCase):
config = cmd._read_pypirc()
config = list(sorted(config.items()))
- waited = [('password', 'secret'), ('realm', 'pypi'),
- ('repository', 'https://upload.pypi.org/legacy/'),
- ('server', 'server1'), ('username', 'me')]
+ waited = [
+ ('password', 'secret'),
+ ('realm', 'pypi'),
+ ('repository', 'https://upload.pypi.org/legacy/'),
+ ('server', 'server1'),
+ ('username', 'me'),
+ ]
self.assertEqual(config, waited)
# old format
self.write_file(self.rc, PYPIRC_OLD)
config = cmd._read_pypirc()
config = list(sorted(config.items()))
- waited = [('password', 'secret'), ('realm', 'pypi'),
- ('repository', 'https://upload.pypi.org/legacy/'),
- ('server', 'server-login'), ('username', 'tarek')]
+ waited = [
+ ('password', 'secret'),
+ ('realm', 'pypi'),
+ ('repository', 'https://upload.pypi.org/legacy/'),
+ ('server', 'server-login'),
+ ('username', 'tarek'),
+ ]
self.assertEqual(config, waited)
def test_server_empty_registration(self):
@@ -128,14 +138,19 @@ class PyPIRCCommandTestCase(BasePyPIRCCommandTestCase):
config = cmd._read_pypirc()
config = list(sorted(config.items()))
- waited = [('password', 'yh^%#rest-of-my-password'), ('realm', 'pypi'),
- ('repository', 'https://upload.pypi.org/legacy/'),
- ('server', 'server3'), ('username', 'cbiggles')]
+ waited = [
+ ('password', 'yh^%#rest-of-my-password'),
+ ('realm', 'pypi'),
+ ('repository', 'https://upload.pypi.org/legacy/'),
+ ('server', 'server3'),
+ ('username', 'cbiggles'),
+ ]
self.assertEqual(config, waited)
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(PyPIRCCommandTestCase)
+
if __name__ == "__main__":
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_config_cmd.py b/setuptools/_distutils/tests/test_config_cmd.py
index 2c84719a..0c1a9d25 100644
--- a/setuptools/_distutils/tests/test_config_cmd.py
+++ b/setuptools/_distutils/tests/test_config_cmd.py
@@ -2,18 +2,16 @@
import unittest
import os
import sys
-from test.support import run_unittest
-
-from .py35compat import missing_compiler_executable
+from test.support import run_unittest, missing_compiler_executable
from distutils.command.config import dump_file, config
from distutils.tests import support
from distutils import log
-class ConfigTestCase(support.LoggingSilencer,
- support.TempdirManager,
- unittest.TestCase):
+class ConfigTestCase(
+ support.LoggingSilencer, support.TempdirManager, unittest.TestCase
+):
def _info(self, msg, *args):
for line in msg.splitlines():
self._logs.append(line)
@@ -37,7 +35,7 @@ class ConfigTestCase(support.LoggingSilencer,
f.close()
dump_file(this_file, 'I am the header')
- self.assertEqual(len(self._logs), numlines+1)
+ self.assertEqual(len(self._logs), numlines + 1)
@unittest.skipIf(sys.platform == 'win32', "can't test on Windows")
def test_search_cpp(self):
@@ -49,7 +47,9 @@ class ConfigTestCase(support.LoggingSilencer,
cmd._check_compiler()
compiler = cmd.compiler
if sys.platform[:3] == "aix" and "xlc" in compiler.preprocessor[0].lower():
- self.skipTest('xlc: The -E option overrides the -P, -o, and -qsyntaxonly options')
+ self.skipTest(
+ 'xlc: The -E option overrides the -P, -o, and -qsyntaxonly options'
+ )
# simple pattern searches
match = cmd.search_cpp(pattern='xxx', body='/* xxx */')
@@ -91,8 +91,10 @@ class ConfigTestCase(support.LoggingSilencer,
for f in (f1, f2):
self.assertFalse(os.path.exists(f))
+
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(ConfigTestCase)
+
if __name__ == "__main__":
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_core.py b/setuptools/_distutils/tests/test_core.py
index 7270d699..23402fb8 100644
--- a/setuptools/_distutils/tests/test_core.py
+++ b/setuptools/_distutils/tests/test_core.py
@@ -56,8 +56,8 @@ if __name__ == "__main__":
main()
"""
-class CoreTestCase(support.EnvironGuard, unittest.TestCase):
+class CoreTestCase(support.EnvironGuard, unittest.TestCase):
def setUp(self):
super(CoreTestCase, self).setUp()
self.old_stdout = sys.stdout
@@ -90,21 +90,18 @@ class CoreTestCase(support.EnvironGuard, unittest.TestCase):
def test_run_setup_provides_file(self):
# Make sure the script can use __file__; if that's missing, the test
# setup.py script will raise NameError.
- distutils.core.run_setup(
- self.write_setup(setup_using___file__))
+ distutils.core.run_setup(self.write_setup(setup_using___file__))
def test_run_setup_preserves_sys_argv(self):
# Make sure run_setup does not clobber sys.argv
argv_copy = sys.argv.copy()
- distutils.core.run_setup(
- self.write_setup(setup_does_nothing))
+ distutils.core.run_setup(self.write_setup(setup_does_nothing))
self.assertEqual(sys.argv, argv_copy)
def test_run_setup_defines_subclass(self):
# Make sure the script can use __file__; if that's missing, the test
# setup.py script will raise NameError.
- dist = distutils.core.run_setup(
- self.write_setup(setup_defines_subclass))
+ dist = distutils.core.run_setup(self.write_setup(setup_defines_subclass))
install = dist.get_command_obj('install')
self.assertIn('cmd', install.sub_commands)
@@ -118,8 +115,7 @@ class CoreTestCase(support.EnvironGuard, unittest.TestCase):
# Create a directory and write the setup.py file there:
os.mkdir(os_helper.TESTFN)
setup_py = os.path.join(os_helper.TESTFN, "setup.py")
- distutils.core.run_setup(
- self.write_setup(setup_prints_cwd, path=setup_py))
+ distutils.core.run_setup(self.write_setup(setup_prints_cwd, path=setup_py))
output = sys.stdout.getvalue()
if output.endswith("\n"):
@@ -128,14 +124,16 @@ class CoreTestCase(support.EnvironGuard, unittest.TestCase):
def test_run_setup_within_if_main(self):
dist = distutils.core.run_setup(
- self.write_setup(setup_within_if_main), stop_after="config")
+ self.write_setup(setup_within_if_main), stop_after="config"
+ )
self.assertIsInstance(dist, Distribution)
self.assertEqual(dist.get_name(), "setup_within_if_main")
def test_run_commands(self):
sys.argv = ['setup.py', 'build']
dist = distutils.core.run_setup(
- self.write_setup(setup_within_if_main), stop_after="commandline")
+ self.write_setup(setup_within_if_main), stop_after="commandline"
+ )
self.assertNotIn('build', dist.have_run)
distutils.core.run_commands(dist)
self.assertIn('build', dist.have_run)
@@ -158,8 +156,10 @@ class CoreTestCase(support.EnvironGuard, unittest.TestCase):
wanted = "options (after parsing config files):\n"
self.assertEqual(stdout.readlines()[0], wanted)
+
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(CoreTestCase)
+
if __name__ == "__main__":
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_cygwinccompiler.py b/setuptools/_distutils/tests/test_cygwinccompiler.py
index 8715a535..b3c164ed 100644
--- a/setuptools/_distutils/tests/test_cygwinccompiler.py
+++ b/setuptools/_distutils/tests/test_cygwinccompiler.py
@@ -4,39 +4,58 @@ import sys
import os
from test.support import run_unittest
-from distutils.cygwinccompiler import (check_config_h,
- CONFIG_H_OK, CONFIG_H_NOTOK,
- CONFIG_H_UNCERTAIN,
- get_msvcr)
+from distutils.cygwinccompiler import (
+ check_config_h,
+ CONFIG_H_OK,
+ CONFIG_H_NOTOK,
+ CONFIG_H_UNCERTAIN,
+ get_msvcr,
+)
from distutils.tests import support
-class CygwinCCompilerTestCase(support.TempdirManager,
- unittest.TestCase):
-
+class CygwinCCompilerTestCase(support.TempdirManager, unittest.TestCase):
def setUp(self):
super(CygwinCCompilerTestCase, self).setUp()
self.version = sys.version
self.python_h = os.path.join(self.mkdtemp(), 'python.h')
from distutils import sysconfig
+
self.old_get_config_h_filename = sysconfig.get_config_h_filename
sysconfig.get_config_h_filename = self._get_config_h_filename
def tearDown(self):
sys.version = self.version
from distutils import sysconfig
+
sysconfig.get_config_h_filename = self.old_get_config_h_filename
super(CygwinCCompilerTestCase, self).tearDown()
def _get_config_h_filename(self):
return self.python_h
+ @unittest.skipIf(sys.platform != "cygwin", "Not running on Cygwin")
+ @unittest.skipIf(
+ not os.path.exists("/usr/lib/libbash.dll.a"), "Don't know a linkable library"
+ )
+ def test_find_library_file(self):
+ from distutils.cygwinccompiler import CygwinCCompiler
+
+ compiler = CygwinCCompiler()
+ link_name = "bash"
+ linkable_file = compiler.find_library_file(["/usr/lib"], link_name)
+ self.assertIsNotNone(linkable_file)
+ self.assertTrue(os.path.exists(linkable_file))
+ self.assertEquals(linkable_file, "/usr/lib/lib{:s}.dll.a".format(link_name))
+
def test_check_config_h(self):
# check_config_h looks for "GCC" in sys.version first
# returns CONFIG_H_OK if found
- sys.version = ('2.6.1 (r261:67515, Dec 6 2008, 16:42:21) \n[GCC '
- '4.0.1 (Apple Computer, Inc. build 5370)]')
+ sys.version = (
+ '2.6.1 (r261:67515, Dec 6 2008, 16:42:21) \n[GCC '
+ '4.0.1 (Apple Computer, Inc. build 5370)]'
+ )
self.assertEqual(check_config_h()[0], CONFIG_H_OK)
@@ -57,40 +76,49 @@ class CygwinCCompilerTestCase(support.TempdirManager,
def test_get_msvcr(self):
# none
- sys.version = ('2.6.1 (r261:67515, Dec 6 2008, 16:42:21) '
- '\n[GCC 4.0.1 (Apple Computer, Inc. build 5370)]')
+ sys.version = (
+ '2.6.1 (r261:67515, Dec 6 2008, 16:42:21) '
+ '\n[GCC 4.0.1 (Apple Computer, Inc. build 5370)]'
+ )
self.assertEqual(get_msvcr(), None)
# MSVC 7.0
- sys.version = ('2.5.1 (r251:54863, Apr 18 2007, 08:51:08) '
- '[MSC v.1300 32 bits (Intel)]')
+ sys.version = (
+ '2.5.1 (r251:54863, Apr 18 2007, 08:51:08) ' '[MSC v.1300 32 bits (Intel)]'
+ )
self.assertEqual(get_msvcr(), ['msvcr70'])
# MSVC 7.1
- sys.version = ('2.5.1 (r251:54863, Apr 18 2007, 08:51:08) '
- '[MSC v.1310 32 bits (Intel)]')
+ sys.version = (
+ '2.5.1 (r251:54863, Apr 18 2007, 08:51:08) ' '[MSC v.1310 32 bits (Intel)]'
+ )
self.assertEqual(get_msvcr(), ['msvcr71'])
# VS2005 / MSVC 8.0
- sys.version = ('2.5.1 (r251:54863, Apr 18 2007, 08:51:08) '
- '[MSC v.1400 32 bits (Intel)]')
+ sys.version = (
+ '2.5.1 (r251:54863, Apr 18 2007, 08:51:08) ' '[MSC v.1400 32 bits (Intel)]'
+ )
self.assertEqual(get_msvcr(), ['msvcr80'])
# VS2008 / MSVC 9.0
- sys.version = ('2.5.1 (r251:54863, Apr 18 2007, 08:51:08) '
- '[MSC v.1500 32 bits (Intel)]')
+ sys.version = (
+ '2.5.1 (r251:54863, Apr 18 2007, 08:51:08) ' '[MSC v.1500 32 bits (Intel)]'
+ )
self.assertEqual(get_msvcr(), ['msvcr90'])
-
+
sys.version = '3.10.0 (tags/v3.10.0:b494f59, Oct 4 2021, 18:46:30) [MSC v.1929 32 bit (Intel)]'
self.assertEqual(get_msvcr(), ['ucrt', 'vcruntime140'])
# unknown
- sys.version = ('2.5.1 (r251:54863, Apr 18 2007, 08:51:08) '
- '[MSC v.2000 32 bits (Intel)]')
+ sys.version = (
+ '2.5.1 (r251:54863, Apr 18 2007, 08:51:08) ' '[MSC v.2000 32 bits (Intel)]'
+ )
self.assertRaises(ValueError, get_msvcr)
+
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(CygwinCCompilerTestCase)
+
if __name__ == '__main__':
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_dep_util.py b/setuptools/_distutils/tests/test_dep_util.py
index 0d52740a..89ae05d1 100644
--- a/setuptools/_distutils/tests/test_dep_util.py
+++ b/setuptools/_distutils/tests/test_dep_util.py
@@ -7,8 +7,8 @@ from distutils.errors import DistutilsFileError
from distutils.tests import support
from test.support import run_unittest
-class DepUtilTestCase(support.TempdirManager, unittest.TestCase):
+class DepUtilTestCase(support.TempdirManager, unittest.TestCase):
def test_newer(self):
tmpdir = self.mkdtemp()
@@ -36,14 +36,13 @@ class DepUtilTestCase(support.TempdirManager, unittest.TestCase):
os.mkdir(targets)
one = os.path.join(sources, 'one')
two = os.path.join(sources, 'two')
- three = os.path.abspath(__file__) # I am the old file
+ three = os.path.abspath(__file__) # I am the old file
four = os.path.join(targets, 'four')
self.write_file(one)
self.write_file(two)
self.write_file(four)
- self.assertEqual(newer_pairwise([one, two], [three, four]),
- ([one],[three]))
+ self.assertEqual(newer_pairwise([one, two], [three, four]), ([one], [three]))
def test_newer_group(self):
tmpdir = self.mkdtemp()
@@ -66,15 +65,14 @@ class DepUtilTestCase(support.TempdirManager, unittest.TestCase):
os.remove(one)
self.assertRaises(OSError, newer_group, [one, two, old_file], three)
- self.assertFalse(newer_group([one, two, old_file], three,
- missing='ignore'))
+ self.assertFalse(newer_group([one, two, old_file], three, missing='ignore'))
- self.assertTrue(newer_group([one, two, old_file], three,
- missing='newer'))
+ self.assertTrue(newer_group([one, two, old_file], three, missing='newer'))
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(DepUtilTestCase)
+
if __name__ == "__main__":
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_dir_util.py b/setuptools/_distutils/tests/test_dir_util.py
index 1b1f3bbb..a1f9a240 100644
--- a/setuptools/_distutils/tests/test_dir_util.py
+++ b/setuptools/_distutils/tests/test_dir_util.py
@@ -6,8 +6,13 @@ import sys
from unittest.mock import patch
from distutils import dir_util, errors
-from distutils.dir_util import (mkpath, remove_tree, create_tree, copy_tree,
- ensure_relative)
+from distutils.dir_util import (
+ mkpath,
+ remove_tree,
+ create_tree,
+ copy_tree,
+ ensure_relative,
+)
from distutils import log
from distutils.tests import support
@@ -15,7 +20,6 @@ from test.support import run_unittest
class DirUtilTestCase(support.TempdirManager, unittest.TestCase):
-
def _log(self, msg, *args):
if len(args) > 0:
self._logs.append(msg % args)
@@ -44,8 +48,7 @@ class DirUtilTestCase(support.TempdirManager, unittest.TestCase):
remove_tree(self.root_target, verbose=0)
mkpath(self.target, verbose=1)
- wanted = ['creating %s' % self.root_target,
- 'creating %s' % self.target]
+ wanted = ['creating %s' % self.root_target, 'creating %s' % self.target]
self.assertEqual(self._logs, wanted)
self._logs = []
@@ -53,18 +56,18 @@ class DirUtilTestCase(support.TempdirManager, unittest.TestCase):
wanted = ["removing '%s' (and everything under it)" % self.root_target]
self.assertEqual(self._logs, wanted)
- @unittest.skipIf(sys.platform.startswith('win'),
- "This test is only appropriate for POSIX-like systems.")
+ @unittest.skipIf(
+ sys.platform.startswith('win'),
+ "This test is only appropriate for POSIX-like systems.",
+ )
def test_mkpath_with_custom_mode(self):
# Get and set the current umask value for testing mode bits.
umask = os.umask(0o002)
os.umask(umask)
mkpath(self.target, 0o700)
- self.assertEqual(
- stat.S_IMODE(os.stat(self.target).st_mode), 0o700 & ~umask)
+ self.assertEqual(stat.S_IMODE(os.stat(self.target).st_mode), 0o700 & ~umask)
mkpath(self.target2, 0o555)
- self.assertEqual(
- stat.S_IMODE(os.stat(self.target2).st_mode), 0o555 & ~umask)
+ self.assertEqual(stat.S_IMODE(os.stat(self.target2).st_mode), 0o555 & ~umask)
def test_create_tree_verbosity(self):
@@ -118,7 +121,7 @@ class DirUtilTestCase(support.TempdirManager, unittest.TestCase):
if os.sep == '/':
self.assertEqual(ensure_relative('/home/foo'), 'home/foo')
self.assertEqual(ensure_relative('some/path'), 'some/path')
- else: # \\
+ else: # \\
self.assertEqual(ensure_relative('c:\\home\\foo'), 'c:home\\foo')
self.assertEqual(ensure_relative('home\\foo'), 'home\\foo')
@@ -126,8 +129,9 @@ class DirUtilTestCase(support.TempdirManager, unittest.TestCase):
"""
An exception in listdir should raise a DistutilsFileError
"""
- with patch("os.listdir", side_effect=OSError()), \
- self.assertRaises(errors.DistutilsFileError):
+ with patch("os.listdir", side_effect=OSError()), self.assertRaises(
+ errors.DistutilsFileError
+ ):
src = self.tempdirs[-1]
dir_util.copy_tree(src, None)
@@ -135,5 +139,6 @@ class DirUtilTestCase(support.TempdirManager, unittest.TestCase):
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(DirUtilTestCase)
+
if __name__ == "__main__":
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_dist.py b/setuptools/_distutils/tests/test_dist.py
index 36155be1..6520a46d 100644
--- a/setuptools/_distutils/tests/test_dist.py
+++ b/setuptools/_distutils/tests/test_dist.py
@@ -11,9 +11,7 @@ from unittest import mock
from distutils.dist import Distribution, fix_help_options
from distutils.cmd import Command
-from test.support import (
- captured_stdout, captured_stderr, run_unittest
-)
+from test.support import captured_stdout, captured_stderr, run_unittest
from .py38compat import TESTFN
from distutils.tests import support
from distutils import log
@@ -42,11 +40,12 @@ class TestDistribution(Distribution):
return self._config_files
-class DistributionTestCase(support.LoggingSilencer,
- support.TempdirManager,
- support.EnvironGuard,
- unittest.TestCase):
-
+class DistributionTestCase(
+ support.LoggingSilencer,
+ support.TempdirManager,
+ support.EnvironGuard,
+ unittest.TestCase,
+):
def setUp(self):
super(DistributionTestCase, self).setUp()
self.argv = sys.argv, sys.argv[:]
@@ -71,15 +70,21 @@ class DistributionTestCase(support.LoggingSilencer,
def test_command_packages_cmdline(self):
from distutils.tests.test_dist import test_dist
- sys.argv.extend(["--command-packages",
- "foo.bar,distutils.tests",
- "test_dist",
- "-Ssometext",
- ])
+
+ sys.argv.extend(
+ [
+ "--command-packages",
+ "foo.bar,distutils.tests",
+ "test_dist",
+ "-Ssometext",
+ ]
+ )
d = self.create_distribution()
# let's actually try to load our test command:
- self.assertEqual(d.get_command_packages(),
- ["distutils.command", "foo.bar", "distutils.tests"])
+ self.assertEqual(
+ d.get_command_packages(),
+ ["distutils.command", "foo.bar", "distutils.tests"],
+ )
cmd = d.get_command_obj("test_dist")
self.assertIsInstance(cmd, test_dist)
self.assertEqual(cmd.sample_option, "sometext")
@@ -95,20 +100,25 @@ class DistributionTestCase(support.LoggingSilencer,
fakepath = '/somedir'
with open(TESTFN, "w") as f:
- print(("[install]\n"
- "install-base = {0}\n"
- "install-platbase = {0}\n"
- "install-lib = {0}\n"
- "install-platlib = {0}\n"
- "install-purelib = {0}\n"
- "install-headers = {0}\n"
- "install-scripts = {0}\n"
- "install-data = {0}\n"
- "prefix = {0}\n"
- "exec-prefix = {0}\n"
- "home = {0}\n"
- "user = {0}\n"
- "root = {0}").format(fakepath), file=f)
+ print(
+ (
+ "[install]\n"
+ "install-base = {0}\n"
+ "install-platbase = {0}\n"
+ "install-lib = {0}\n"
+ "install-platlib = {0}\n"
+ "install-purelib = {0}\n"
+ "install-headers = {0}\n"
+ "install-scripts = {0}\n"
+ "install-data = {0}\n"
+ "prefix = {0}\n"
+ "exec-prefix = {0}\n"
+ "home = {0}\n"
+ "user = {0}\n"
+ "root = {0}"
+ ).format(fakepath),
+ file=f,
+ )
# Base case: Not in a Virtual Environment
with mock.patch.multiple(sys, prefix='/a', base_prefix='/a') as values:
@@ -133,8 +143,8 @@ class DistributionTestCase(support.LoggingSilencer,
}
self.assertEqual(
- sorted(d.command_options.get('install').keys()),
- sorted(result_dict.keys()))
+ sorted(d.command_options.get('install').keys()), sorted(result_dict.keys())
+ )
for (key, value) in d.command_options.get('install').items():
self.assertEqual(value, result_dict[key])
@@ -157,14 +167,14 @@ class DistributionTestCase(support.LoggingSilencer,
f.close()
d = self.create_distribution([TESTFN])
- self.assertEqual(d.get_command_packages(),
- ["distutils.command", "foo.bar", "splat"])
+ self.assertEqual(
+ d.get_command_packages(), ["distutils.command", "foo.bar", "splat"]
+ )
# ensure command line overrides config:
sys.argv[1:] = ["--command-packages", "spork", "build"]
d = self.create_distribution([TESTFN])
- self.assertEqual(d.get_command_packages(),
- ["distutils.command", "spork"])
+ self.assertEqual(d.get_command_packages(), ["distutils.command", "spork"])
# Setting --command-packages to '' should cause the default to
# be used even if a config file specified something else:
@@ -184,16 +194,21 @@ class DistributionTestCase(support.LoggingSilencer,
self.addCleanup(setattr, warnings, 'warn', warnings.warn)
warnings.warn = _warn
- dist = Distribution(attrs={'author': 'xxx', 'name': 'xxx',
- 'version': 'xxx', 'url': 'xxxx',
- 'options': {}})
+ dist = Distribution(
+ attrs={
+ 'author': 'xxx',
+ 'name': 'xxx',
+ 'version': 'xxx',
+ 'url': 'xxxx',
+ 'options': {},
+ }
+ )
self.assertEqual(len(warns), 0)
self.assertNotIn('options', dir(dist))
def test_finalize_options(self):
- attrs = {'keywords': 'one,two',
- 'platforms': 'one,two'}
+ attrs = {'keywords': 'one,two', 'platforms': 'one,two'}
dist = Distribution(attrs=attrs)
dist.finalize_options()
@@ -202,8 +217,7 @@ class DistributionTestCase(support.LoggingSilencer,
self.assertEqual(dist.metadata.platforms, ['one', 'two'])
self.assertEqual(dist.metadata.keywords, ['one', 'two'])
- attrs = {'keywords': 'foo bar',
- 'platforms': 'foo bar'}
+ attrs = {'keywords': 'foo bar', 'platforms': 'foo bar'}
dist = Distribution(attrs=attrs)
dist.finalize_options()
self.assertEqual(dist.metadata.platforms, ['foo bar'])
@@ -214,8 +228,7 @@ class DistributionTestCase(support.LoggingSilencer,
self.assertEqual(dist.command_packages, None)
cmds = dist.get_command_packages()
self.assertEqual(cmds, ['distutils.command'])
- self.assertEqual(dist.command_packages,
- ['distutils.command'])
+ self.assertEqual(dist.command_packages, ['distutils.command'])
dist.command_packages = 'one,two'
cmds = dist.get_command_packages()
@@ -228,7 +241,6 @@ class DistributionTestCase(support.LoggingSilencer,
kwargs = {'level': 'ok2'}
self.assertRaises(ValueError, dist.announce, args, kwargs)
-
def test_find_config_files_disable(self):
# Ticket #1180: Allow user to disable their home config file.
temp_home = self.mkdtemp()
@@ -255,11 +267,10 @@ class DistributionTestCase(support.LoggingSilencer,
os.path.expanduser = old_expander
# make sure --no-user-cfg disables the user cfg file
- self.assertEqual(len(all_files)-1, len(files))
+ self.assertEqual(len(all_files) - 1, len(files))
-class MetadataTestCase(support.TempdirManager, support.EnvironGuard,
- unittest.TestCase):
+class MetadataTestCase(support.TempdirManager, support.EnvironGuard, unittest.TestCase):
def setUp(self):
super(MetadataTestCase, self).setUp()
self.argv = sys.argv, sys.argv[:]
@@ -275,8 +286,7 @@ class MetadataTestCase(support.TempdirManager, support.EnvironGuard,
return sio.getvalue()
def test_simple_metadata(self):
- attrs = {"name": "package",
- "version": "1.0"}
+ attrs = {"name": "package", "version": "1.0"}
dist = Distribution(attrs)
meta = self.format_metadata(dist)
self.assertIn("Metadata-Version: 1.0", meta)
@@ -285,34 +295,35 @@ class MetadataTestCase(support.TempdirManager, support.EnvironGuard,
self.assertNotIn("obsoletes:", meta.lower())
def test_provides(self):
- attrs = {"name": "package",
- "version": "1.0",
- "provides": ["package", "package.sub"]}
+ attrs = {
+ "name": "package",
+ "version": "1.0",
+ "provides": ["package", "package.sub"],
+ }
dist = Distribution(attrs)
- self.assertEqual(dist.metadata.get_provides(),
- ["package", "package.sub"])
- self.assertEqual(dist.get_provides(),
- ["package", "package.sub"])
+ self.assertEqual(dist.metadata.get_provides(), ["package", "package.sub"])
+ self.assertEqual(dist.get_provides(), ["package", "package.sub"])
meta = self.format_metadata(dist)
self.assertIn("Metadata-Version: 1.1", meta)
self.assertNotIn("requires:", meta.lower())
self.assertNotIn("obsoletes:", meta.lower())
def test_provides_illegal(self):
- self.assertRaises(ValueError, Distribution,
- {"name": "package",
- "version": "1.0",
- "provides": ["my.pkg (splat)"]})
+ self.assertRaises(
+ ValueError,
+ Distribution,
+ {"name": "package", "version": "1.0", "provides": ["my.pkg (splat)"]},
+ )
def test_requires(self):
- attrs = {"name": "package",
- "version": "1.0",
- "requires": ["other", "another (==1.0)"]}
+ attrs = {
+ "name": "package",
+ "version": "1.0",
+ "requires": ["other", "another (==1.0)"],
+ }
dist = Distribution(attrs)
- self.assertEqual(dist.metadata.get_requires(),
- ["other", "another (==1.0)"])
- self.assertEqual(dist.get_requires(),
- ["other", "another (==1.0)"])
+ self.assertEqual(dist.metadata.get_requires(), ["other", "another (==1.0)"])
+ self.assertEqual(dist.get_requires(), ["other", "another (==1.0)"])
meta = self.format_metadata(dist)
self.assertIn("Metadata-Version: 1.1", meta)
self.assertNotIn("provides:", meta.lower())
@@ -321,27 +332,26 @@ class MetadataTestCase(support.TempdirManager, support.EnvironGuard,
self.assertNotIn("obsoletes:", meta.lower())
def test_requires_illegal(self):
- self.assertRaises(ValueError, Distribution,
- {"name": "package",
- "version": "1.0",
- "requires": ["my.pkg (splat)"]})
+ self.assertRaises(
+ ValueError,
+ Distribution,
+ {"name": "package", "version": "1.0", "requires": ["my.pkg (splat)"]},
+ )
def test_requires_to_list(self):
- attrs = {"name": "package",
- "requires": iter(["other"])}
+ attrs = {"name": "package", "requires": iter(["other"])}
dist = Distribution(attrs)
self.assertIsInstance(dist.metadata.requires, list)
-
def test_obsoletes(self):
- attrs = {"name": "package",
- "version": "1.0",
- "obsoletes": ["other", "another (<1.0)"]}
+ attrs = {
+ "name": "package",
+ "version": "1.0",
+ "obsoletes": ["other", "another (<1.0)"],
+ }
dist = Distribution(attrs)
- self.assertEqual(dist.metadata.get_obsoletes(),
- ["other", "another (<1.0)"])
- self.assertEqual(dist.get_obsoletes(),
- ["other", "another (<1.0)"])
+ self.assertEqual(dist.metadata.get_obsoletes(), ["other", "another (<1.0)"])
+ self.assertEqual(dist.get_obsoletes(), ["other", "another (<1.0)"])
meta = self.format_metadata(dist)
self.assertIn("Metadata-Version: 1.1", meta)
self.assertNotIn("provides:", meta.lower())
@@ -350,48 +360,59 @@ class MetadataTestCase(support.TempdirManager, support.EnvironGuard,
self.assertIn("Obsoletes: another (<1.0)", meta)
def test_obsoletes_illegal(self):
- self.assertRaises(ValueError, Distribution,
- {"name": "package",
- "version": "1.0",
- "obsoletes": ["my.pkg (splat)"]})
+ self.assertRaises(
+ ValueError,
+ Distribution,
+ {"name": "package", "version": "1.0", "obsoletes": ["my.pkg (splat)"]},
+ )
def test_obsoletes_to_list(self):
- attrs = {"name": "package",
- "obsoletes": iter(["other"])}
+ attrs = {"name": "package", "obsoletes": iter(["other"])}
dist = Distribution(attrs)
self.assertIsInstance(dist.metadata.obsoletes, list)
def test_classifier(self):
- attrs = {'name': 'Boa', 'version': '3.0',
- 'classifiers': ['Programming Language :: Python :: 3']}
+ attrs = {
+ 'name': 'Boa',
+ 'version': '3.0',
+ 'classifiers': ['Programming Language :: Python :: 3'],
+ }
dist = Distribution(attrs)
- self.assertEqual(dist.get_classifiers(),
- ['Programming Language :: Python :: 3'])
+ self.assertEqual(
+ dist.get_classifiers(), ['Programming Language :: Python :: 3']
+ )
meta = self.format_metadata(dist)
self.assertIn('Metadata-Version: 1.1', meta)
def test_classifier_invalid_type(self):
- attrs = {'name': 'Boa', 'version': '3.0',
- 'classifiers': ('Programming Language :: Python :: 3',)}
+ attrs = {
+ 'name': 'Boa',
+ 'version': '3.0',
+ 'classifiers': ('Programming Language :: Python :: 3',),
+ }
with captured_stderr() as error:
d = Distribution(attrs)
# should have warning about passing a non-list
self.assertIn('should be a list', error.getvalue())
# should be converted to a list
self.assertIsInstance(d.metadata.classifiers, list)
- self.assertEqual(d.metadata.classifiers,
- list(attrs['classifiers']))
+ self.assertEqual(d.metadata.classifiers, list(attrs['classifiers']))
def test_keywords(self):
- attrs = {'name': 'Monty', 'version': '1.0',
- 'keywords': ['spam', 'eggs', 'life of brian']}
+ attrs = {
+ 'name': 'Monty',
+ 'version': '1.0',
+ 'keywords': ['spam', 'eggs', 'life of brian'],
+ }
dist = Distribution(attrs)
- self.assertEqual(dist.get_keywords(),
- ['spam', 'eggs', 'life of brian'])
+ self.assertEqual(dist.get_keywords(), ['spam', 'eggs', 'life of brian'])
def test_keywords_invalid_type(self):
- attrs = {'name': 'Monty', 'version': '1.0',
- 'keywords': ('spam', 'eggs', 'life of brian')}
+ attrs = {
+ 'name': 'Monty',
+ 'version': '1.0',
+ 'keywords': ('spam', 'eggs', 'life of brian'),
+ }
with captured_stderr() as error:
d = Distribution(attrs)
# should have warning about passing a non-list
@@ -401,15 +422,20 @@ class MetadataTestCase(support.TempdirManager, support.EnvironGuard,
self.assertEqual(d.metadata.keywords, list(attrs['keywords']))
def test_platforms(self):
- attrs = {'name': 'Monty', 'version': '1.0',
- 'platforms': ['GNU/Linux', 'Some Evil Platform']}
+ attrs = {
+ 'name': 'Monty',
+ 'version': '1.0',
+ 'platforms': ['GNU/Linux', 'Some Evil Platform'],
+ }
dist = Distribution(attrs)
- self.assertEqual(dist.get_platforms(),
- ['GNU/Linux', 'Some Evil Platform'])
+ self.assertEqual(dist.get_platforms(), ['GNU/Linux', 'Some Evil Platform'])
def test_platforms_invalid_types(self):
- attrs = {'name': 'Monty', 'version': '1.0',
- 'platforms': ('GNU/Linux', 'Some Evil Platform')}
+ attrs = {
+ 'name': 'Monty',
+ 'version': '1.0',
+ 'platforms': ('GNU/Linux', 'Some Evil Platform'),
+ }
with captured_stderr() as error:
d = Distribution(attrs)
# should have warning about passing a non-list
@@ -419,21 +445,24 @@ class MetadataTestCase(support.TempdirManager, support.EnvironGuard,
self.assertEqual(d.metadata.platforms, list(attrs['platforms']))
def test_download_url(self):
- attrs = {'name': 'Boa', 'version': '3.0',
- 'download_url': 'http://example.org/boa'}
+ attrs = {
+ 'name': 'Boa',
+ 'version': '3.0',
+ 'download_url': 'http://example.org/boa',
+ }
dist = Distribution(attrs)
meta = self.format_metadata(dist)
self.assertIn('Metadata-Version: 1.1', meta)
def test_long_description(self):
- long_desc = textwrap.dedent("""\
+ long_desc = textwrap.dedent(
+ """\
example::
We start here
and continue here
- and end here.""")
- attrs = {"name": "package",
- "version": "1.0",
- "long_description": long_desc}
+ and end here."""
+ )
+ attrs = {"name": "package", "version": "1.0", "long_description": long_desc}
dist = Distribution(attrs)
meta = self.format_metadata(dist)
@@ -470,8 +499,9 @@ class MetadataTestCase(support.TempdirManager, support.EnvironGuard,
# home drive should be found
os.environ['USERPROFILE'] = temp_dir
files = dist.find_config_files()
- self.assertIn(user_filename, files,
- '%r not found in %r' % (user_filename, files))
+ self.assertIn(
+ user_filename, files, '%r not found in %r' % (user_filename, files)
+ )
finally:
os.remove(user_filename)
@@ -491,19 +521,19 @@ class MetadataTestCase(support.TempdirManager, support.EnvironGuard,
with captured_stdout() as s:
dist.parse_command_line()
- output = [line for line in s.getvalue().split('\n')
- if line.strip() != '']
+ output = [line for line in s.getvalue().split('\n') if line.strip() != '']
self.assertTrue(output)
-
def test_read_metadata(self):
- attrs = {"name": "package",
- "version": "1.0",
- "long_description": "desc",
- "description": "xxx",
- "download_url": "http://example.com",
- "keywords": ['one', 'two'],
- "requires": ['foo']}
+ attrs = {
+ "name": "package",
+ "version": "1.0",
+ "long_description": "desc",
+ "description": "xxx",
+ "download_url": "http://example.com",
+ "keywords": ['one', 'two'],
+ "requires": ['foo'],
+ }
dist = Distribution(attrs)
metadata = dist.metadata
@@ -519,15 +549,17 @@ class MetadataTestCase(support.TempdirManager, support.EnvironGuard,
self.assertEqual(metadata.description, "xxx")
self.assertEqual(metadata.download_url, 'http://example.com')
self.assertEqual(metadata.keywords, ['one', 'two'])
- self.assertEqual(metadata.platforms, ['UNKNOWN'])
+ self.assertEqual(metadata.platforms, None)
self.assertEqual(metadata.obsoletes, None)
self.assertEqual(metadata.requires, ['foo'])
+
def test_suite():
suite = unittest.TestSuite()
suite.addTest(unittest.TestLoader().loadTestsFromTestCase(DistributionTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase(MetadataTestCase))
return suite
+
if __name__ == "__main__":
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_extension.py b/setuptools/_distutils/tests/test_extension.py
index 78a55daa..77fe3f82 100644
--- a/setuptools/_distutils/tests/test_extension.py
+++ b/setuptools/_distutils/tests/test_extension.py
@@ -8,8 +8,8 @@ from distutils.extension import read_setup_file, Extension
from .py38compat import check_warnings
-class ExtensionTestCase(unittest.TestCase):
+class ExtensionTestCase(unittest.TestCase):
def test_read_setup_file(self):
# trying to read a Setup file
# (sample extracted from the PyGame project)
@@ -21,14 +21,42 @@ class ExtensionTestCase(unittest.TestCase):
# here are the extensions read_setup_file should have created
# out of the file
- wanted = ['_arraysurfarray', '_camera', '_numericsndarray',
- '_numericsurfarray', 'base', 'bufferproxy', 'cdrom',
- 'color', 'constants', 'display', 'draw', 'event',
- 'fastevent', 'font', 'gfxdraw', 'image', 'imageext',
- 'joystick', 'key', 'mask', 'mixer', 'mixer_music',
- 'mouse', 'movie', 'overlay', 'pixelarray', 'pypm',
- 'rect', 'rwobject', 'scrap', 'surface', 'surflock',
- 'time', 'transform']
+ wanted = [
+ '_arraysurfarray',
+ '_camera',
+ '_numericsndarray',
+ '_numericsurfarray',
+ 'base',
+ 'bufferproxy',
+ 'cdrom',
+ 'color',
+ 'constants',
+ 'display',
+ 'draw',
+ 'event',
+ 'fastevent',
+ 'font',
+ 'gfxdraw',
+ 'image',
+ 'imageext',
+ 'joystick',
+ 'key',
+ 'mask',
+ 'mixer',
+ 'mixer_music',
+ 'mouse',
+ 'movie',
+ 'overlay',
+ 'pixelarray',
+ 'pypm',
+ 'rect',
+ 'rwobject',
+ 'scrap',
+ 'surface',
+ 'surflock',
+ 'time',
+ 'transform',
+ ]
self.assertEqual(names, wanted)
@@ -46,10 +74,20 @@ class ExtensionTestCase(unittest.TestCase):
self.assertEqual(ext.sources, ['file1', 'file2'])
# others arguments have defaults
- for attr in ('include_dirs', 'define_macros', 'undef_macros',
- 'library_dirs', 'libraries', 'runtime_library_dirs',
- 'extra_objects', 'extra_compile_args', 'extra_link_args',
- 'export_symbols', 'swig_opts', 'depends'):
+ for attr in (
+ 'include_dirs',
+ 'define_macros',
+ 'undef_macros',
+ 'library_dirs',
+ 'libraries',
+ 'runtime_library_dirs',
+ 'extra_objects',
+ 'extra_compile_args',
+ 'extra_link_args',
+ 'export_symbols',
+ 'swig_opts',
+ 'depends',
+ ):
self.assertEqual(getattr(ext, attr), [])
self.assertEqual(ext.language, None)
@@ -61,11 +99,14 @@ class ExtensionTestCase(unittest.TestCase):
ext = Extension('name', ['file1', 'file2'], chic=True)
self.assertEqual(len(w.warnings), 1)
- self.assertEqual(str(w.warnings[0].message),
- "Unknown Extension options: 'chic'")
+ self.assertEqual(
+ str(w.warnings[0].message), "Unknown Extension options: 'chic'"
+ )
+
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(ExtensionTestCase)
+
if __name__ == "__main__":
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_file_util.py b/setuptools/_distutils/tests/test_file_util.py
index 81b90d6c..22898b95 100644
--- a/setuptools/_distutils/tests/test_file_util.py
+++ b/setuptools/_distutils/tests/test_file_util.py
@@ -13,7 +13,6 @@ from .py38compat import unlink
class FileUtilTestCase(support.TempdirManager, unittest.TestCase):
-
def _log(self, msg, *args):
if len(args) > 0:
self._logs.append(msg % args)
@@ -64,17 +63,18 @@ class FileUtilTestCase(support.TempdirManager, unittest.TestCase):
def test_move_file_exception_unpacking_rename(self):
# see issue 22182
- with patch("os.rename", side_effect=OSError("wrong", 1)), \
- self.assertRaises(DistutilsFileError):
+ with patch("os.rename", side_effect=OSError("wrong", 1)), self.assertRaises(
+ DistutilsFileError
+ ):
with open(self.source, 'w') as fobj:
fobj.write('spam eggs')
move_file(self.source, self.target, verbose=0)
def test_move_file_exception_unpacking_unlink(self):
# see issue 22182
- with patch("os.rename", side_effect=OSError(errno.EXDEV, "wrong")), \
- patch("os.unlink", side_effect=OSError("wrong", 1)), \
- self.assertRaises(DistutilsFileError):
+ with patch("os.rename", side_effect=OSError(errno.EXDEV, "wrong")), patch(
+ "os.unlink", side_effect=OSError("wrong", 1)
+ ), self.assertRaises(DistutilsFileError):
with open(self.source, 'w') as fobj:
fobj.write('spam eggs')
move_file(self.source, self.target, verbose=0)
@@ -120,5 +120,6 @@ class FileUtilTestCase(support.TempdirManager, unittest.TestCase):
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(FileUtilTestCase)
+
if __name__ == "__main__":
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_filelist.py b/setuptools/_distutils/tests/test_filelist.py
index a90edcf1..71718a86 100644
--- a/setuptools/_distutils/tests/test_filelist.py
+++ b/setuptools/_distutils/tests/test_filelist.py
@@ -11,7 +11,6 @@ from distutils import filelist
from test.support import captured_stdout, run_unittest
from distutils.tests import support
-from .py35compat import adapt_glob
from . import py38compat as os_helper
@@ -36,9 +35,7 @@ def make_local_path(s):
return s.replace('/', os.sep)
-class FileListTestCase(support.LoggingSilencer,
- unittest.TestCase):
-
+class FileListTestCase(support.LoggingSilencer, unittest.TestCase):
def assertNoWarnings(self):
self.assertEqual(self.get_logs(WARN), [])
self.clear_logs()
@@ -61,47 +58,53 @@ class FileListTestCase(support.LoggingSilencer,
(r'foo\\*', r'(?s:foo\\\\[^%(sep)s]*)\Z'),
(r'foo\\\*', r'(?s:foo\\\\\\[^%(sep)s]*)\Z'),
('foo????', r'(?s:foo[^%(sep)s][^%(sep)s][^%(sep)s][^%(sep)s])\Z'),
- (r'foo\\??', r'(?s:foo\\\\[^%(sep)s][^%(sep)s])\Z')):
+ (r'foo\\??', r'(?s:foo\\\\[^%(sep)s][^%(sep)s])\Z'),
+ ):
regex = regex % {'sep': sep}
- self.assertEqual(glob_to_re(glob), adapt_glob(regex))
+ self.assertEqual(glob_to_re(glob), regex)
def test_process_template_line(self):
# testing all MANIFEST.in template patterns
file_list = FileList()
- l = make_local_path
+ mlp = make_local_path
# simulated file list
- file_list.allfiles = ['foo.tmp', 'ok', 'xo', 'four.txt',
- 'buildout.cfg',
- # filelist does not filter out VCS directories,
- # it's sdist that does
- l('.hg/last-message.txt'),
- l('global/one.txt'),
- l('global/two.txt'),
- l('global/files.x'),
- l('global/here.tmp'),
- l('f/o/f.oo'),
- l('dir/graft-one'),
- l('dir/dir2/graft2'),
- l('dir3/ok'),
- l('dir3/sub/ok.txt'),
- ]
+ file_list.allfiles = [
+ 'foo.tmp',
+ 'ok',
+ 'xo',
+ 'four.txt',
+ 'buildout.cfg',
+ # filelist does not filter out VCS directories,
+ # it's sdist that does
+ mlp('.hg/last-message.txt'),
+ mlp('global/one.txt'),
+ mlp('global/two.txt'),
+ mlp('global/files.x'),
+ mlp('global/here.tmp'),
+ mlp('f/o/f.oo'),
+ mlp('dir/graft-one'),
+ mlp('dir/dir2/graft2'),
+ mlp('dir3/ok'),
+ mlp('dir3/sub/ok.txt'),
+ ]
for line in MANIFEST_IN.split('\n'):
if line.strip() == '':
continue
file_list.process_template_line(line)
- wanted = ['ok',
- 'buildout.cfg',
- 'four.txt',
- l('.hg/last-message.txt'),
- l('global/one.txt'),
- l('global/two.txt'),
- l('f/o/f.oo'),
- l('dir/graft-one'),
- l('dir/dir2/graft2'),
- ]
+ wanted = [
+ 'ok',
+ 'buildout.cfg',
+ 'four.txt',
+ mlp('.hg/last-message.txt'),
+ mlp('global/one.txt'),
+ mlp('global/two.txt'),
+ mlp('f/o/f.oo'),
+ mlp('dir/graft-one'),
+ mlp('dir/dir2/graft2'),
+ ]
self.assertEqual(file_list.files, wanted)
@@ -135,24 +138,23 @@ class FileListTestCase(support.LoggingSilencer,
def test_translate_pattern(self):
# not regex
- self.assertTrue(hasattr(
- translate_pattern('a', anchor=True, is_regex=False),
- 'search'))
+ self.assertTrue(
+ hasattr(translate_pattern('a', anchor=True, is_regex=False), 'search')
+ )
# is a regex
regex = re.compile('a')
- self.assertEqual(
- translate_pattern(regex, anchor=True, is_regex=True),
- regex)
+ self.assertEqual(translate_pattern(regex, anchor=True, is_regex=True), regex)
# plain string flagged as regex
- self.assertTrue(hasattr(
- translate_pattern('a', anchor=True, is_regex=True),
- 'search'))
+ self.assertTrue(
+ hasattr(translate_pattern('a', anchor=True, is_regex=True), 'search')
+ )
# glob support
- self.assertTrue(translate_pattern(
- '*.py', anchor=True, is_regex=False).search('filelist.py'))
+ self.assertTrue(
+ translate_pattern('*.py', anchor=True, is_regex=False).search('filelist.py')
+ )
def test_exclude_pattern(self):
# return False if no match
@@ -189,18 +191,27 @@ class FileListTestCase(support.LoggingSilencer,
self.assertEqual(file_list.allfiles, ['a.py', 'b.txt'])
def test_process_template(self):
- l = make_local_path
+ mlp = make_local_path
# invalid lines
file_list = FileList()
- for action in ('include', 'exclude', 'global-include',
- 'global-exclude', 'recursive-include',
- 'recursive-exclude', 'graft', 'prune', 'blarg'):
- self.assertRaises(DistutilsTemplateError,
- file_list.process_template_line, action)
+ for action in (
+ 'include',
+ 'exclude',
+ 'global-include',
+ 'global-exclude',
+ 'recursive-include',
+ 'recursive-exclude',
+ 'graft',
+ 'prune',
+ 'blarg',
+ ):
+ self.assertRaises(
+ DistutilsTemplateError, file_list.process_template_line, action
+ )
# include
file_list = FileList()
- file_list.set_allfiles(['a.py', 'b.txt', l('d/c.py')])
+ file_list.set_allfiles(['a.py', 'b.txt', mlp('d/c.py')])
file_list.process_template_line('include *.py')
self.assertEqual(file_list.files, ['a.py'])
@@ -212,31 +223,31 @@ class FileListTestCase(support.LoggingSilencer,
# exclude
file_list = FileList()
- file_list.files = ['a.py', 'b.txt', l('d/c.py')]
+ file_list.files = ['a.py', 'b.txt', mlp('d/c.py')]
file_list.process_template_line('exclude *.py')
- self.assertEqual(file_list.files, ['b.txt', l('d/c.py')])
+ self.assertEqual(file_list.files, ['b.txt', mlp('d/c.py')])
self.assertNoWarnings()
file_list.process_template_line('exclude *.rb')
- self.assertEqual(file_list.files, ['b.txt', l('d/c.py')])
+ self.assertEqual(file_list.files, ['b.txt', mlp('d/c.py')])
self.assertWarnings()
# global-include
file_list = FileList()
- file_list.set_allfiles(['a.py', 'b.txt', l('d/c.py')])
+ file_list.set_allfiles(['a.py', 'b.txt', mlp('d/c.py')])
file_list.process_template_line('global-include *.py')
- self.assertEqual(file_list.files, ['a.py', l('d/c.py')])
+ self.assertEqual(file_list.files, ['a.py', mlp('d/c.py')])
self.assertNoWarnings()
file_list.process_template_line('global-include *.rb')
- self.assertEqual(file_list.files, ['a.py', l('d/c.py')])
+ self.assertEqual(file_list.files, ['a.py', mlp('d/c.py')])
self.assertWarnings()
# global-exclude
file_list = FileList()
- file_list.files = ['a.py', 'b.txt', l('d/c.py')]
+ file_list.files = ['a.py', 'b.txt', mlp('d/c.py')]
file_list.process_template_line('global-exclude *.py')
self.assertEqual(file_list.files, ['b.txt'])
@@ -248,52 +259,50 @@ class FileListTestCase(support.LoggingSilencer,
# recursive-include
file_list = FileList()
- file_list.set_allfiles(['a.py', l('d/b.py'), l('d/c.txt'),
- l('d/d/e.py')])
+ file_list.set_allfiles(['a.py', mlp('d/b.py'), mlp('d/c.txt'), mlp('d/d/e.py')])
file_list.process_template_line('recursive-include d *.py')
- self.assertEqual(file_list.files, [l('d/b.py'), l('d/d/e.py')])
+ self.assertEqual(file_list.files, [mlp('d/b.py'), mlp('d/d/e.py')])
self.assertNoWarnings()
file_list.process_template_line('recursive-include e *.py')
- self.assertEqual(file_list.files, [l('d/b.py'), l('d/d/e.py')])
+ self.assertEqual(file_list.files, [mlp('d/b.py'), mlp('d/d/e.py')])
self.assertWarnings()
# recursive-exclude
file_list = FileList()
- file_list.files = ['a.py', l('d/b.py'), l('d/c.txt'), l('d/d/e.py')]
+ file_list.files = ['a.py', mlp('d/b.py'), mlp('d/c.txt'), mlp('d/d/e.py')]
file_list.process_template_line('recursive-exclude d *.py')
- self.assertEqual(file_list.files, ['a.py', l('d/c.txt')])
+ self.assertEqual(file_list.files, ['a.py', mlp('d/c.txt')])
self.assertNoWarnings()
file_list.process_template_line('recursive-exclude e *.py')
- self.assertEqual(file_list.files, ['a.py', l('d/c.txt')])
+ self.assertEqual(file_list.files, ['a.py', mlp('d/c.txt')])
self.assertWarnings()
# graft
file_list = FileList()
- file_list.set_allfiles(['a.py', l('d/b.py'), l('d/d/e.py'),
- l('f/f.py')])
+ file_list.set_allfiles(['a.py', mlp('d/b.py'), mlp('d/d/e.py'), mlp('f/f.py')])
file_list.process_template_line('graft d')
- self.assertEqual(file_list.files, [l('d/b.py'), l('d/d/e.py')])
+ self.assertEqual(file_list.files, [mlp('d/b.py'), mlp('d/d/e.py')])
self.assertNoWarnings()
file_list.process_template_line('graft e')
- self.assertEqual(file_list.files, [l('d/b.py'), l('d/d/e.py')])
+ self.assertEqual(file_list.files, [mlp('d/b.py'), mlp('d/d/e.py')])
self.assertWarnings()
# prune
file_list = FileList()
- file_list.files = ['a.py', l('d/b.py'), l('d/d/e.py'), l('f/f.py')]
+ file_list.files = ['a.py', mlp('d/b.py'), mlp('d/d/e.py'), mlp('f/f.py')]
file_list.process_template_line('prune d')
- self.assertEqual(file_list.files, ['a.py', l('f/f.py')])
+ self.assertEqual(file_list.files, ['a.py', mlp('f/f.py')])
self.assertNoWarnings()
file_list.process_template_line('prune e')
- self.assertEqual(file_list.files, ['a.py', l('f/f.py')])
+ self.assertEqual(file_list.files, ['a.py', mlp('f/f.py')])
self.assertWarnings()
@@ -343,10 +352,12 @@ class FindAllTestCase(unittest.TestCase):
def test_suite():
- return unittest.TestSuite([
- unittest.TestLoader().loadTestsFromTestCase(FileListTestCase),
- unittest.TestLoader().loadTestsFromTestCase(FindAllTestCase),
- ])
+ return unittest.TestSuite(
+ [
+ unittest.TestLoader().loadTestsFromTestCase(FileListTestCase),
+ unittest.TestLoader().loadTestsFromTestCase(FindAllTestCase),
+ ]
+ )
if __name__ == "__main__":
diff --git a/setuptools/_distutils/tests/test_install.py b/setuptools/_distutils/tests/test_install.py
index 3aef9e43..5f0a64db 100644
--- a/setuptools/_distutils/tests/test_install.py
+++ b/setuptools/_distutils/tests/test_install.py
@@ -19,16 +19,23 @@ from distutils.extension import Extension
from distutils.tests import support
from test import support as test_support
+import pytest
+
def _make_ext_name(modname):
return modname + sysconfig.get_config_var('EXT_SUFFIX')
-class InstallTestCase(support.TempdirManager,
- support.EnvironGuard,
- support.LoggingSilencer,
- unittest.TestCase):
-
+class InstallTestCase(
+ support.TempdirManager,
+ support.EnvironGuard,
+ support.LoggingSilencer,
+ unittest.TestCase,
+):
+ @pytest.mark.xfail(
+ 'platform.system() == "Windows" and sys.version_info > (3, 11)',
+ reason="pypa/distutils#148",
+ )
def test_home_installation_scheme(self):
# This ensure two things:
# - that --home generates the desired set of directory names
@@ -42,7 +49,7 @@ class InstallTestCase(support.TempdirManager,
dist.command_obj["build"] = support.DummyCommand(
build_base=builddir,
build_lib=os.path.join(builddir, "lib"),
- )
+ )
cmd = install(dist)
cmd.home = destination
@@ -63,8 +70,10 @@ class InstallTestCase(support.TempdirManager,
platlibdir = os.path.join(destination, _platlibdir, impl_name)
check_path(cmd.install_platlib, platlibdir)
check_path(cmd.install_purelib, libdir)
- check_path(cmd.install_headers,
- os.path.join(destination, "include", impl_name, "foopkg"))
+ check_path(
+ cmd.install_headers,
+ os.path.join(destination, "include", impl_name, "foopkg"),
+ )
check_path(cmd.install_scripts, os.path.join(destination, "bin"))
check_path(cmd.install_data, destination)
@@ -85,6 +94,7 @@ class InstallTestCase(support.TempdirManager,
if path.startswith('~'):
return os.path.normpath(self.tmpdir + path[1:])
return path
+
self.old_expand = os.path.expanduser
os.path.expanduser = _expanduser
@@ -104,8 +114,7 @@ class InstallTestCase(support.TempdirManager,
cmd = install(dist)
# making sure the user option is there
- options = [name for name, short, lable in
- cmd.user_options]
+ options = [name for name, short, lable in cmd.user_options]
self.assertIn('user', options)
# setting a value
@@ -128,13 +137,16 @@ class InstallTestCase(support.TempdirManager,
actual_headers = os.path.relpath(cmd.install_headers, self.user_base)
if os.name == 'nt':
site_path = os.path.relpath(
- os.path.dirname(self.old_user_site), self.old_user_base)
+ os.path.dirname(self.old_user_site), self.old_user_base
+ )
include = os.path.join(site_path, 'Include')
else:
include = sysconfig.get_python_inc(0, '')
expect_headers = os.path.join(include, 'xx')
- self.assertEqual(os.path.normcase(actual_headers), os.path.normcase(expect_headers))
+ self.assertEqual(
+ os.path.normcase(actual_headers), os.path.normcase(expect_headers)
+ )
def test_handle_extra_path(self):
dist = Distribution({'name': 'xx', 'extra_path': 'path,dirs'})
@@ -187,8 +199,7 @@ class InstallTestCase(support.TempdirManager,
def test_record(self):
install_dir = self.mkdtemp()
- project_dir, dist = self.create_dist(py_modules=['hello'],
- scripts=['sayhi'])
+ project_dir, dist = self.create_dist(py_modules=['hello'], scripts=['sayhi'])
os.chdir(project_dir)
self.write_file('hello.py', "def main(): print('o hai')")
self.write_file('sayhi', 'from hello import main; main()')
@@ -207,9 +218,12 @@ class InstallTestCase(support.TempdirManager,
f.close()
found = [os.path.basename(line) for line in content.splitlines()]
- expected = ['hello.py', 'hello.%s.pyc' % sys.implementation.cache_tag,
- 'sayhi',
- 'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2]]
+ expected = [
+ 'hello.py',
+ 'hello.%s.pyc' % sys.implementation.cache_tag,
+ 'sayhi',
+ 'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2],
+ ]
self.assertEqual(found, expected)
def test_record_extensions(self):
@@ -217,8 +231,9 @@ class InstallTestCase(support.TempdirManager,
if cmd is not None:
self.skipTest('The %r command is not found' % cmd)
install_dir = self.mkdtemp()
- project_dir, dist = self.create_dist(ext_modules=[
- Extension('xx', ['xxmodule.c'])])
+ project_dir, dist = self.create_dist(
+ ext_modules=[Extension('xx', ['xxmodule.c'])]
+ )
os.chdir(project_dir)
support.copy_xxmodule_c(project_dir)
@@ -241,8 +256,10 @@ class InstallTestCase(support.TempdirManager,
f.close()
found = [os.path.basename(line) for line in content.splitlines()]
- expected = [_make_ext_name('xx'),
- 'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2]]
+ expected = [
+ _make_ext_name('xx'),
+ 'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2],
+ ]
self.assertEqual(found, expected)
def test_debug_mode(self):
@@ -260,5 +277,6 @@ class InstallTestCase(support.TempdirManager,
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(InstallTestCase)
+
if __name__ == "__main__":
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_install_data.py b/setuptools/_distutils/tests/test_install_data.py
index 6191d2fa..a08168b2 100644
--- a/setuptools/_distutils/tests/test_install_data.py
+++ b/setuptools/_distutils/tests/test_install_data.py
@@ -6,11 +6,13 @@ from distutils.command.install_data import install_data
from distutils.tests import support
from test.support import run_unittest
-class InstallDataTestCase(support.TempdirManager,
- support.LoggingSilencer,
- support.EnvironGuard,
- unittest.TestCase):
+class InstallDataTestCase(
+ support.TempdirManager,
+ support.LoggingSilencer,
+ support.EnvironGuard,
+ unittest.TestCase,
+):
def test_simple_run(self):
pkg_dir, dist = self.create_dist()
cmd = install_data(dist)
@@ -57,9 +59,7 @@ class InstallDataTestCase(support.TempdirManager,
inst4 = os.path.join(pkg_dir, 'inst4')
three = os.path.join(cmd.install_dir, 'three')
self.write_file(three, 'xx')
- cmd.data_files = [one, (inst2, [two]),
- ('inst3', [three]),
- (inst4, [])]
+ cmd.data_files = [one, (inst2, [two]), ('inst3', [three]), (inst4, [])]
cmd.ensure_finalized()
cmd.run()
@@ -68,8 +68,10 @@ class InstallDataTestCase(support.TempdirManager,
self.assertTrue(os.path.exists(os.path.join(inst2, rtwo)))
self.assertTrue(os.path.exists(os.path.join(inst, rone)))
+
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(InstallDataTestCase)
+
if __name__ == "__main__":
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_install_headers.py b/setuptools/_distutils/tests/test_install_headers.py
index 1aa4d09c..db4f4dbb 100644
--- a/setuptools/_distutils/tests/test_install_headers.py
+++ b/setuptools/_distutils/tests/test_install_headers.py
@@ -6,11 +6,13 @@ from distutils.command.install_headers import install_headers
from distutils.tests import support
from test.support import run_unittest
-class InstallHeadersTestCase(support.TempdirManager,
- support.LoggingSilencer,
- support.EnvironGuard,
- unittest.TestCase):
+class InstallHeadersTestCase(
+ support.TempdirManager,
+ support.LoggingSilencer,
+ support.EnvironGuard,
+ unittest.TestCase,
+):
def test_simple_run(self):
# we have two headers
header_list = self.mkdtemp()
@@ -32,8 +34,10 @@ class InstallHeadersTestCase(support.TempdirManager,
# let's check the results
self.assertEqual(len(cmd.get_outputs()), 2)
+
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(InstallHeadersTestCase)
+
if __name__ == "__main__":
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_install_lib.py b/setuptools/_distutils/tests/test_install_lib.py
index 652653f2..1ef233a7 100644
--- a/setuptools/_distutils/tests/test_install_lib.py
+++ b/setuptools/_distutils/tests/test_install_lib.py
@@ -11,11 +11,12 @@ from distutils.errors import DistutilsOptionError
from test.support import run_unittest
-class InstallLibTestCase(support.TempdirManager,
- support.LoggingSilencer,
- support.EnvironGuard,
- unittest.TestCase):
-
+class InstallLibTestCase(
+ support.TempdirManager,
+ support.LoggingSilencer,
+ support.EnvironGuard,
+ unittest.TestCase,
+):
def test_finalize_options(self):
dist = self.create_dist()[1]
cmd = install_lib(dist)
@@ -45,8 +46,9 @@ class InstallLibTestCase(support.TempdirManager,
self.write_file(f, '# python file')
cmd.byte_compile([f])
pyc_file = importlib.util.cache_from_source('foo.py', optimization='')
- pyc_opt_file = importlib.util.cache_from_source('foo.py',
- optimization=cmd.optimize)
+ pyc_opt_file = importlib.util.cache_from_source(
+ 'foo.py', optimization=cmd.optimize
+ )
self.assertTrue(os.path.exists(pyc_file))
self.assertTrue(os.path.exists(pyc_opt_file))
@@ -104,12 +106,12 @@ class InstallLibTestCase(support.TempdirManager,
finally:
sys.dont_write_bytecode = old_dont_write_bytecode
- self.assertIn('byte-compiling is disabled',
- self.logs[0][1] % self.logs[0][2])
+ self.assertIn('byte-compiling is disabled', self.logs[0][1] % self.logs[0][2])
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(InstallLibTestCase)
+
if __name__ == "__main__":
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_install_scripts.py b/setuptools/_distutils/tests/test_install_scripts.py
index 648db3b1..bac78801 100644
--- a/setuptools/_distutils/tests/test_install_scripts.py
+++ b/setuptools/_distutils/tests/test_install_scripts.py
@@ -10,19 +10,17 @@ from distutils.tests import support
from test.support import run_unittest
-class InstallScriptsTestCase(support.TempdirManager,
- support.LoggingSilencer,
- unittest.TestCase):
-
+class InstallScriptsTestCase(
+ support.TempdirManager, support.LoggingSilencer, unittest.TestCase
+):
def test_default_settings(self):
dist = Distribution()
- dist.command_obj["build"] = support.DummyCommand(
- build_scripts="/foo/bar")
+ dist.command_obj["build"] = support.DummyCommand(build_scripts="/foo/bar")
dist.command_obj["install"] = support.DummyCommand(
install_scripts="/splat/funk",
force=1,
skip_build=1,
- )
+ )
cmd = install_scripts(dist)
self.assertFalse(cmd.force)
self.assertFalse(cmd.skip_build)
@@ -48,15 +46,21 @@ class InstallScriptsTestCase(support.TempdirManager,
finally:
f.close()
- write_script("script1.py", ("#! /usr/bin/env python2.3\n"
- "# bogus script w/ Python sh-bang\n"
- "pass\n"))
- write_script("script2.py", ("#!/usr/bin/python\n"
- "# bogus script w/ Python sh-bang\n"
- "pass\n"))
- write_script("shell.sh", ("#!/bin/sh\n"
- "# bogus shell script w/ sh-bang\n"
- "exit 0\n"))
+ write_script(
+ "script1.py",
+ (
+ "#! /usr/bin/env python2.3\n"
+ "# bogus script w/ Python sh-bang\n"
+ "pass\n"
+ ),
+ )
+ write_script(
+ "script2.py",
+ ("#!/usr/bin/python\n" "# bogus script w/ Python sh-bang\n" "pass\n"),
+ )
+ write_script(
+ "shell.sh", ("#!/bin/sh\n" "# bogus shell script w/ sh-bang\n" "exit 0\n")
+ )
target = self.mkdtemp()
dist = Distribution()
@@ -65,7 +69,7 @@ class InstallScriptsTestCase(support.TempdirManager,
install_scripts=target,
force=1,
skip_build=1,
- )
+ )
cmd = install_scripts(dist)
cmd.finalize_options()
cmd.run()
@@ -78,5 +82,6 @@ class InstallScriptsTestCase(support.TempdirManager,
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(InstallScriptsTestCase)
+
if __name__ == "__main__":
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_log.py b/setuptools/_distutils/tests/test_log.py
index ec2ae028..33f7f96c 100644
--- a/setuptools/_distutils/tests/test_log.py
+++ b/setuptools/_distutils/tests/test_log.py
@@ -7,40 +7,55 @@ from test.support import swap_attr, run_unittest
from distutils import log
+
class TestLog(unittest.TestCase):
def test_non_ascii(self):
# Issues #8663, #34421: test that non-encodable text is escaped with
# backslashreplace error handler and encodable non-ASCII text is
# output as is.
- for errors in ('strict', 'backslashreplace', 'surrogateescape',
- 'replace', 'ignore'):
+ for errors in (
+ 'strict',
+ 'backslashreplace',
+ 'surrogateescape',
+ 'replace',
+ 'ignore',
+ ):
with self.subTest(errors=errors):
- stdout = io.TextIOWrapper(io.BytesIO(),
- encoding='cp437', errors=errors)
- stderr = io.TextIOWrapper(io.BytesIO(),
- encoding='cp437', errors=errors)
+ stdout = io.TextIOWrapper(io.BytesIO(), encoding='cp437', errors=errors)
+ stderr = io.TextIOWrapper(io.BytesIO(), encoding='cp437', errors=errors)
old_threshold = log.set_threshold(log.DEBUG)
try:
- with swap_attr(sys, 'stdout', stdout), \
- swap_attr(sys, 'stderr', stderr):
+ with swap_attr(sys, 'stdout', stdout), swap_attr(
+ sys, 'stderr', stderr
+ ):
log.debug('Dεbug\tMėssãge')
log.fatal('Fαtal\tÈrrōr')
finally:
log.set_threshold(old_threshold)
stdout.seek(0)
- self.assertEqual(stdout.read().rstrip(),
- 'Dεbug\tM?ss?ge' if errors == 'replace' else
- 'Dεbug\tMssge' if errors == 'ignore' else
- 'Dεbug\tM\\u0117ss\\xe3ge')
+ self.assertEqual(
+ stdout.read().rstrip(),
+ 'Dεbug\tM?ss?ge'
+ if errors == 'replace'
+ else 'Dεbug\tMssge'
+ if errors == 'ignore'
+ else 'Dεbug\tM\\u0117ss\\xe3ge',
+ )
stderr.seek(0)
- self.assertEqual(stderr.read().rstrip(),
- 'Fαtal\t?rr?r' if errors == 'replace' else
- 'Fαtal\trrr' if errors == 'ignore' else
- 'Fαtal\t\\xc8rr\\u014dr')
+ self.assertEqual(
+ stderr.read().rstrip(),
+ 'Fαtal\t?rr?r'
+ if errors == 'replace'
+ else 'Fαtal\trrr'
+ if errors == 'ignore'
+ else 'Fαtal\t\\xc8rr\\u014dr',
+ )
+
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(TestLog)
+
if __name__ == "__main__":
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_msvc9compiler.py b/setuptools/_distutils/tests/test_msvc9compiler.py
index 6235405e..ec4781af 100644
--- a/setuptools/_distutils/tests/test_msvc9compiler.py
+++ b/setuptools/_distutils/tests/test_msvc9compiler.py
@@ -90,38 +90,42 @@ _CLEANED_MANIFEST = """\
</dependency>
</assembly>"""
-if sys.platform=="win32":
+if sys.platform == "win32":
from distutils.msvccompiler import get_build_version
- if get_build_version()>=8.0:
+
+ if get_build_version() >= 8.0:
SKIP_MESSAGE = None
else:
SKIP_MESSAGE = "These tests are only for MSVC8.0 or above"
else:
SKIP_MESSAGE = "These tests are only for win32"
-@unittest.skipUnless(SKIP_MESSAGE is None, SKIP_MESSAGE)
-class msvc9compilerTestCase(support.TempdirManager,
- unittest.TestCase):
+@unittest.skipUnless(SKIP_MESSAGE is None, SKIP_MESSAGE)
+class msvc9compilerTestCase(support.TempdirManager, unittest.TestCase):
def test_no_compiler(self):
# makes sure query_vcvarsall raises
# a DistutilsPlatformError if the compiler
# is not found
from distutils.msvc9compiler import query_vcvarsall
+
def _find_vcvarsall(version):
return None
from distutils import msvc9compiler
+
old_find_vcvarsall = msvc9compiler.find_vcvarsall
msvc9compiler.find_vcvarsall = _find_vcvarsall
try:
- self.assertRaises(DistutilsPlatformError, query_vcvarsall,
- 'wont find this version')
+ self.assertRaises(
+ DistutilsPlatformError, query_vcvarsall, 'wont find this version'
+ )
finally:
msvc9compiler.find_vcvarsall = old_find_vcvarsall
def test_reg_class(self):
from distutils.msvc9compiler import Reg
+
self.assertRaises(KeyError, Reg.get_value, 'xxx', 'xxx')
# looking for values that should exist on all
@@ -131,6 +135,7 @@ class msvc9compilerTestCase(support.TempdirManager,
self.assertIn(v, ('0', '1', '2'))
import winreg
+
HKCU = winreg.HKEY_CURRENT_USER
keys = Reg.read_keys(HKCU, 'xxxx')
self.assertEqual(keys, None)
@@ -140,6 +145,7 @@ class msvc9compilerTestCase(support.TempdirManager,
def test_remove_visual_c_ref(self):
from distutils.msvc9compiler import MSVCCompiler
+
tempdir = self.mkdtemp()
manifest = os.path.join(tempdir, 'manifest')
f = open(manifest, 'w')
@@ -164,6 +170,7 @@ class msvc9compilerTestCase(support.TempdirManager,
def test_remove_entire_manifest(self):
from distutils.msvc9compiler import MSVCCompiler
+
tempdir = self.mkdtemp()
manifest = os.path.join(tempdir, 'manifest')
f = open(manifest, 'w')
@@ -180,5 +187,6 @@ class msvc9compilerTestCase(support.TempdirManager,
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(msvc9compilerTestCase)
+
if __name__ == "__main__":
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_msvccompiler.py b/setuptools/_distutils/tests/test_msvccompiler.py
index 846e5bb8..21fe57f8 100644
--- a/setuptools/_distutils/tests/test_msvccompiler.py
+++ b/setuptools/_distutils/tests/test_msvccompiler.py
@@ -9,15 +9,14 @@ from distutils.tests import support
from test.support import run_unittest
-SKIP_MESSAGE = (None if sys.platform == "win32" else
- "These tests are only for win32")
+SKIP_MESSAGE = None if sys.platform == "win32" else "These tests are only for win32"
-@unittest.skipUnless(SKIP_MESSAGE is None, SKIP_MESSAGE)
-class msvccompilerTestCase(support.TempdirManager,
- unittest.TestCase):
+@unittest.skipUnless(SKIP_MESSAGE is None, SKIP_MESSAGE)
+class msvccompilerTestCase(support.TempdirManager, unittest.TestCase):
def test_no_compiler(self):
import distutils._msvccompiler as _msvccompiler
+
# makes sure query_vcvarsall raises
# a DistutilsPlatformError if the compiler
# is not found
@@ -27,9 +26,11 @@ class msvccompilerTestCase(support.TempdirManager,
old_find_vcvarsall = _msvccompiler._find_vcvarsall
_msvccompiler._find_vcvarsall = _find_vcvarsall
try:
- self.assertRaises(DistutilsPlatformError,
- _msvccompiler._get_vc_env,
- 'wont find this version')
+ self.assertRaises(
+ DistutilsPlatformError,
+ _msvccompiler._get_vc_env,
+ 'wont find this version',
+ )
finally:
_msvccompiler._find_vcvarsall = old_find_vcvarsall
@@ -95,14 +96,14 @@ class TestSpawn(unittest.TestCase):
Concurrent calls to spawn should have consistent results.
"""
import distutils._msvccompiler as _msvccompiler
+
compiler = _msvccompiler.MSVCCompiler()
compiler._paths = "expected"
inner_cmd = 'import os; assert os.environ["PATH"] == "expected"'
command = [sys.executable, '-c', inner_cmd]
threads = [
- CheckThread(target=compiler.spawn, args=[command])
- for n in range(100)
+ CheckThread(target=compiler.spawn, args=[command]) for n in range(100)
]
for thread in threads:
thread.start()
@@ -117,6 +118,7 @@ class TestSpawn(unittest.TestCase):
"""
import distutils._msvccompiler as _msvccompiler
from distutils import ccompiler
+
compiler = _msvccompiler.MSVCCompiler()
compiler._paths = "expected"
@@ -124,8 +126,7 @@ class TestSpawn(unittest.TestCase):
"A spawn without an env argument."
assert os.environ["PATH"] == "expected"
- with unittest.mock.patch.object(
- ccompiler.CCompiler, 'spawn', CCompiler_spawn):
+ with unittest.mock.patch.object(ccompiler.CCompiler, 'spawn', CCompiler_spawn):
compiler.spawn(["n/a"])
assert os.environ.get("PATH") != "expected"
@@ -134,5 +135,6 @@ class TestSpawn(unittest.TestCase):
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(msvccompilerTestCase)
+
if __name__ == "__main__":
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_register.py b/setuptools/_distutils/tests/test_register.py
index 5770ed58..0f91ad36 100644
--- a/setuptools/_distutils/tests/test_register.py
+++ b/setuptools/_distutils/tests/test_register.py
@@ -41,8 +41,10 @@ username:tarek
password:password
"""
+
class Inputs(object):
"""Fakes user inputs."""
+
def __init__(self, *answers):
self.answers = answers
self.index = 0
@@ -53,8 +55,10 @@ class Inputs(object):
finally:
self.index += 1
+
class FakeOpener(object):
"""Fakes a PyPI server"""
+
def __init__(self):
self.reqs = []
@@ -71,17 +75,18 @@ class FakeOpener(object):
def getheader(self, name, default=None):
return {
'content-type': 'text/plain; charset=utf-8',
- }.get(name.lower(), default)
+ }.get(name.lower(), default)
class RegisterTestCase(BasePyPIRCCommandTestCase):
-
def setUp(self):
super(RegisterTestCase, self).setUp()
# patching the password prompt
self._old_getpass = getpass.getpass
+
def _getpass(prompt):
return 'password'
+
getpass.getpass = _getpass
urllib.request._opener = None
self.old_opener = urllib.request.build_opener
@@ -95,9 +100,13 @@ class RegisterTestCase(BasePyPIRCCommandTestCase):
def _get_cmd(self, metadata=None):
if metadata is None:
- metadata = {'url': 'xxx', 'author': 'xxx',
- 'author_email': 'xxx',
- 'name': 'xxx', 'version': 'xxx'}
+ metadata = {
+ 'url': 'xxx',
+ 'author': 'xxx',
+ 'author_email': 'xxx',
+ 'name': 'xxx',
+ 'version': 'xxx',
+ }
pkg_info, dist = self.create_dist(**metadata)
return register(dist)
@@ -143,6 +152,7 @@ class RegisterTestCase(BasePyPIRCCommandTestCase):
# if we run the command again
def _no_way(prompt=''):
raise AssertionError(prompt)
+
register_module.input = _no_way
cmd.show_response = 1
@@ -154,8 +164,8 @@ class RegisterTestCase(BasePyPIRCCommandTestCase):
req1 = dict(self.conn.reqs[0].headers)
req2 = dict(self.conn.reqs[1].headers)
- self.assertEqual(req1['Content-length'], '1374')
- self.assertEqual(req2['Content-length'], '1374')
+ self.assertEqual(req1['Content-length'], '1359')
+ self.assertEqual(req2['Content-length'], '1359')
self.assertIn(b'xxx', self.conn.reqs[1].data)
def test_password_not_in_file(self):
@@ -220,10 +230,14 @@ class RegisterTestCase(BasePyPIRCCommandTestCase):
self.assertRaises(DistutilsSetupError, cmd.run)
# metadata are OK but long_description is broken
- metadata = {'url': 'xxx', 'author': 'xxx',
- 'author_email': 'éxéxé',
- 'name': 'xxx', 'version': 'xxx',
- 'long_description': 'title\n==\n\ntext'}
+ metadata = {
+ 'url': 'xxx',
+ 'author': 'xxx',
+ 'author_email': 'éxéxé',
+ 'name': 'xxx',
+ 'version': 'xxx',
+ 'long_description': 'title\n==\n\ntext',
+ }
cmd = self._get_cmd(metadata)
cmd.ensure_finalized()
@@ -255,11 +269,15 @@ class RegisterTestCase(BasePyPIRCCommandTestCase):
del register_module.input
# and finally a Unicode test (bug #12114)
- metadata = {'url': 'xxx', 'author': '\u00c9ric',
- 'author_email': 'xxx', 'name': 'xxx',
- 'version': 'xxx',
- 'description': 'Something about esszet \u00df',
- 'long_description': 'More things about esszet \u00df'}
+ metadata = {
+ 'url': 'xxx',
+ 'author': '\u00c9ric',
+ 'author_email': 'xxx',
+ 'name': 'xxx',
+ 'version': 'xxx',
+ 'description': 'Something about esszet \u00df',
+ 'long_description': 'More things about esszet \u00df',
+ }
cmd = self._get_cmd(metadata)
cmd.ensure_finalized()
@@ -275,10 +293,14 @@ class RegisterTestCase(BasePyPIRCCommandTestCase):
@unittest.skipUnless(docutils is not None, 'needs docutils')
def test_register_invalid_long_description(self):
description = ':funkie:`str`' # mimic Sphinx-specific markup
- metadata = {'url': 'xxx', 'author': 'xxx',
- 'author_email': 'xxx',
- 'name': 'xxx', 'version': 'xxx',
- 'long_description': description}
+ metadata = {
+ 'url': 'xxx',
+ 'author': 'xxx',
+ 'author_email': 'xxx',
+ 'name': 'xxx',
+ 'version': 'xxx',
+ 'long_description': description,
+ }
cmd = self._get_cmd(metadata)
cmd.ensure_finalized()
cmd.strict = True
@@ -321,5 +343,6 @@ class RegisterTestCase(BasePyPIRCCommandTestCase):
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(RegisterTestCase)
+
if __name__ == "__main__":
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_sdist.py b/setuptools/_distutils/tests/test_sdist.py
index 4c51717c..3a6aea23 100644
--- a/setuptools/_distutils/tests/test_sdist.py
+++ b/setuptools/_distutils/tests/test_sdist.py
@@ -13,6 +13,7 @@ from .py38compat import check_warnings
try:
import zlib
+
ZLIB_SUPPORT = True
except ImportError:
ZLIB_SUPPORT = False
@@ -48,8 +49,8 @@ somecode%(sep)sdoc.dat
somecode%(sep)sdoc.txt
"""
-class SDistTestCase(BasePyPIRCCommandTestCase):
+class SDistTestCase(BasePyPIRCCommandTestCase):
def setUp(self):
# PyPIRCCommandTestCase creates a temp dir already
# and put it in self.tmp_dir
@@ -72,9 +73,13 @@ class SDistTestCase(BasePyPIRCCommandTestCase):
def get_cmd(self, metadata=None):
"""Returns a cmd"""
if metadata is None:
- metadata = {'name': 'fake', 'version': '1.0',
- 'url': 'xxx', 'author': 'xxx',
- 'author_email': 'xxx'}
+ metadata = {
+ 'name': 'fake',
+ 'version': '1.0',
+ 'url': 'xxx',
+ 'author': 'xxx',
+ 'author_email': 'xxx',
+ }
dist = Distribution(metadata)
dist.script_name = 'setup.py'
dist.packages = ['somecode']
@@ -93,12 +98,10 @@ class SDistTestCase(BasePyPIRCCommandTestCase):
self.write_file((self.tmp_dir, 'somecode', '.svn', 'ok.py'), 'xxx')
os.mkdir(join(self.tmp_dir, 'somecode', '.hg'))
- self.write_file((self.tmp_dir, 'somecode', '.hg',
- 'ok'), 'xxx')
+ self.write_file((self.tmp_dir, 'somecode', '.hg', 'ok'), 'xxx')
os.mkdir(join(self.tmp_dir, 'somecode', '.git'))
- self.write_file((self.tmp_dir, 'somecode', '.git',
- 'ok'), 'xxx')
+ self.write_file((self.tmp_dir, 'somecode', '.git', 'ok'), 'xxx')
self.write_file((self.tmp_dir, 'somecode', '.nfs0001'), 'xxx')
@@ -124,15 +127,19 @@ class SDistTestCase(BasePyPIRCCommandTestCase):
zip_file.close()
# making sure everything has been pruned correctly
- expected = ['', 'PKG-INFO', 'README', 'setup.py',
- 'somecode/', 'somecode/__init__.py']
+ expected = [
+ '',
+ 'PKG-INFO',
+ 'README',
+ 'setup.py',
+ 'somecode/',
+ 'somecode/__init__.py',
+ ]
self.assertEqual(sorted(content), ['fake-1.0/' + x for x in expected])
@unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run')
- @unittest.skipIf(find_executable('tar') is None,
- "The tar command is not found")
- @unittest.skipIf(find_executable('gzip') is None,
- "The gzip command is not found")
+ @unittest.skipIf(find_executable('tar') is None, "The tar command is not found")
+ @unittest.skipIf(find_executable('gzip') is None, "The gzip command is not found")
def test_make_distribution(self):
# now building a sdist
dist, cmd = self.get_cmd()
@@ -172,8 +179,7 @@ class SDistTestCase(BasePyPIRCCommandTestCase):
# filling data_files by pointing files
# in package_data
- dist.package_data = {'': ['*.cfg', '*.dat'],
- 'somecode': ['*.txt']}
+ dist.package_data = {'': ['*.cfg', '*.dat'], 'somecode': ['*.txt']}
self.write_file((self.tmp_dir, 'somecode', 'doc.txt'), '#')
self.write_file((self.tmp_dir, 'somecode', 'doc.dat'), '#')
@@ -193,12 +199,11 @@ class SDistTestCase(BasePyPIRCCommandTestCase):
self.write_file((some_dir, 'file.txt'), '#')
self.write_file((some_dir, 'other_file.txt'), '#')
- dist.data_files = [('data', ['data/data.dt',
- 'buildout.cfg',
- 'inroot.txt',
- 'notexisting']),
- 'some/file.txt',
- 'some/other_file.txt']
+ dist.data_files = [
+ ('data', ['data/data.dt', 'buildout.cfg', 'inroot.txt', 'notexisting']),
+ 'some/file.txt',
+ 'some/other_file.txt',
+ ]
# adding a script
script_dir = join(self.tmp_dir, 'scripts')
@@ -224,12 +229,25 @@ class SDistTestCase(BasePyPIRCCommandTestCase):
zip_file.close()
# making sure everything was added
- expected = ['', 'PKG-INFO', 'README', 'buildout.cfg',
- 'data/', 'data/data.dt', 'inroot.txt',
- 'scripts/', 'scripts/script.py', 'setup.py',
- 'some/', 'some/file.txt', 'some/other_file.txt',
- 'somecode/', 'somecode/__init__.py', 'somecode/doc.dat',
- 'somecode/doc.txt']
+ expected = [
+ '',
+ 'PKG-INFO',
+ 'README',
+ 'buildout.cfg',
+ 'data/',
+ 'data/data.dt',
+ 'inroot.txt',
+ 'scripts/',
+ 'scripts/script.py',
+ 'setup.py',
+ 'some/',
+ 'some/file.txt',
+ 'some/other_file.txt',
+ 'somecode/',
+ 'somecode/__init__.py',
+ 'somecode/doc.dat',
+ 'somecode/doc.txt',
+ ]
self.assertEqual(sorted(content), ['fake-1.0/' + x for x in expected])
# checking the MANIFEST
@@ -249,9 +267,10 @@ class SDistTestCase(BasePyPIRCCommandTestCase):
# with the `check` subcommand
cmd.ensure_finalized()
cmd.run()
- warnings = [msg for msg in self.get_logs(WARN) if
- msg.startswith('warning: check:')]
- self.assertEqual(len(warnings), 2)
+ warnings = [
+ msg for msg in self.get_logs(WARN) if msg.startswith('warning: check:')
+ ]
+ self.assertEqual(len(warnings), 1)
# trying with a complete set of metadata
self.clear_logs()
@@ -259,8 +278,9 @@ class SDistTestCase(BasePyPIRCCommandTestCase):
cmd.ensure_finalized()
cmd.metadata_check = 0
cmd.run()
- warnings = [msg for msg in self.get_logs(WARN) if
- msg.startswith('warning: check:')]
+ warnings = [
+ msg for msg in self.get_logs(WARN) if msg.startswith('warning: check:')
+ ]
self.assertEqual(len(warnings), 0)
def test_check_metadata_deprecated(self):
@@ -277,8 +297,11 @@ class SDistTestCase(BasePyPIRCCommandTestCase):
# the output should be a header line + one line per format
num_formats = len(ARCHIVE_FORMATS.keys())
- output = [line for line in stdout.getvalue().split('\n')
- if line.strip().startswith('--formats=')]
+ output = [
+ line
+ for line in stdout.getvalue().split('\n')
+ if line.strip().startswith('--formats=')
+ ]
self.assertEqual(len(output), num_formats)
def test_finalize_options(self):
@@ -341,8 +364,9 @@ class SDistTestCase(BasePyPIRCCommandTestCase):
f = open(cmd.manifest)
try:
- manifest = [line.strip() for line in f.read().split('\n')
- if line.strip() != '']
+ manifest = [
+ line.strip() for line in f.read().split('\n') if line.strip() != ''
+ ]
finally:
f.close()
@@ -360,8 +384,9 @@ class SDistTestCase(BasePyPIRCCommandTestCase):
f = open(cmd.manifest)
try:
- manifest2 = [line.strip() for line in f.read().split('\n')
- if line.strip() != '']
+ manifest2 = [
+ line.strip() for line in f.read().split('\n') if line.strip() != ''
+ ]
finally:
f.close()
@@ -378,22 +403,24 @@ class SDistTestCase(BasePyPIRCCommandTestCase):
f = open(cmd.manifest)
try:
- manifest = [line.strip() for line in f.read().split('\n')
- if line.strip() != '']
+ manifest = [
+ line.strip() for line in f.read().split('\n') if line.strip() != ''
+ ]
finally:
f.close()
- self.assertEqual(manifest[0],
- '# file GENERATED by distutils, do NOT edit')
+ self.assertEqual(manifest[0], '# file GENERATED by distutils, do NOT edit')
@unittest.skipUnless(ZLIB_SUPPORT, "Need zlib support to run")
def test_manifest_comments(self):
# make sure comments don't cause exceptions or wrong includes
- contents = dedent("""\
+ contents = dedent(
+ """\
# bad.py
#bad.py
good.py
- """)
+ """
+ )
dist, cmd = self.get_cmd()
cmd.ensure_finalized()
self.write_file((self.tmp_dir, cmd.manifest), contents)
@@ -410,15 +437,18 @@ class SDistTestCase(BasePyPIRCCommandTestCase):
cmd.formats = ['gztar']
cmd.ensure_finalized()
self.write_file((self.tmp_dir, cmd.manifest), 'README.manual')
- self.write_file((self.tmp_dir, 'README.manual'),
- 'This project maintains its MANIFEST file itself.')
+ self.write_file(
+ (self.tmp_dir, 'README.manual'),
+ 'This project maintains its MANIFEST file itself.',
+ )
cmd.run()
self.assertEqual(cmd.filelist.files, ['README.manual'])
f = open(cmd.manifest)
try:
- manifest = [line.strip() for line in f.read().split('\n')
- if line.strip() != '']
+ manifest = [
+ line.strip() for line in f.read().split('\n') if line.strip() != ''
+ ]
finally:
f.close()
@@ -430,16 +460,16 @@ class SDistTestCase(BasePyPIRCCommandTestCase):
filenames = [tarinfo.name for tarinfo in archive]
finally:
archive.close()
- self.assertEqual(sorted(filenames), ['fake-1.0', 'fake-1.0/PKG-INFO',
- 'fake-1.0/README.manual'])
+ self.assertEqual(
+ sorted(filenames),
+ ['fake-1.0', 'fake-1.0/PKG-INFO', 'fake-1.0/README.manual'],
+ )
@unittest.skipUnless(ZLIB_SUPPORT, "requires zlib")
@require_unix_id
@require_uid_0
- @unittest.skipIf(find_executable('tar') is None,
- "The tar command is not found")
- @unittest.skipIf(find_executable('gzip') is None,
- "The gzip command is not found")
+ @unittest.skipIf(find_executable('tar') is None, "The tar command is not found")
+ @unittest.skipIf(find_executable('gzip') is None, "The gzip command is not found")
def test_make_distribution_owner_group(self):
# now building a sdist
dist, cmd = self.get_cmd()
@@ -482,8 +512,10 @@ class SDistTestCase(BasePyPIRCCommandTestCase):
finally:
archive.close()
+
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(SDistTestCase)
+
if __name__ == "__main__":
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_spawn.py b/setuptools/_distutils/tests/test_spawn.py
index c5ed8e2b..a7732562 100644
--- a/setuptools/_distutils/tests/test_spawn.py
+++ b/setuptools/_distutils/tests/test_spawn.py
@@ -3,9 +3,8 @@ import os
import stat
import sys
import unittest.mock
-from test.support import run_unittest
+from test.support import run_unittest, unix_shell
-from .py35compat import unix_shell
from . import py38compat as os_helper
from distutils.spawn import find_executable
@@ -13,12 +12,9 @@ from distutils.spawn import spawn
from distutils.errors import DistutilsExecError
from distutils.tests import support
-class SpawnTestCase(support.TempdirManager,
- support.LoggingSilencer,
- unittest.TestCase):
- @unittest.skipUnless(os.name in ('nt', 'posix'),
- 'Runs only under posix or nt')
+class SpawnTestCase(support.TempdirManager, support.LoggingSilencer, unittest.TestCase):
+ @unittest.skipUnless(os.name in ('nt', 'posix'), 'Runs only under posix or nt')
def test_spawn(self):
tmpdir = self.mkdtemp()
@@ -74,16 +70,15 @@ class SpawnTestCase(support.TempdirManager,
# test non-existent program
dont_exist_program = "dontexist_" + program
- rv = find_executable(dont_exist_program , path=tmp_dir)
+ rv = find_executable(dont_exist_program, path=tmp_dir)
self.assertIsNone(rv)
# PATH='': no match, except in the current directory
with os_helper.EnvironmentVarGuard() as env:
env['PATH'] = ''
- with unittest.mock.patch('distutils.spawn.os.confstr',
- return_value=tmp_dir, create=True), \
- unittest.mock.patch('distutils.spawn.os.defpath',
- tmp_dir):
+ with unittest.mock.patch(
+ 'distutils.spawn.os.confstr', return_value=tmp_dir, create=True
+ ), unittest.mock.patch('distutils.spawn.os.defpath', tmp_dir):
rv = find_executable(program)
self.assertIsNone(rv)
@@ -95,9 +90,9 @@ class SpawnTestCase(support.TempdirManager,
# PATH=':': explicitly looks in the current directory
with os_helper.EnvironmentVarGuard() as env:
env['PATH'] = os.pathsep
- with unittest.mock.patch('distutils.spawn.os.confstr',
- return_value='', create=True), \
- unittest.mock.patch('distutils.spawn.os.defpath', ''):
+ with unittest.mock.patch(
+ 'distutils.spawn.os.confstr', return_value='', create=True
+ ), unittest.mock.patch('distutils.spawn.os.defpath', ''):
rv = find_executable(program)
self.assertIsNone(rv)
@@ -111,18 +106,16 @@ class SpawnTestCase(support.TempdirManager,
env.pop('PATH', None)
# without confstr
- with unittest.mock.patch('distutils.spawn.os.confstr',
- side_effect=ValueError,
- create=True), \
- unittest.mock.patch('distutils.spawn.os.defpath',
- tmp_dir):
+ with unittest.mock.patch(
+ 'distutils.spawn.os.confstr', side_effect=ValueError, create=True
+ ), unittest.mock.patch('distutils.spawn.os.defpath', tmp_dir):
rv = find_executable(program)
self.assertEqual(rv, filename)
# with confstr
- with unittest.mock.patch('distutils.spawn.os.confstr',
- return_value=tmp_dir, create=True), \
- unittest.mock.patch('distutils.spawn.os.defpath', ''):
+ with unittest.mock.patch(
+ 'distutils.spawn.os.confstr', return_value=tmp_dir, create=True
+ ), unittest.mock.patch('distutils.spawn.os.defpath', ''):
rv = find_executable(program)
self.assertEqual(rv, filename)
@@ -135,5 +128,6 @@ class SpawnTestCase(support.TempdirManager,
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(SpawnTestCase)
+
if __name__ == "__main__":
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_sysconfig.py b/setuptools/_distutils/tests/test_sysconfig.py
index e671f9e0..a033e075 100644
--- a/setuptools/_distutils/tests/test_sysconfig.py
+++ b/setuptools/_distutils/tests/test_sysconfig.py
@@ -7,6 +7,9 @@ import sys
import textwrap
import unittest
+import jaraco.envs
+
+import distutils
from distutils import sysconfig
from distutils.ccompiler import get_default_compiler
from distutils.unixccompiler import UnixCCompiler
@@ -14,7 +17,6 @@ from distutils.tests import support
from test.support import run_unittest, swap_item
from .py38compat import TESTFN
-from .py38compat import check_warnings
class SysconfigTestCase(support.EnvironGuard, unittest.TestCase):
@@ -38,20 +40,23 @@ class SysconfigTestCase(support.EnvironGuard, unittest.TestCase):
config_h = sysconfig.get_config_h_filename()
self.assertTrue(os.path.isfile(config_h), config_h)
- @unittest.skipIf(sys.platform == 'win32',
- 'Makefile only exists on Unix like systems')
- @unittest.skipIf(sys.implementation.name != 'cpython',
- 'Makefile only exists in CPython')
+ @unittest.skipIf(
+ sys.platform == 'win32', 'Makefile only exists on Unix like systems'
+ )
+ @unittest.skipIf(
+ sys.implementation.name != 'cpython', 'Makefile only exists in CPython'
+ )
def test_get_makefile_filename(self):
makefile = sysconfig.get_makefile_filename()
self.assertTrue(os.path.isfile(makefile), makefile)
def test_get_python_lib(self):
# XXX doesn't work on Linux when Python was never installed before
- #self.assertTrue(os.path.isdir(lib_dir), lib_dir)
+ # self.assertTrue(os.path.isdir(lib_dir), lib_dir)
# test for pythonxx.lib?
- self.assertNotEqual(sysconfig.get_python_lib(),
- sysconfig.get_python_lib(prefix=TESTFN))
+ self.assertNotEqual(
+ sysconfig.get_python_lib(), sysconfig.get_python_lib(prefix=TESTFN)
+ )
def test_get_config_vars(self):
cvars = sysconfig.get_config_vars()
@@ -73,9 +78,7 @@ class SysconfigTestCase(support.EnvironGuard, unittest.TestCase):
self.assertTrue(os.path.exists(Python_h), Python_h)
self.assertTrue(sysconfig._is_python_source_dir(srcdir))
elif os.name == 'posix':
- self.assertEqual(
- os.path.dirname(sysconfig.get_makefile_filename()),
- srcdir)
+ self.assertEqual(os.path.dirname(sysconfig.get_makefile_filename()), srcdir)
def test_srcdir_independent_of_cwd(self):
# srcdir should be independent of the current working directory
@@ -111,7 +114,6 @@ class SysconfigTestCase(support.EnvironGuard, unittest.TestCase):
'CCSHARED': '--sc-ccshared',
'LDSHARED': 'sc_ldshared',
'SHLIB_SUFFIX': 'sc_shutil_suffix',
-
# On macOS, disable _osx_support.customize_compiler()
'CUSTOMIZED_OSX_COMPILER': 'True',
}
@@ -124,8 +126,9 @@ class SysconfigTestCase(support.EnvironGuard, unittest.TestCase):
return comp
- @unittest.skipUnless(get_default_compiler() == 'unix',
- 'not testing if default compiler is not unix')
+ @unittest.skipUnless(
+ get_default_compiler() == 'unix', 'not testing if default compiler is not unix'
+ )
def test_customize_compiler(self):
# Make sure that sysconfig._config_vars is initialized
sysconfig.get_config_vars()
@@ -142,27 +145,25 @@ class SysconfigTestCase(support.EnvironGuard, unittest.TestCase):
os.environ['RANLIB'] = 'env_ranlib'
comp = self.customize_compiler()
- self.assertEqual(comp.exes['archiver'],
- 'env_ar --env-arflags')
- self.assertEqual(comp.exes['preprocessor'],
- 'env_cpp --env-cppflags')
- self.assertEqual(comp.exes['compiler'],
- 'env_cc --sc-cflags --env-cflags --env-cppflags')
- self.assertEqual(comp.exes['compiler_so'],
- ('env_cc --sc-cflags '
- '--env-cflags ''--env-cppflags --sc-ccshared'))
- self.assertEqual(comp.exes['compiler_cxx'],
- 'env_cxx --env-cxx-flags')
- self.assertEqual(comp.exes['linker_exe'],
- 'env_cc')
- self.assertEqual(comp.exes['linker_so'],
- ('env_ldshared --env-ldflags --env-cflags'
- ' --env-cppflags'))
+ self.assertEqual(comp.exes['archiver'], 'env_ar --env-arflags')
+ self.assertEqual(comp.exes['preprocessor'], 'env_cpp --env-cppflags')
+ self.assertEqual(
+ comp.exes['compiler'], 'env_cc --sc-cflags --env-cflags --env-cppflags'
+ )
+ self.assertEqual(
+ comp.exes['compiler_so'],
+ ('env_cc --sc-cflags ' '--env-cflags ' '--env-cppflags --sc-ccshared'),
+ )
+ self.assertEqual(comp.exes['compiler_cxx'], 'env_cxx --env-cxx-flags')
+ self.assertEqual(comp.exes['linker_exe'], 'env_cc')
+ self.assertEqual(
+ comp.exes['linker_so'],
+ ('env_ldshared --env-ldflags --env-cflags' ' --env-cppflags'),
+ )
self.assertEqual(comp.shared_lib_extension, 'sc_shutil_suffix')
if sys.platform == "darwin":
- self.assertEqual(comp.exes['ranlib'],
- 'env_ranlib')
+ self.assertEqual(comp.exes['ranlib'], 'env_ranlib')
else:
self.assertTrue('ranlib' not in comp.exes)
@@ -178,20 +179,13 @@ class SysconfigTestCase(support.EnvironGuard, unittest.TestCase):
del os.environ['RANLIB']
comp = self.customize_compiler()
- self.assertEqual(comp.exes['archiver'],
- 'sc_ar --sc-arflags')
- self.assertEqual(comp.exes['preprocessor'],
- 'sc_cc -E')
- self.assertEqual(comp.exes['compiler'],
- 'sc_cc --sc-cflags')
- self.assertEqual(comp.exes['compiler_so'],
- 'sc_cc --sc-cflags --sc-ccshared')
- self.assertEqual(comp.exes['compiler_cxx'],
- 'sc_cxx')
- self.assertEqual(comp.exes['linker_exe'],
- 'sc_cc')
- self.assertEqual(comp.exes['linker_so'],
- 'sc_ldshared')
+ self.assertEqual(comp.exes['archiver'], 'sc_ar --sc-arflags')
+ self.assertEqual(comp.exes['preprocessor'], 'sc_cc -E')
+ self.assertEqual(comp.exes['compiler'], 'sc_cc --sc-cflags')
+ self.assertEqual(comp.exes['compiler_so'], 'sc_cc --sc-cflags --sc-ccshared')
+ self.assertEqual(comp.exes['compiler_cxx'], 'sc_cxx')
+ self.assertEqual(comp.exes['linker_exe'], 'sc_cc')
+ self.assertEqual(comp.exes['linker_so'], 'sc_ldshared')
self.assertEqual(comp.shared_lib_extension, 'sc_shutil_suffix')
self.assertTrue('ranlib' not in comp.exes)
@@ -204,8 +198,9 @@ class SysconfigTestCase(support.EnvironGuard, unittest.TestCase):
finally:
fd.close()
d = sysconfig.parse_makefile(self.makefile)
- self.assertEqual(d, {'CONFIG_ARGS': "'--arg1=optarg1' 'ENV=LIB'",
- 'OTHER': 'foo'})
+ self.assertEqual(
+ d, {'CONFIG_ARGS': "'--arg1=optarg1' 'ENV=LIB'", 'OTHER': 'foo'}
+ )
def test_parse_makefile_literal_dollar(self):
self.makefile = TESTFN
@@ -216,19 +211,25 @@ class SysconfigTestCase(support.EnvironGuard, unittest.TestCase):
finally:
fd.close()
d = sysconfig.parse_makefile(self.makefile)
- self.assertEqual(d, {'CONFIG_ARGS': r"'--arg1=optarg1' 'ENV=\$LIB'",
- 'OTHER': 'foo'})
-
+ self.assertEqual(
+ d, {'CONFIG_ARGS': r"'--arg1=optarg1' 'ENV=\$LIB'", 'OTHER': 'foo'}
+ )
def test_sysconfig_module(self):
import sysconfig as global_sysconfig
- self.assertEqual(global_sysconfig.get_config_var('CFLAGS'),
- sysconfig.get_config_var('CFLAGS'))
- self.assertEqual(global_sysconfig.get_config_var('LDFLAGS'),
- sysconfig.get_config_var('LDFLAGS'))
- @unittest.skipIf(sysconfig.get_config_var('CUSTOMIZED_OSX_COMPILER'),
- 'compiler flags customized')
+ self.assertEqual(
+ global_sysconfig.get_config_var('CFLAGS'),
+ sysconfig.get_config_var('CFLAGS'),
+ )
+ self.assertEqual(
+ global_sysconfig.get_config_var('LDFLAGS'),
+ sysconfig.get_config_var('LDFLAGS'),
+ )
+
+ @unittest.skipIf(
+ sysconfig.get_config_var('CUSTOMIZED_OSX_COMPILER'), 'compiler flags customized'
+ )
def test_sysconfig_compiler_vars(self):
# On OS X, binary installers support extension module building on
# various levels of the operating system with differing Xcode
@@ -245,49 +246,46 @@ class SysconfigTestCase(support.EnvironGuard, unittest.TestCase):
# The longer-term solution is to only have one version of sysconfig.
import sysconfig as global_sysconfig
+
if sysconfig.get_config_var('CUSTOMIZED_OSX_COMPILER'):
self.skipTest('compiler flags customized')
- self.assertEqual(global_sysconfig.get_config_var('LDSHARED'),
- sysconfig.get_config_var('LDSHARED'))
- self.assertEqual(global_sysconfig.get_config_var('CC'),
- sysconfig.get_config_var('CC'))
-
- @unittest.skipIf(sysconfig.get_config_var('EXT_SUFFIX') is None,
- 'EXT_SUFFIX required for this test')
+ self.assertEqual(
+ global_sysconfig.get_config_var('LDSHARED'),
+ sysconfig.get_config_var('LDSHARED'),
+ )
+ self.assertEqual(
+ global_sysconfig.get_config_var('CC'), sysconfig.get_config_var('CC')
+ )
+
+ @unittest.skipIf(
+ sysconfig.get_config_var('EXT_SUFFIX') is None,
+ 'EXT_SUFFIX required for this test',
+ )
def test_SO_deprecation(self):
- self.assertWarns(DeprecationWarning,
- sysconfig.get_config_var, 'SO')
-
- @unittest.skipIf(sysconfig.get_config_var('EXT_SUFFIX') is None,
- 'EXT_SUFFIX required for this test')
- def test_SO_value(self):
- with check_warnings(('', DeprecationWarning)):
- self.assertEqual(sysconfig.get_config_var('SO'),
- sysconfig.get_config_var('EXT_SUFFIX'))
-
- @unittest.skipIf(sysconfig.get_config_var('EXT_SUFFIX') is None,
- 'EXT_SUFFIX required for this test')
- def test_SO_in_vars(self):
- vars = sysconfig.get_config_vars()
- self.assertIsNotNone(vars['SO'])
- self.assertEqual(vars['SO'], vars['EXT_SUFFIX'])
+ self.assertWarns(DeprecationWarning, sysconfig.get_config_var, 'SO')
def test_customize_compiler_before_get_config_vars(self):
# Issue #21923: test that a Distribution compiler
# instance can be called without an explicit call to
# get_config_vars().
with open(TESTFN, 'w') as f:
- f.writelines(textwrap.dedent('''\
+ f.writelines(
+ textwrap.dedent(
+ '''\
from distutils.core import Distribution
config = Distribution().get_command_obj('config')
# try_compile may pass or it may fail if no compiler
# is found but it should not raise an exception.
rc = config.try_compile('int x;')
- '''))
- p = subprocess.Popen([str(sys.executable), TESTFN],
- stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT,
- universal_newlines=True)
+ '''
+ )
+ )
+ p = subprocess.Popen(
+ [str(sys.executable), TESTFN],
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ universal_newlines=True,
+ )
outs, errs = p.communicate()
self.assertEqual(0, p.returncode, "Subprocess failed: " + outs)
@@ -301,14 +299,40 @@ class SysconfigTestCase(support.EnvironGuard, unittest.TestCase):
result = sysconfig.parse_config_h(f)
self.assertTrue(isinstance(result, dict))
- @unittest.skipUnless(sys.platform == 'win32',
- 'Testing windows pyd suffix')
- @unittest.skipUnless(sys.implementation.name == 'cpython',
- 'Need cpython for this test')
+ @unittest.skipUnless(sys.platform == 'win32', 'Testing windows pyd suffix')
+ @unittest.skipUnless(
+ sys.implementation.name == 'cpython', 'Need cpython for this test'
+ )
def test_win_ext_suffix(self):
self.assertTrue(sysconfig.get_config_var("EXT_SUFFIX").endswith(".pyd"))
self.assertNotEqual(sysconfig.get_config_var("EXT_SUFFIX"), ".pyd")
+ @unittest.skipUnless(sys.platform == 'win32', 'Testing Windows build layout')
+ @unittest.skipUnless(
+ sys.implementation.name == 'cpython', 'Need cpython for this test'
+ )
+ @unittest.skipUnless(
+ '\\PCbuild\\'.casefold() in sys.executable.casefold(),
+ 'Need sys.executable to be in a source tree',
+ )
+ def test_win_build_venv_from_source_tree(self):
+ """Ensure distutils.sysconfig detects venvs from source tree builds."""
+ env = jaraco.envs.VEnv()
+ env.create_opts = env.clean_opts
+ env.root = TESTFN
+ env.ensure_env()
+ cmd = [
+ env.exe(),
+ "-c",
+ "import distutils.sysconfig; print(distutils.sysconfig.python_build)",
+ ]
+ distutils_path = os.path.dirname(os.path.dirname(distutils.__file__))
+ out = subprocess.check_output(
+ cmd, env={**os.environ, "PYTHONPATH": distutils_path}
+ )
+ assert out == "True"
+
+
def test_suite():
suite = unittest.TestSuite()
suite.addTest(unittest.TestLoader().loadTestsFromTestCase(SysconfigTestCase))
diff --git a/setuptools/_distutils/tests/test_text_file.py b/setuptools/_distutils/tests/test_text_file.py
index ebac3d52..16de9caa 100644
--- a/setuptools/_distutils/tests/test_text_file.py
+++ b/setuptools/_distutils/tests/test_text_file.py
@@ -12,32 +12,35 @@ line 3 \\
continues on next line
"""
-class TextFileTestCase(support.TempdirManager, unittest.TestCase):
+class TextFileTestCase(support.TempdirManager, unittest.TestCase):
def test_class(self):
# old tests moved from text_file.__main__
# so they are really called by the buildbots
# result 1: no fancy options
- result1 = ['# test file\n', '\n', 'line 3 \\\n',
- '# intervening comment\n',
- ' continues on next line\n']
+ result1 = [
+ '# test file\n',
+ '\n',
+ 'line 3 \\\n',
+ '# intervening comment\n',
+ ' continues on next line\n',
+ ]
# result 2: just strip comments
- result2 = ["\n",
- "line 3 \\\n",
- " continues on next line\n"]
+ result2 = ["\n", "line 3 \\\n", " continues on next line\n"]
# result 3: just strip blank lines
- result3 = ["# test file\n",
- "line 3 \\\n",
- "# intervening comment\n",
- " continues on next line\n"]
+ result3 = [
+ "# test file\n",
+ "line 3 \\\n",
+ "# intervening comment\n",
+ " continues on next line\n",
+ ]
# result 4: default, strip comments, blank lines,
# and trailing whitespace
- result4 = ["line 3 \\",
- " continues on next line"]
+ result4 = ["line 3 \\", " continues on next line"]
# result 5: strip comments and blanks, plus join lines (but don't
# "collapse" joined lines
@@ -59,22 +62,25 @@ class TextFileTestCase(support.TempdirManager, unittest.TestCase):
finally:
out_file.close()
- in_file = TextFile(filename, strip_comments=0, skip_blanks=0,
- lstrip_ws=0, rstrip_ws=0)
+ in_file = TextFile(
+ filename, strip_comments=0, skip_blanks=0, lstrip_ws=0, rstrip_ws=0
+ )
try:
test_input(1, "no processing", in_file, result1)
finally:
in_file.close()
- in_file = TextFile(filename, strip_comments=1, skip_blanks=0,
- lstrip_ws=0, rstrip_ws=0)
+ in_file = TextFile(
+ filename, strip_comments=1, skip_blanks=0, lstrip_ws=0, rstrip_ws=0
+ )
try:
test_input(2, "strip comments", in_file, result2)
finally:
in_file.close()
- in_file = TextFile(filename, strip_comments=0, skip_blanks=1,
- lstrip_ws=0, rstrip_ws=0)
+ in_file = TextFile(
+ filename, strip_comments=0, skip_blanks=1, lstrip_ws=0, rstrip_ws=0
+ )
try:
test_input(3, "strip blanks", in_file, result3)
finally:
@@ -86,22 +92,31 @@ class TextFileTestCase(support.TempdirManager, unittest.TestCase):
finally:
in_file.close()
- in_file = TextFile(filename, strip_comments=1, skip_blanks=1,
- join_lines=1, rstrip_ws=1)
+ in_file = TextFile(
+ filename, strip_comments=1, skip_blanks=1, join_lines=1, rstrip_ws=1
+ )
try:
test_input(5, "join lines without collapsing", in_file, result5)
finally:
in_file.close()
- in_file = TextFile(filename, strip_comments=1, skip_blanks=1,
- join_lines=1, rstrip_ws=1, collapse_join=1)
+ in_file = TextFile(
+ filename,
+ strip_comments=1,
+ skip_blanks=1,
+ join_lines=1,
+ rstrip_ws=1,
+ collapse_join=1,
+ )
try:
test_input(6, "join lines with collapsing", in_file, result6)
finally:
in_file.close()
+
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(TextFileTestCase)
+
if __name__ == "__main__":
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_unixccompiler.py b/setuptools/_distutils/tests/test_unixccompiler.py
index c8b4c149..879769fc 100644
--- a/setuptools/_distutils/tests/test_unixccompiler.py
+++ b/setuptools/_distutils/tests/test_unixccompiler.py
@@ -14,16 +14,18 @@ from distutils.util import _clear_cached_macosx_ver
from . import support
-class UnixCCompilerTestCase(support.TempdirManager, unittest.TestCase):
+class UnixCCompilerTestCase(support.TempdirManager, unittest.TestCase):
def setUp(self):
super().setUp()
self._backup_platform = sys.platform
self._backup_get_config_var = sysconfig.get_config_var
self._backup_get_config_vars = sysconfig.get_config_vars
+
class CompilerWrapper(UnixCCompiler):
def rpath_foo(self):
return self.runtime_library_dir_option('/foo')
+
self.cc = CompilerWrapper()
def tearDown(self):
@@ -49,18 +51,18 @@ class UnixCCompilerTestCase(support.TempdirManager, unittest.TestCase):
# Version value of None generates two tests: as None and as empty string
# Expected flag value of None means an mismatch exception is expected
darwin_test_cases = [
- ((None , None ), darwin_lib_flag),
- ((None , '11' ), darwin_rpath_flag),
- (('10' , None ), darwin_lib_flag),
- (('10.3' , None ), darwin_lib_flag),
- (('10.3.1', None ), darwin_lib_flag),
- (('10.5' , None ), darwin_rpath_flag),
- (('10.5.1', None ), darwin_rpath_flag),
- (('10.3' , '10.3' ), darwin_lib_flag),
- (('10.3' , '10.5' ), darwin_rpath_flag),
- (('10.5' , '10.3' ), darwin_lib_flag),
- (('10.5' , '11' ), darwin_rpath_flag),
- (('10.4' , '10' ), None),
+ ((None, None), darwin_lib_flag),
+ ((None, '11'), darwin_rpath_flag),
+ (('10', None), darwin_lib_flag),
+ (('10.3', None), darwin_lib_flag),
+ (('10.3.1', None), darwin_lib_flag),
+ (('10.5', None), darwin_rpath_flag),
+ (('10.5.1', None), darwin_rpath_flag),
+ (('10.3', '10.3'), darwin_lib_flag),
+ (('10.3', '10.5'), darwin_rpath_flag),
+ (('10.5', '10.3'), darwin_lib_flag),
+ (('10.5', '11'), darwin_rpath_flag),
+ (('10.4', '10'), None),
]
def make_darwin_gcv(syscfg_macosx_ver):
@@ -68,12 +70,15 @@ class UnixCCompilerTestCase(support.TempdirManager, unittest.TestCase):
if var == darwin_ver_var:
return syscfg_macosx_ver
return "xxx"
+
return gcv
def do_darwin_test(syscfg_macosx_ver, env_macosx_ver, expected_flag):
env = os.environ
- msg = "macOS version = (sysconfig=%r, env=%r)" % \
- (syscfg_macosx_ver, env_macosx_ver)
+ msg = "macOS version = (sysconfig=%r, env=%r)" % (
+ syscfg_macosx_ver,
+ env_macosx_ver,
+ )
# Save
old_gcv = sysconfig.get_config_var
@@ -91,8 +96,9 @@ class UnixCCompilerTestCase(support.TempdirManager, unittest.TestCase):
if expected_flag is not None:
self.assertEqual(self.cc.rpath_foo(), expected_flag, msg=msg)
else:
- with self.assertRaisesRegex(DistutilsPlatformError,
- darwin_ver_var + r' mismatch', msg=msg):
+ with self.assertRaisesRegex(
+ DistutilsPlatformError, darwin_ver_var + r' mismatch', msg=msg
+ ):
self.cc.rpath_foo()
# Restore
@@ -118,18 +124,22 @@ class UnixCCompilerTestCase(support.TempdirManager, unittest.TestCase):
# hp-ux
sys.platform = 'hp-ux'
+
def gcv(v):
return 'xxx'
+
sysconfig.get_config_var = gcv
self.assertEqual(self.cc.rpath_foo(), ['+s', '-L/foo'])
def gcv(v):
return 'gcc'
+
sysconfig.get_config_var = gcv
self.assertEqual(self.cc.rpath_foo(), ['-Wl,+s', '-L/foo'])
def gcv(v):
return 'g++'
+
sysconfig.get_config_var = gcv
self.assertEqual(self.cc.rpath_foo(), ['-Wl,+s', '-L/foo'])
@@ -137,11 +147,13 @@ class UnixCCompilerTestCase(support.TempdirManager, unittest.TestCase):
# GCC GNULD
sys.platform = 'bar'
+
def gcv(v):
if v == 'CC':
return 'gcc'
elif v == 'GNULD':
return 'yes'
+
sysconfig.get_config_var = gcv
self.assertEqual(self.cc.rpath_foo(), '-Wl,--enable-new-dtags,-R/foo')
@@ -150,47 +162,56 @@ class UnixCCompilerTestCase(support.TempdirManager, unittest.TestCase):
return 'gcc -pthread -B /bar'
elif v == 'GNULD':
return 'yes'
+
sysconfig.get_config_var = gcv
self.assertEqual(self.cc.rpath_foo(), '-Wl,--enable-new-dtags,-R/foo')
# GCC non-GNULD
sys.platform = 'bar'
+
def gcv(v):
if v == 'CC':
return 'gcc'
elif v == 'GNULD':
return 'no'
+
sysconfig.get_config_var = gcv
self.assertEqual(self.cc.rpath_foo(), '-Wl,-R/foo')
# GCC GNULD with fully qualified configuration prefix
# see #7617
sys.platform = 'bar'
+
def gcv(v):
if v == 'CC':
return 'x86_64-pc-linux-gnu-gcc-4.4.2'
elif v == 'GNULD':
return 'yes'
+
sysconfig.get_config_var = gcv
self.assertEqual(self.cc.rpath_foo(), '-Wl,--enable-new-dtags,-R/foo')
# non-GCC GNULD
sys.platform = 'bar'
+
def gcv(v):
if v == 'CC':
return 'cc'
elif v == 'GNULD':
return 'yes'
+
sysconfig.get_config_var = gcv
self.assertEqual(self.cc.rpath_foo(), '-Wl,--enable-new-dtags,-R/foo')
# non-GCC non-GNULD
sys.platform = 'bar'
+
def gcv(v):
if v == 'CC':
return 'cc'
elif v == 'GNULD':
return 'no'
+
sysconfig.get_config_var = gcv
self.assertEqual(self.cc.rpath_foo(), '-Wl,-R/foo')
@@ -207,6 +228,7 @@ class UnixCCompilerTestCase(support.TempdirManager, unittest.TestCase):
if args:
return list(map(sysconfig.get_config_var, args))
return _orig()
+
sysconfig.get_config_var = gcv
sysconfig.get_config_vars = gcvs
with EnvironmentVarGuard() as env:
@@ -223,6 +245,7 @@ class UnixCCompilerTestCase(support.TempdirManager, unittest.TestCase):
pypa/distutils#126
"""
+
def gcv(v):
if v == 'LDSHARED':
return 'gcc-4.2 -bundle -undefined dynamic_lookup '
@@ -237,10 +260,13 @@ class UnixCCompilerTestCase(support.TempdirManager, unittest.TestCase):
sysconfig.get_config_var = gcv
sysconfig.get_config_vars = gcvs
- with patch.object(self.cc, 'spawn', return_value=None) as mock_spawn, \
- patch.object(self.cc, '_need_link', return_value=True), \
- patch.object(self.cc, 'mkpath', return_value=None), \
- EnvironmentVarGuard() as env:
+ with patch.object(
+ self.cc, 'spawn', return_value=None
+ ) as mock_spawn, patch.object(
+ self.cc, '_need_link', return_value=True
+ ), patch.object(
+ self.cc, 'mkpath', return_value=None
+ ), EnvironmentVarGuard() as env:
env['CC'] = 'ccache my_cc'
env['CXX'] = 'my_cxx'
del env['LDSHARED']
@@ -265,6 +291,7 @@ class UnixCCompilerTestCase(support.TempdirManager, unittest.TestCase):
if args:
return list(map(sysconfig.get_config_var, args))
return _orig()
+
sysconfig.get_config_var = gcv
sysconfig.get_config_vars = gcvs
with EnvironmentVarGuard() as env:
@@ -285,5 +312,6 @@ class UnixCCompilerTestCase(support.TempdirManager, unittest.TestCase):
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(UnixCCompilerTestCase)
+
if __name__ == "__main__":
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_upload.py b/setuptools/_distutils/tests/test_upload.py
index ce3e84a2..afba2fae 100644
--- a/setuptools/_distutils/tests/test_upload.py
+++ b/setuptools/_distutils/tests/test_upload.py
@@ -43,8 +43,8 @@ index-servers =
username:me
"""
-class FakeOpen(object):
+class FakeOpen(object):
def __init__(self, url, msg=None, code=None):
self.url = url
if not isinstance(url, str):
@@ -57,7 +57,7 @@ class FakeOpen(object):
def getheader(self, name, default=None):
return {
'content-type': 'text/plain; charset=utf-8',
- }.get(name.lower(), default)
+ }.get(name.lower(), default)
def read(self):
return b'xyzzy'
@@ -67,7 +67,6 @@ class FakeOpen(object):
class uploadTestCase(BasePyPIRCCommandTestCase):
-
def setUp(self):
super(uploadTestCase, self).setUp()
self.old_open = upload_mod.urlopen
@@ -91,9 +90,12 @@ class uploadTestCase(BasePyPIRCCommandTestCase):
dist = Distribution()
cmd = upload(dist)
cmd.finalize_options()
- for attr, waited in (('username', 'me'), ('password', 'secret'),
- ('realm', 'pypi'),
- ('repository', 'https://upload.pypi.org/legacy/')):
+ for attr, waited in (
+ ('username', 'me'),
+ ('password', 'secret'),
+ ('realm', 'pypi'),
+ ('repository', 'https://upload.pypi.org/legacy/'),
+ ):
self.assertEqual(getattr(cmd, attr), waited)
def test_saved_password(self):
@@ -137,13 +139,12 @@ class uploadTestCase(BasePyPIRCCommandTestCase):
expected_url = 'https://upload.pypi.org/legacy/'
self.assertEqual(self.last_open.req.get_full_url(), expected_url)
data = self.last_open.req.data
- self.assertIn(b'xxx',data)
+ self.assertIn(b'xxx', data)
self.assertIn(b'protocol_version', data)
self.assertIn(b'sha256_digest', data)
self.assertIn(
- b'cd2eb0837c9b4c962c22d2ff8b5441b7b45805887f051d39bf133b583baf'
- b'6860',
- data
+ b'cd2eb0837c9b4c962c22d2ff8b5441b7b45805887f051d39bf133b583baf' b'6860',
+ data,
)
if b'md5_digest' in data:
self.assertIn(b'f561aaf6ef0bf14d4208bb46a4ccb3ad', data)
@@ -152,7 +153,7 @@ class uploadTestCase(BasePyPIRCCommandTestCase):
b'b6f289a27d4fe90da63c503bfe0a9b761a8f76bb86148565065f040be'
b'6d1c3044cf7ded78ef800509bccb4b648e507d88dc6383d67642aadcc'
b'ce443f1534330a',
- data
+ data,
)
# The PyPI response body was echoed
@@ -173,8 +174,7 @@ class uploadTestCase(BasePyPIRCCommandTestCase):
# other fields that ended with \r used to be modified, now are
# preserved.
pkg_dir, dist = self.create_dist(
- dist_files=dist_files,
- description='long description\r'
+ dist_files=dist_files, description='long description\r'
)
cmd = upload(dist)
cmd.show_response = 1
@@ -200,13 +200,18 @@ class uploadTestCase(BasePyPIRCCommandTestCase):
pkg_dir, dist = self.create_dist(dist_files=dist_files)
tests = [
(OSError('oserror'), 'oserror', OSError),
- (HTTPError('url', 400, 'httperror', {}, None),
- 'Upload failed (400): httperror', DistutilsError),
+ (
+ HTTPError('url', 400, 'httperror', {}, None),
+ 'Upload failed (400): httperror',
+ DistutilsError,
+ ),
]
for exception, expected, raised_exception in tests:
with self.subTest(exception=type(exception).__name__):
- with mock.patch('distutils.command.upload.urlopen',
- new=mock.Mock(side_effect=exception)):
+ with mock.patch(
+ 'distutils.command.upload.urlopen',
+ new=mock.Mock(side_effect=exception),
+ ):
with self.assertRaises(raised_exception):
cmd = upload(dist)
cmd.ensure_finalized()
@@ -219,5 +224,6 @@ class uploadTestCase(BasePyPIRCCommandTestCase):
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(uploadTestCase)
+
if __name__ == "__main__":
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_util.py b/setuptools/_distutils/tests/test_util.py
index 2738388e..cebd61cc 100644
--- a/setuptools/_distutils/tests/test_util.py
+++ b/setuptools/_distutils/tests/test_util.py
@@ -8,16 +8,24 @@ from test.support import run_unittest
from unittest import mock
from distutils.errors import DistutilsPlatformError, DistutilsByteCompileError
-from distutils.util import (get_platform, convert_path, change_root,
- check_environ, split_quoted, strtobool,
- rfc822_escape, byte_compile,
- grok_environment_error, get_host_platform)
-from distutils import util # used to patch _environ_checked
+from distutils.util import (
+ get_platform,
+ convert_path,
+ change_root,
+ check_environ,
+ split_quoted,
+ strtobool,
+ rfc822_escape,
+ byte_compile,
+ grok_environment_error,
+ get_host_platform,
+)
+from distutils import util # used to patch _environ_checked
from distutils import sysconfig
from distutils.tests import support
-class UtilTestCase(support.EnvironGuard, unittest.TestCase):
+class UtilTestCase(support.EnvironGuard, unittest.TestCase):
def setUp(self):
super(UtilTestCase, self).setUp()
# saving the environment
@@ -64,9 +72,9 @@ class UtilTestCase(support.EnvironGuard, unittest.TestCase):
def test_get_host_platform(self):
with unittest.mock.patch('os.name', 'nt'):
- with unittest.mock.patch('sys.version', '... [... (ARM64)]'):
+ with unittest.mock.patch('sys.version', '... [... (ARM64)]'):
self.assertEqual(get_host_platform(), 'win-arm64')
- with unittest.mock.patch('sys.version', '... [... (ARM)]'):
+ with unittest.mock.patch('sys.version', '... [... (ARM)]'):
self.assertEqual(get_host_platform(), 'win-arm32')
with unittest.mock.patch('sys.version_info', (3, 9, 0, 'final', 0)):
@@ -75,76 +83,86 @@ class UtilTestCase(support.EnvironGuard, unittest.TestCase):
def test_get_platform(self):
with unittest.mock.patch('os.name', 'nt'):
with unittest.mock.patch.dict('os.environ', {'VSCMD_ARG_TGT_ARCH': 'x86'}):
- self.assertEqual(get_platform(), 'win32')
+ self.assertEqual(get_platform(), 'win32')
with unittest.mock.patch.dict('os.environ', {'VSCMD_ARG_TGT_ARCH': 'x64'}):
- self.assertEqual(get_platform(), 'win-amd64')
+ self.assertEqual(get_platform(), 'win-amd64')
with unittest.mock.patch.dict('os.environ', {'VSCMD_ARG_TGT_ARCH': 'arm'}):
- self.assertEqual(get_platform(), 'win-arm32')
- with unittest.mock.patch.dict('os.environ', {'VSCMD_ARG_TGT_ARCH': 'arm64'}):
- self.assertEqual(get_platform(), 'win-arm64')
+ self.assertEqual(get_platform(), 'win-arm32')
+ with unittest.mock.patch.dict(
+ 'os.environ', {'VSCMD_ARG_TGT_ARCH': 'arm64'}
+ ):
+ self.assertEqual(get_platform(), 'win-arm64')
def test_convert_path(self):
# linux/mac
os.sep = '/'
+
def _join(path):
return '/'.join(path)
+
os.path.join = _join
- self.assertEqual(convert_path('/home/to/my/stuff'),
- '/home/to/my/stuff')
+ self.assertEqual(convert_path('/home/to/my/stuff'), '/home/to/my/stuff')
# win
os.sep = '\\'
+
def _join(*path):
return '\\'.join(path)
+
os.path.join = _join
self.assertRaises(ValueError, convert_path, '/home/to/my/stuff')
self.assertRaises(ValueError, convert_path, 'home/to/my/stuff/')
- self.assertEqual(convert_path('home/to/my/stuff'),
- 'home\\to\\my\\stuff')
- self.assertEqual(convert_path('.'),
- os.curdir)
+ self.assertEqual(convert_path('home/to/my/stuff'), 'home\\to\\my\\stuff')
+ self.assertEqual(convert_path('.'), os.curdir)
def test_change_root(self):
# linux/mac
os.name = 'posix'
+
def _isabs(path):
return path[0] == '/'
+
os.path.isabs = _isabs
+
def _join(*path):
return '/'.join(path)
+
os.path.join = _join
- self.assertEqual(change_root('/root', '/old/its/here'),
- '/root/old/its/here')
- self.assertEqual(change_root('/root', 'its/here'),
- '/root/its/here')
+ self.assertEqual(change_root('/root', '/old/its/here'), '/root/old/its/here')
+ self.assertEqual(change_root('/root', 'its/here'), '/root/its/here')
# windows
os.name = 'nt'
+
def _isabs(path):
return path.startswith('c:\\')
+
os.path.isabs = _isabs
+
def _splitdrive(path):
if path.startswith('c:'):
return ('', path.replace('c:', ''))
return ('', path)
+
os.path.splitdrive = _splitdrive
+
def _join(*path):
return '\\'.join(path)
+
os.path.join = _join
- self.assertEqual(change_root('c:\\root', 'c:\\old\\its\\here'),
- 'c:\\root\\old\\its\\here')
- self.assertEqual(change_root('c:\\root', 'its\\here'),
- 'c:\\root\\its\\here')
+ self.assertEqual(
+ change_root('c:\\root', 'c:\\old\\its\\here'), 'c:\\root\\old\\its\\here'
+ )
+ self.assertEqual(change_root('c:\\root', 'its\\here'), 'c:\\root\\its\\here')
# BugsBunny os (it's a great os)
os.name = 'BugsBunny'
- self.assertRaises(DistutilsPlatformError,
- change_root, 'c:\\root', 'its\\here')
+ self.assertRaises(DistutilsPlatformError, change_root, 'c:\\root', 'its\\here')
# XXX platforms to be covered: mac
@@ -165,8 +183,9 @@ class UtilTestCase(support.EnvironGuard, unittest.TestCase):
import pwd
# only set pw_dir field, other fields are not used
- result = pwd.struct_passwd((None, None, None, None, None,
- '/home/distutils', None))
+ result = pwd.struct_passwd(
+ (None, None, None, None, None, '/home/distutils', None)
+ )
with mock.patch.object(pwd, 'getpwuid', return_value=result):
check_environ()
self.assertEqual(os.environ['HOME'], '/home/distutils')
@@ -180,8 +199,10 @@ class UtilTestCase(support.EnvironGuard, unittest.TestCase):
self.assertNotIn('HOME', os.environ)
def test_split_quoted(self):
- self.assertEqual(split_quoted('""one"" "two" \'three\' \\four'),
- ['one', 'two', 'three', 'four'])
+ self.assertEqual(
+ split_quoted('""one"" "two" \'three\' \\four'),
+ ['one', 'two', 'three', 'four'],
+ )
def test_strtobool(self):
yes = ('y', 'Y', 'yes', 'True', 't', 'true', 'True', 'On', 'on', '1')
@@ -196,8 +217,9 @@ class UtilTestCase(support.EnvironGuard, unittest.TestCase):
def test_rfc822_escape(self):
header = 'I am a\npoor\nlonesome\nheader\n'
res = rfc822_escape(header)
- wanted = ('I am a%(8s)spoor%(8s)slonesome%(8s)s'
- 'header%(8s)s') % {'8s': '\n'+8*' '}
+ wanted = ('I am a%(8s)spoor%(8s)slonesome%(8s)s' 'header%(8s)s') % {
+ '8s': '\n' + 8 * ' '
+ }
self.assertEqual(res, wanted)
def test_dont_write_bytecode(self):
@@ -220,5 +242,6 @@ class UtilTestCase(support.EnvironGuard, unittest.TestCase):
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(UtilTestCase)
+
if __name__ == "__main__":
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_version.py b/setuptools/_distutils/tests/test_version.py
index 8405aa3a..cecb279f 100644
--- a/setuptools/_distutils/tests/test_version.py
+++ b/setuptools/_distutils/tests/test_version.py
@@ -5,8 +5,8 @@ from distutils.version import LooseVersion
from distutils.version import StrictVersion
from test.support import run_unittest
-class VersionTestCase(unittest.TestCase):
+class VersionTestCase(unittest.TestCase):
def setUp(self):
self.ctx = distutils.version.suppress_known_deprecation()
self.ctx.__enter__()
@@ -24,21 +24,23 @@ class VersionTestCase(unittest.TestCase):
self.assertEqual(str(version), '1.2')
def test_cmp_strict(self):
- versions = (('1.5.1', '1.5.2b2', -1),
- ('161', '3.10a', ValueError),
- ('8.02', '8.02', 0),
- ('3.4j', '1996.07.12', ValueError),
- ('3.2.pl0', '3.1.1.6', ValueError),
- ('2g6', '11g', ValueError),
- ('0.9', '2.2', -1),
- ('1.2.1', '1.2', 1),
- ('1.1', '1.2.2', -1),
- ('1.2', '1.1', 1),
- ('1.2.1', '1.2.2', -1),
- ('1.2.2', '1.2', 1),
- ('1.2', '1.2.2', -1),
- ('0.4.0', '0.4', 0),
- ('1.13++', '5.5.kw', ValueError))
+ versions = (
+ ('1.5.1', '1.5.2b2', -1),
+ ('161', '3.10a', ValueError),
+ ('8.02', '8.02', 0),
+ ('3.4j', '1996.07.12', ValueError),
+ ('3.2.pl0', '3.1.1.6', ValueError),
+ ('2g6', '11g', ValueError),
+ ('0.9', '2.2', -1),
+ ('1.2.1', '1.2', 1),
+ ('1.1', '1.2.2', -1),
+ ('1.2', '1.1', 1),
+ ('1.2.1', '1.2.2', -1),
+ ('1.2.2', '1.2', 1),
+ ('1.2', '1.2.2', -1),
+ ('0.4.0', '0.4', 0),
+ ('1.13++', '5.5.kw', ValueError),
+ )
for v1, v2, wanted in versions:
try:
@@ -47,49 +49,55 @@ class VersionTestCase(unittest.TestCase):
if wanted is ValueError:
continue
else:
- raise AssertionError(("cmp(%s, %s) "
- "shouldn't raise ValueError")
- % (v1, v2))
- self.assertEqual(res, wanted,
- 'cmp(%s, %s) should be %s, got %s' %
- (v1, v2, wanted, res))
+ raise AssertionError(
+ ("cmp(%s, %s) " "shouldn't raise ValueError") % (v1, v2)
+ )
+ self.assertEqual(
+ res, wanted, 'cmp(%s, %s) should be %s, got %s' % (v1, v2, wanted, res)
+ )
res = StrictVersion(v1)._cmp(v2)
- self.assertEqual(res, wanted,
- 'cmp(%s, %s) should be %s, got %s' %
- (v1, v2, wanted, res))
+ self.assertEqual(
+ res, wanted, 'cmp(%s, %s) should be %s, got %s' % (v1, v2, wanted, res)
+ )
res = StrictVersion(v1)._cmp(object())
- self.assertIs(res, NotImplemented,
- 'cmp(%s, %s) should be NotImplemented, got %s' %
- (v1, v2, res))
-
+ self.assertIs(
+ res,
+ NotImplemented,
+ 'cmp(%s, %s) should be NotImplemented, got %s' % (v1, v2, res),
+ )
def test_cmp(self):
- versions = (('1.5.1', '1.5.2b2', -1),
- ('161', '3.10a', 1),
- ('8.02', '8.02', 0),
- ('3.4j', '1996.07.12', -1),
- ('3.2.pl0', '3.1.1.6', 1),
- ('2g6', '11g', -1),
- ('0.960923', '2.2beta29', -1),
- ('1.13++', '5.5.kw', -1))
-
+ versions = (
+ ('1.5.1', '1.5.2b2', -1),
+ ('161', '3.10a', 1),
+ ('8.02', '8.02', 0),
+ ('3.4j', '1996.07.12', -1),
+ ('3.2.pl0', '3.1.1.6', 1),
+ ('2g6', '11g', -1),
+ ('0.960923', '2.2beta29', -1),
+ ('1.13++', '5.5.kw', -1),
+ )
for v1, v2, wanted in versions:
res = LooseVersion(v1)._cmp(LooseVersion(v2))
- self.assertEqual(res, wanted,
- 'cmp(%s, %s) should be %s, got %s' %
- (v1, v2, wanted, res))
+ self.assertEqual(
+ res, wanted, 'cmp(%s, %s) should be %s, got %s' % (v1, v2, wanted, res)
+ )
res = LooseVersion(v1)._cmp(v2)
- self.assertEqual(res, wanted,
- 'cmp(%s, %s) should be %s, got %s' %
- (v1, v2, wanted, res))
+ self.assertEqual(
+ res, wanted, 'cmp(%s, %s) should be %s, got %s' % (v1, v2, wanted, res)
+ )
res = LooseVersion(v1)._cmp(object())
- self.assertIs(res, NotImplemented,
- 'cmp(%s, %s) should be NotImplemented, got %s' %
- (v1, v2, res))
+ self.assertIs(
+ res,
+ NotImplemented,
+ 'cmp(%s, %s) should be NotImplemented, got %s' % (v1, v2, res),
+ )
+
def test_suite():
return unittest.TestLoader().loadTestsFromTestCase(VersionTestCase)
+
if __name__ == "__main__":
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/test_versionpredicate.py b/setuptools/_distutils/tests/test_versionpredicate.py
index 28ae09dc..ce3d0f46 100644
--- a/setuptools/_distutils/tests/test_versionpredicate.py
+++ b/setuptools/_distutils/tests/test_versionpredicate.py
@@ -6,8 +6,10 @@ import distutils.versionpredicate
import doctest
from test.support import run_unittest
+
def test_suite():
return doctest.DocTestSuite(distutils.versionpredicate)
+
if __name__ == '__main__':
run_unittest(test_suite())
diff --git a/setuptools/_distutils/tests/unix_compat.py b/setuptools/_distutils/tests/unix_compat.py
index b7718c26..8250b363 100644
--- a/setuptools/_distutils/tests/unix_compat.py
+++ b/setuptools/_distutils/tests/unix_compat.py
@@ -11,6 +11,5 @@ except ImportError:
UNIX_ID_SUPPORT = grp and pwd
UID_0_SUPPORT = UNIX_ID_SUPPORT and sys.platform != "cygwin"
-require_unix_id = unittest.skipUnless(
- UNIX_ID_SUPPORT, "Requires grp and pwd support")
+require_unix_id = unittest.skipUnless(UNIX_ID_SUPPORT, "Requires grp and pwd support")
require_uid_0 = unittest.skipUnless(UID_0_SUPPORT, "Requires UID 0 support")
diff --git a/setuptools/_distutils/text_file.py b/setuptools/_distutils/text_file.py
index 93abad38..015d6802 100644
--- a/setuptools/_distutils/text_file.py
+++ b/setuptools/_distutils/text_file.py
@@ -9,79 +9,82 @@ import sys, io
class TextFile:
"""Provides a file-like object that takes care of all the things you
- commonly want to do when processing a text file that has some
- line-by-line syntax: strip comments (as long as "#" is your
- comment character), skip blank lines, join adjacent lines by
- escaping the newline (ie. backslash at end of line), strip
- leading and/or trailing whitespace. All of these are optional
- and independently controllable.
-
- Provides a 'warn()' method so you can generate warning messages that
- report physical line number, even if the logical line in question
- spans multiple physical lines. Also provides 'unreadline()' for
- implementing line-at-a-time lookahead.
-
- Constructor is called as:
-
- TextFile (filename=None, file=None, **options)
-
- It bombs (RuntimeError) if both 'filename' and 'file' are None;
- 'filename' should be a string, and 'file' a file object (or
- something that provides 'readline()' and 'close()' methods). It is
- recommended that you supply at least 'filename', so that TextFile
- can include it in warning messages. If 'file' is not supplied,
- TextFile creates its own using 'io.open()'.
-
- The options are all boolean, and affect the value returned by
- 'readline()':
- strip_comments [default: true]
- strip from "#" to end-of-line, as well as any whitespace
- leading up to the "#" -- unless it is escaped by a backslash
- lstrip_ws [default: false]
- strip leading whitespace from each line before returning it
- rstrip_ws [default: true]
- strip trailing whitespace (including line terminator!) from
- each line before returning it
- skip_blanks [default: true}
- skip lines that are empty *after* stripping comments and
- whitespace. (If both lstrip_ws and rstrip_ws are false,
- then some lines may consist of solely whitespace: these will
- *not* be skipped, even if 'skip_blanks' is true.)
- join_lines [default: false]
- if a backslash is the last non-newline character on a line
- after stripping comments and whitespace, join the following line
- to it to form one "logical line"; if N consecutive lines end
- with a backslash, then N+1 physical lines will be joined to
- form one logical line.
- collapse_join [default: false]
- strip leading whitespace from lines that are joined to their
- predecessor; only matters if (join_lines and not lstrip_ws)
- errors [default: 'strict']
- error handler used to decode the file content
-
- Note that since 'rstrip_ws' can strip the trailing newline, the
- semantics of 'readline()' must differ from those of the builtin file
- object's 'readline()' method! In particular, 'readline()' returns
- None for end-of-file: an empty string might just be a blank line (or
- an all-whitespace line), if 'rstrip_ws' is true but 'skip_blanks' is
- not."""
-
- default_options = { 'strip_comments': 1,
- 'skip_blanks': 1,
- 'lstrip_ws': 0,
- 'rstrip_ws': 1,
- 'join_lines': 0,
- 'collapse_join': 0,
- 'errors': 'strict',
- }
+ commonly want to do when processing a text file that has some
+ line-by-line syntax: strip comments (as long as "#" is your
+ comment character), skip blank lines, join adjacent lines by
+ escaping the newline (ie. backslash at end of line), strip
+ leading and/or trailing whitespace. All of these are optional
+ and independently controllable.
+
+ Provides a 'warn()' method so you can generate warning messages that
+ report physical line number, even if the logical line in question
+ spans multiple physical lines. Also provides 'unreadline()' for
+ implementing line-at-a-time lookahead.
+
+ Constructor is called as:
+
+ TextFile (filename=None, file=None, **options)
+
+ It bombs (RuntimeError) if both 'filename' and 'file' are None;
+ 'filename' should be a string, and 'file' a file object (or
+ something that provides 'readline()' and 'close()' methods). It is
+ recommended that you supply at least 'filename', so that TextFile
+ can include it in warning messages. If 'file' is not supplied,
+ TextFile creates its own using 'io.open()'.
+
+ The options are all boolean, and affect the value returned by
+ 'readline()':
+ strip_comments [default: true]
+ strip from "#" to end-of-line, as well as any whitespace
+ leading up to the "#" -- unless it is escaped by a backslash
+ lstrip_ws [default: false]
+ strip leading whitespace from each line before returning it
+ rstrip_ws [default: true]
+ strip trailing whitespace (including line terminator!) from
+ each line before returning it
+ skip_blanks [default: true}
+ skip lines that are empty *after* stripping comments and
+ whitespace. (If both lstrip_ws and rstrip_ws are false,
+ then some lines may consist of solely whitespace: these will
+ *not* be skipped, even if 'skip_blanks' is true.)
+ join_lines [default: false]
+ if a backslash is the last non-newline character on a line
+ after stripping comments and whitespace, join the following line
+ to it to form one "logical line"; if N consecutive lines end
+ with a backslash, then N+1 physical lines will be joined to
+ form one logical line.
+ collapse_join [default: false]
+ strip leading whitespace from lines that are joined to their
+ predecessor; only matters if (join_lines and not lstrip_ws)
+ errors [default: 'strict']
+ error handler used to decode the file content
+
+ Note that since 'rstrip_ws' can strip the trailing newline, the
+ semantics of 'readline()' must differ from those of the builtin file
+ object's 'readline()' method! In particular, 'readline()' returns
+ None for end-of-file: an empty string might just be a blank line (or
+ an all-whitespace line), if 'rstrip_ws' is true but 'skip_blanks' is
+ not."""
+
+ default_options = {
+ 'strip_comments': 1,
+ 'skip_blanks': 1,
+ 'lstrip_ws': 0,
+ 'rstrip_ws': 1,
+ 'join_lines': 0,
+ 'collapse_join': 0,
+ 'errors': 'strict',
+ }
def __init__(self, filename=None, file=None, **options):
"""Construct a new TextFile object. At least one of 'filename'
- (a string) and 'file' (a file-like object) must be supplied.
- They keyword argument options are described above and affect
- the values returned by 'readline()'."""
+ (a string) and 'file' (a file-like object) must be supplied.
+ They keyword argument options are described above and affect
+ the values returned by 'readline()'."""
if filename is None and file is None:
- raise RuntimeError("you must supply either or both of 'filename' and 'file'")
+ raise RuntimeError(
+ "you must supply either or both of 'filename' and 'file'"
+ )
# set values for all options -- either from client option hash
# or fallback to default_options
@@ -101,7 +104,7 @@ class TextFile:
else:
self.filename = filename
self.file = file
- self.current_line = 0 # assuming that file is at BOF!
+ self.current_line = 0 # assuming that file is at BOF!
# 'linebuf' is a stack of lines that will be emptied before we
# actually read from the file; it's only populated by an
@@ -110,14 +113,14 @@ class TextFile:
def open(self, filename):
"""Open a new file named 'filename'. This overrides both the
- 'filename' and 'file' arguments to the constructor."""
+ 'filename' and 'file' arguments to the constructor."""
self.filename = filename
self.file = io.open(self.filename, 'r', errors=self.errors)
self.current_line = 0
def close(self):
"""Close the current file and forget everything we know about it
- (filename, current line number)."""
+ (filename, current line number)."""
file = self.file
self.file = None
self.filename = None
@@ -141,24 +144,24 @@ class TextFile:
def warn(self, msg, line=None):
"""Print (to stderr) a warning message tied to the current logical
- line in the current file. If the current logical line in the
- file spans multiple physical lines, the warning refers to the
- whole range, eg. "lines 3-5". If 'line' supplied, it overrides
- the current line number; it may be a list or tuple to indicate a
- range of physical lines, or an integer for a single physical
- line."""
+ line in the current file. If the current logical line in the
+ file spans multiple physical lines, the warning refers to the
+ whole range, eg. "lines 3-5". If 'line' supplied, it overrides
+ the current line number; it may be a list or tuple to indicate a
+ range of physical lines, or an integer for a single physical
+ line."""
sys.stderr.write("warning: " + self.gen_error(msg, line) + "\n")
def readline(self):
"""Read and return a single logical line from the current file (or
- from an internal buffer if lines have previously been "unread"
- with 'unreadline()'). If the 'join_lines' option is true, this
- may involve reading multiple physical lines concatenated into a
- single string. Updates the current line number, so calling
- 'warn()' after 'readline()' emits a warning about the physical
- line(s) just read. Returns None on end-of-file, since the empty
- string can occur if 'rstrip_ws' is true but 'strip_blanks' is
- not."""
+ from an internal buffer if lines have previously been "unread"
+ with 'unreadline()'). If the 'join_lines' option is true, this
+ may involve reading multiple physical lines concatenated into a
+ single string. Updates the current line number, so calling
+ 'warn()' after 'readline()' emits a warning about the physical
+ line(s) just read. Returns None on end-of-file, since the empty
+ string can occur if 'rstrip_ws' is true but 'strip_blanks' is
+ not."""
# If any "unread" lines waiting in 'linebuf', return the top
# one. (We don't actually buffer read-ahead data -- lines only
# get put in 'linebuf' if the client explicitly does an
@@ -187,12 +190,12 @@ class TextFile:
# lurking in there) and otherwise leave the line alone.
pos = line.find("#")
- if pos == -1: # no "#" -- no comments
+ if pos == -1: # no "#" -- no comments
pass
# It's definitely a comment -- either "#" is the first
# character, or it's elsewhere and unescaped.
- elif pos == 0 or line[pos-1] != "\\":
+ elif pos == 0 or line[pos - 1] != "\\":
# Have to preserve the trailing newline, because it's
# the job of a later step (rstrip_ws) to remove it --
# and if rstrip_ws is false, we'd better preserve it!
@@ -211,15 +214,14 @@ class TextFile:
# result in "hello there".
if line.strip() == "":
continue
- else: # it's an escaped "#"
+ else: # it's an escaped "#"
line = line.replace("\\#", "#")
# did previous line end with a backslash? then accumulate
if self.join_lines and buildup_line:
# oops: end of file
if line is None:
- self.warn("continuation line immediately precedes "
- "end-of-file")
+ self.warn("continuation line immediately precedes " "end-of-file")
return buildup_line
if self.collapse_join:
@@ -230,11 +232,10 @@ class TextFile:
if isinstance(self.current_line, list):
self.current_line[1] = self.current_line[1] + 1
else:
- self.current_line = [self.current_line,
- self.current_line + 1]
+ self.current_line = [self.current_line, self.current_line + 1]
# just an ordinary line, read it as usual
else:
- if line is None: # eof
+ if line is None: # eof
return None
# still have to be careful about incrementing the line number!
@@ -271,7 +272,7 @@ class TextFile:
def readlines(self):
"""Read and return the list of all logical lines remaining in the
- current file."""
+ current file."""
lines = []
while True:
line = self.readline()
@@ -281,6 +282,6 @@ class TextFile:
def unreadline(self, line):
"""Push 'line' (a string) onto an internal buffer that will be
- checked by future 'readline()' calls. Handy for implementing
- a parser with line-at-a-time lookahead."""
+ checked by future 'readline()' calls. Handy for implementing
+ a parser with line-at-a-time lookahead."""
self.linebuf.append(line)
diff --git a/setuptools/_distutils/unixccompiler.py b/setuptools/_distutils/unixccompiler.py
index 715408f5..4be74fdf 100644
--- a/setuptools/_distutils/unixccompiler.py
+++ b/setuptools/_distutils/unixccompiler.py
@@ -17,10 +17,8 @@ import os, sys, re, shlex
from distutils import sysconfig
from distutils.dep_util import newer
-from distutils.ccompiler import \
- CCompiler, gen_preprocess_options, gen_lib_options
-from distutils.errors import \
- DistutilsExecError, CompileError, LibError, LinkError
+from distutils.ccompiler import CCompiler, gen_preprocess_options, gen_lib_options
+from distutils.errors import DistutilsExecError, CompileError, LibError, LinkError
from distutils import log
from ._macos_compat import compiler_fixup
@@ -110,15 +108,16 @@ class UnixCCompiler(CCompiler):
# are pretty generic; they will probably have to be set by an outsider
# (eg. using information discovered by the sysconfig about building
# Python extensions).
- executables = {'preprocessor' : None,
- 'compiler' : ["cc"],
- 'compiler_so' : ["cc"],
- 'compiler_cxx' : ["cc"],
- 'linker_so' : ["cc", "-shared"],
- 'linker_exe' : ["cc"],
- 'archiver' : ["ar", "-cr"],
- 'ranlib' : None,
- }
+ executables = {
+ 'preprocessor': None,
+ 'compiler': ["cc"],
+ 'compiler_so': ["cc"],
+ 'compiler_cxx': ["cc"],
+ 'linker_so': ["cc", "-shared"],
+ 'linker_exe': ["cc"],
+ 'archiver': ["ar", "-cr"],
+ 'ranlib': None,
+ }
if sys.platform[:6] == "darwin":
executables['ranlib'] = ["ranlib"]
@@ -129,7 +128,7 @@ class UnixCCompiler(CCompiler):
# reasonable common default here, but it's not necessarily used on all
# Unices!
- src_extensions = [".c",".C",".cc",".cxx",".cpp",".m"]
+ src_extensions = [".c", ".C", ".cc", ".cxx", ".cpp", ".m"]
obj_extension = ".o"
static_lib_extension = ".a"
shared_lib_extension = ".so"
@@ -140,8 +139,15 @@ class UnixCCompiler(CCompiler):
if sys.platform == "cygwin":
exe_extension = ".exe"
- def preprocess(self, source, output_file=None, macros=None,
- include_dirs=None, extra_preargs=None, extra_postargs=None):
+ def preprocess(
+ self,
+ source,
+ output_file=None,
+ macros=None,
+ include_dirs=None,
+ extra_preargs=None,
+ extra_postargs=None,
+ ):
fixed_args = self._fix_compile_args(None, macros, include_dirs)
ignore, macros, include_dirs = fixed_args
pp_opts = gen_preprocess_options(macros, include_dirs)
@@ -167,26 +173,22 @@ class UnixCCompiler(CCompiler):
raise CompileError(msg)
def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
- compiler_so = compiler_fixup(
- self.compiler_so, cc_args + extra_postargs)
+ compiler_so = compiler_fixup(self.compiler_so, cc_args + extra_postargs)
try:
- self.spawn(compiler_so + cc_args + [src, '-o', obj] +
- extra_postargs)
+ self.spawn(compiler_so + cc_args + [src, '-o', obj] + extra_postargs)
except DistutilsExecError as msg:
raise CompileError(msg)
- def create_static_lib(self, objects, output_libname,
- output_dir=None, debug=0, target_lang=None):
+ def create_static_lib(
+ self, objects, output_libname, output_dir=None, debug=0, target_lang=None
+ ):
objects, output_dir = self._fix_object_args(objects, output_dir)
- output_filename = \
- self.library_filename(output_libname, output_dir=output_dir)
+ output_filename = self.library_filename(output_libname, output_dir=output_dir)
if self._need_link(objects, output_filename):
self.mkpath(os.path.dirname(output_filename))
- self.spawn(self.archiver +
- [output_filename] +
- objects + self.objects)
+ self.spawn(self.archiver + [output_filename] + objects + self.objects)
# Not many Unices required ranlib anymore -- SunOS 4.x is, I
# think the only major Unix that does. Maybe we need some
@@ -201,26 +203,34 @@ class UnixCCompiler(CCompiler):
else:
log.debug("skipping %s (up-to-date)", output_filename)
- def link(self, target_desc, objects,
- output_filename, output_dir=None, libraries=None,
- library_dirs=None, runtime_library_dirs=None,
- export_symbols=None, debug=0, extra_preargs=None,
- extra_postargs=None, build_temp=None, target_lang=None):
+ def link(
+ self,
+ target_desc,
+ objects,
+ output_filename,
+ output_dir=None,
+ libraries=None,
+ library_dirs=None,
+ runtime_library_dirs=None,
+ export_symbols=None,
+ debug=0,
+ extra_preargs=None,
+ extra_postargs=None,
+ build_temp=None,
+ target_lang=None,
+ ):
objects, output_dir = self._fix_object_args(objects, output_dir)
- fixed_args = self._fix_lib_args(libraries, library_dirs,
- runtime_library_dirs)
+ fixed_args = self._fix_lib_args(libraries, library_dirs, runtime_library_dirs)
libraries, library_dirs, runtime_library_dirs = fixed_args
- lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs,
- libraries)
+ lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, libraries)
if not isinstance(output_dir, (str, type(None))):
raise TypeError("'output_dir' must be a string or None")
if output_dir is not None:
output_filename = os.path.join(output_dir, output_filename)
if self._need_link(objects, output_filename):
- ld_args = (objects + self.objects +
- lib_opts + ['-o', output_filename])
+ ld_args = objects + self.objects + lib_opts + ['-o', output_filename]
if debug:
ld_args[:0] = ['-g']
if extra_preargs:
@@ -259,8 +269,10 @@ class UnixCCompiler(CCompiler):
def library_dir_option(self, dir):
return "-L" + dir
- def _is_gcc(self, compiler_name):
- return "gcc" in compiler_name or "g++" in compiler_name
+ def _is_gcc(self):
+ cc_var = sysconfig.get_config_var("CC")
+ compiler = os.path.basename(shlex.split(cc_var)[0])
+ return "gcc" in compiler or "g++" in compiler
def runtime_library_dir_option(self, dir):
# XXX Hackish, at the very least. See Python bug #445902:
@@ -276,20 +288,21 @@ class UnixCCompiler(CCompiler):
# this time, there's no way to determine this information from
# the configuration data stored in the Python installation, so
# we use this hack.
- compiler = os.path.basename(shlex.split(sysconfig.get_config_var("CC"))[0])
if sys.platform[:6] == "darwin":
from distutils.util import get_macosx_target_ver, split_version
+
macosx_target_ver = get_macosx_target_ver()
if macosx_target_ver and split_version(macosx_target_ver) >= [10, 5]:
return "-Wl,-rpath," + dir
- else: # no support for -rpath on earlier macOS versions
+ else: # no support for -rpath on earlier macOS versions
return "-L" + dir
elif sys.platform[:7] == "freebsd":
return "-Wl,-rpath=" + dir
elif sys.platform[:5] == "hp-ux":
- if self._is_gcc(compiler):
- return ["-Wl,+s", "-L" + dir]
- return ["+s", "-L" + dir]
+ return [
+ "-Wl,+s" if self._is_gcc() else "+s",
+ "-L" + dir,
+ ]
# For all compilers, `-Wl` is the presumed way to
# pass a compiler option to the linker and `-R` is
@@ -336,8 +349,6 @@ class UnixCCompiler(CCompiler):
else:
sysroot = m.group(1)
-
-
for dir in dirs:
shared = os.path.join(dir, shared_f)
dylib = os.path.join(dir, dylib_f)
@@ -345,8 +356,9 @@ class UnixCCompiler(CCompiler):
xcode_stub = os.path.join(dir, xcode_stub_f)
if sys.platform == 'darwin' and (
- dir.startswith('/System/') or (
- dir.startswith('/usr/') and not dir.startswith('/usr/local/'))):
+ dir.startswith('/System/')
+ or (dir.startswith('/usr/') and not dir.startswith('/usr/local/'))
+ ):
shared = os.path.join(sysroot, dir[1:], shared_f)
dylib = os.path.join(sysroot, dir[1:], dylib_f)
diff --git a/setuptools/_distutils/util.py b/setuptools/_distutils/util.py
index 6d506d7e..d59c362b 100644
--- a/setuptools/_distutils/util.py
+++ b/setuptools/_distutils/util.py
@@ -4,10 +4,11 @@ Miscellaneous utility functions -- anything that doesn't fit into
one of the other *util.py modules.
"""
+import importlib.util
import os
import re
-import importlib.util
import string
+import subprocess
import sys
import sysconfig
from distutils.errors import DistutilsPlatformError
@@ -15,19 +16,18 @@ from distutils.dep_util import newer
from distutils.spawn import spawn
from distutils import log
from distutils.errors import DistutilsByteCompileError
-from .py35compat import _optim_args_from_interpreter_flags
def get_host_platform():
- """Return a string that identifies the current platform. This is used mainly to
- distinguish platform-specific build directories and platform-specific built
- distributions.
+ """
+ Return a string that identifies the current platform. Use this
+ function to distinguish platform-specific build directories and
+ platform-specific built distributions.
"""
- # We initially exposed platforms as defined in Python 3.9
+ # This function initially exposed platforms as defined in Python 3.9
# even with older Python versions when distutils was split out.
- # Now that we delegate to stdlib sysconfig we need to restore this
- # in case anyone has started to depend on it.
+ # Now it delegates to stdlib sysconfig, but maintains compatibility.
if sys.version_info < (3, 8):
if os.name == 'nt':
@@ -41,43 +41,49 @@ def get_host_platform():
osname, host, release, version, machine = os.uname()
if osname[:3] == "aix":
from .py38compat import aix_platform
+
return aix_platform(osname, version, release)
return sysconfig.get_platform()
+
def get_platform():
if os.name == 'nt':
TARGET_TO_PLAT = {
- 'x86' : 'win32',
- 'x64' : 'win-amd64',
- 'arm' : 'win-arm32',
+ 'x86': 'win32',
+ 'x64': 'win-amd64',
+ 'arm': 'win-arm32',
'arm64': 'win-arm64',
}
- return TARGET_TO_PLAT.get(os.environ.get('VSCMD_ARG_TGT_ARCH')) or get_host_platform()
- else:
- return get_host_platform()
+ target = os.environ.get('VSCMD_ARG_TGT_ARCH')
+ return TARGET_TO_PLAT.get(target) or get_host_platform()
+ return get_host_platform()
if sys.platform == 'darwin':
- _syscfg_macosx_ver = None # cache the version pulled from sysconfig
+ _syscfg_macosx_ver = None # cache the version pulled from sysconfig
MACOSX_VERSION_VAR = 'MACOSX_DEPLOYMENT_TARGET'
+
def _clear_cached_macosx_ver():
"""For testing only. Do not call."""
global _syscfg_macosx_ver
_syscfg_macosx_ver = None
+
def get_macosx_target_ver_from_syscfg():
"""Get the version of macOS latched in the Python interpreter configuration.
Returns the version as a string or None if can't obtain one. Cached."""
global _syscfg_macosx_ver
if _syscfg_macosx_ver is None:
from distutils import sysconfig
+
ver = sysconfig.get_config_var(MACOSX_VERSION_VAR) or ''
if ver:
_syscfg_macosx_ver = ver
return _syscfg_macosx_ver
+
def get_macosx_target_ver():
"""Return the version of macOS for which we are building.
@@ -95,12 +101,16 @@ def get_macosx_target_ver():
# ensures extension modules are built with correct compatibility
# values, specifically LDSHARED which can use
# '-undefined dynamic_lookup' which only works on >= 10.3.
- if syscfg_ver and split_version(syscfg_ver) >= [10, 3] and \
- split_version(env_ver) < [10, 3]:
- my_msg = ('$' + MACOSX_VERSION_VAR + ' mismatch: '
- 'now "%s" but "%s" during configure; '
- 'must use 10.3 or later'
- % (env_ver, syscfg_ver))
+ if (
+ syscfg_ver
+ and split_version(syscfg_ver) >= [10, 3]
+ and split_version(env_ver) < [10, 3]
+ ):
+ my_msg = (
+ '$' + MACOSX_VERSION_VAR + ' mismatch: '
+ 'now "%s" but "%s" during configure; '
+ 'must use 10.3 or later' % (env_ver, syscfg_ver)
+ )
raise DistutilsPlatformError(my_msg)
return env_ver
return syscfg_ver
@@ -111,7 +121,7 @@ def split_version(s):
return [int(n) for n in s.split('.')]
-def convert_path (pathname):
+def convert_path(pathname):
"""Return 'pathname' as a name that will work on the native filesystem,
i.e. split it on '/' and put it back together again using the current
directory separator. Needed because filenames in the setup script are
@@ -136,10 +146,11 @@ def convert_path (pathname):
return os.curdir
return os.path.join(*paths)
+
# convert_path ()
-def change_root (new_root, pathname):
+def change_root(new_root, pathname):
"""Return 'pathname' with 'new_root' prepended. If 'pathname' is
relative, this is equivalent to "os.path.join(new_root,pathname)".
Otherwise, it requires making 'pathname' relative and then joining the
@@ -157,12 +168,13 @@ def change_root (new_root, pathname):
path = path[1:]
return os.path.join(new_root, path)
- else:
- raise DistutilsPlatformError("nothing known about platform '%s'" % os.name)
+ raise DistutilsPlatformError(f"nothing known about platform '{os.name}'")
_environ_checked = 0
-def check_environ ():
+
+
+def check_environ():
"""Ensure that 'os.environ' has all the environment variables we
guarantee that users can use in config files, command-line options,
etc. Currently this includes:
@@ -177,6 +189,7 @@ def check_environ ():
if os.name == 'posix' and 'HOME' not in os.environ:
try:
import pwd
+
os.environ['HOME'] = pwd.getpwuid(os.getuid())[5]
except (ImportError, KeyError):
# bpo-10496: if the current user identifier doesn't exist in the
@@ -189,7 +202,7 @@ def check_environ ():
_environ_checked = 1
-def subst_vars (s, local_vars):
+def subst_vars(s, local_vars):
"""
Perform variable substitution on 'string'.
Variables are indicated by format-style braces ("{var}").
@@ -207,19 +220,20 @@ def subst_vars (s, local_vars):
except KeyError as var:
raise ValueError(f"invalid variable {var}")
-# subst_vars ()
-
def _subst_compat(s):
"""
Replace shell/Perl-style variable substitution with
format-style. For compatibility.
"""
+
def _subst(match):
return f'{{{match.group(1)}}}'
+
repl = re.sub(r'\$([a-zA-Z_][a-zA-Z_0-9]*)', _subst, s)
if repl != s:
import warnings
+
warnings.warn(
"shell/Perl-style substitions are deprecated",
DeprecationWarning,
@@ -227,7 +241,7 @@ def _subst_compat(s):
return repl
-def grok_environment_error (exc, prefix="error: "):
+def grok_environment_error(exc, prefix="error: "):
# Function kept for backward compatibility.
# Used to try clever things with EnvironmentErrors,
# but nowadays str(exception) produces good messages.
@@ -236,13 +250,16 @@ def grok_environment_error (exc, prefix="error: "):
# Needed by 'split_quoted()'
_wordchars_re = _squote_re = _dquote_re = None
+
+
def _init_regex():
global _wordchars_re, _squote_re, _dquote_re
_wordchars_re = re.compile(r'[^\\\'\"%s ]*' % string.whitespace)
_squote_re = re.compile(r"'(?:[^'\\]|\\.)*'")
_dquote_re = re.compile(r'"(?:[^"\\]|\\.)*"')
-def split_quoted (s):
+
+def split_quoted(s):
"""Split a string up according to Unix shell-like rules for quotes and
backslashes. In short: words are delimited by spaces, as long as those
spaces are not escaped by a backslash, or inside a quoted string.
@@ -256,7 +273,8 @@ def split_quoted (s):
# This is a nice algorithm for splitting up a single string, since it
# doesn't require character-by-character examination. It was a little
# bit of a brain-bender to get it working right, though...
- if _wordchars_re is None: _init_regex()
+ if _wordchars_re is None:
+ _init_regex()
s = s.strip()
words = []
@@ -269,20 +287,23 @@ def split_quoted (s):
words.append(s[:end])
break
- if s[end] in string.whitespace: # unescaped, unquoted whitespace: now
- words.append(s[:end]) # we definitely have a word delimiter
+ if s[end] in string.whitespace:
+ # unescaped, unquoted whitespace: now
+ # we definitely have a word delimiter
+ words.append(s[:end])
s = s[end:].lstrip()
pos = 0
- elif s[end] == '\\': # preserve whatever is being escaped;
- # will become part of the current word
- s = s[:end] + s[end+1:]
- pos = end+1
+ elif s[end] == '\\':
+ # preserve whatever is being escaped;
+ # will become part of the current word
+ s = s[:end] + s[end + 1 :]
+ pos = end + 1
else:
- if s[end] == "'": # slurp singly-quoted string
+ if s[end] == "'": # slurp singly-quoted string
m = _squote_re.match(s, end)
- elif s[end] == '"': # slurp doubly-quoted string
+ elif s[end] == '"': # slurp doubly-quoted string
m = _dquote_re.match(s, end)
else:
raise RuntimeError("this can't happen (bad char '%c')" % s[end])
@@ -291,7 +312,7 @@ def split_quoted (s):
raise ValueError("bad string (mismatched %s quotes?)" % s[end])
(beg, end) = m.span()
- s = s[:beg] + s[beg+1:end-1] + s[end:]
+ s = s[:beg] + s[beg + 1 : end - 1] + s[end:]
pos = m.end() - 2
if pos >= len(s):
@@ -300,10 +321,11 @@ def split_quoted (s):
return words
+
# split_quoted ()
-def execute (func, args, msg=None, verbose=0, dry_run=0):
+def execute(func, args, msg=None, verbose=0, dry_run=0):
"""Perform some action that affects the outside world (eg. by
writing to the filesystem). Such actions are special because they
are disabled by the 'dry_run' flag. This method takes care of all
@@ -314,7 +336,7 @@ def execute (func, args, msg=None, verbose=0, dry_run=0):
"""
if msg is None:
msg = "%s%r" % (func.__name__, args)
- if msg[-2:] == ',)': # correct for singleton tuple
+ if msg[-2:] == ',)': # correct for singleton tuple
msg = msg[0:-2] + ')'
log.info(msg)
@@ -322,7 +344,7 @@ def execute (func, args, msg=None, verbose=0, dry_run=0):
func(*args)
-def strtobool (val):
+def strtobool(val):
"""Convert a string representation of truth to true (1) or false (0).
True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
@@ -338,11 +360,16 @@ def strtobool (val):
raise ValueError("invalid truth value %r" % (val,))
-def byte_compile (py_files,
- optimize=0, force=0,
- prefix=None, base_dir=None,
- verbose=1, dry_run=0,
- direct=None):
+def byte_compile(
+ py_files,
+ optimize=0,
+ force=0,
+ prefix=None,
+ base_dir=None,
+ verbose=1,
+ dry_run=0,
+ direct=None,
+):
"""Byte-compile a collection of Python source files to .pyc
files in a __pycache__ subdirectory. 'py_files' is a list
of files to compile; any files that don't end in ".py" are silently
@@ -372,10 +399,6 @@ def byte_compile (py_files,
it set to None.
"""
- # Late import to fix a bootstrap issue: _posixsubprocess is built by
- # setup.py, but setup.py uses distutils.
- import subprocess
-
# nothing is done if sys.dont_write_bytecode is True
if sys.dont_write_bytecode:
raise DistutilsByteCompileError('byte-compiling is disabled.')
@@ -391,16 +414,18 @@ def byte_compile (py_files,
# optimize mode, or if either optimization level was requested by
# the caller.
if direct is None:
- direct = (__debug__ and optimize == 0)
+ direct = __debug__ and optimize == 0
# "Indirect" byte-compilation: write a temporary script and then
# run it with the appropriate flags.
if not direct:
try:
from tempfile import mkstemp
+
(script_fd, script_name) = mkstemp(".py")
except ImportError:
from tempfile import mktemp
+
(script_fd, script_name) = None, mktemp(".py")
log.info("writing byte-compilation script '%s'", script_name)
if not dry_run:
@@ -410,10 +435,12 @@ def byte_compile (py_files,
script = open(script_name, "w")
with script:
- script.write("""\
+ script.write(
+ """\
from distutils.util import byte_compile
files = [
-""")
+"""
+ )
# XXX would be nice to write absolute filenames, just for
# safety's sake (script should be more robust in the face of
@@ -425,24 +452,22 @@ files = [
# problem is that it's really a directory, but I'm treating it
# as a dumb string, so trailing slashes and so forth matter.
- #py_files = map(os.path.abspath, py_files)
- #if prefix:
- # prefix = os.path.abspath(prefix)
-
script.write(",\n".join(map(repr, py_files)) + "]\n")
- script.write("""
+ script.write(
+ """
byte_compile(files, optimize=%r, force=%r,
prefix=%r, base_dir=%r,
verbose=%r, dry_run=0,
direct=1)
-""" % (optimize, force, prefix, base_dir, verbose))
+"""
+ % (optimize, force, prefix, base_dir, verbose)
+ )
cmd = [sys.executable]
- cmd.extend(_optim_args_from_interpreter_flags())
+ cmd.extend(subprocess._optim_args_from_interpreter_flags())
cmd.append(script_name)
spawn(cmd, dry_run=dry_run)
- execute(os.remove, (script_name,), "removing %s" % script_name,
- dry_run=dry_run)
+ execute(os.remove, (script_name,), "removing %s" % script_name, dry_run=dry_run)
# "Direct" byte-compilation: use the py_compile module to compile
# right here, right now. Note that the script generated in indirect
@@ -462,16 +487,17 @@ byte_compile(files, optimize=%r, force=%r,
# dfile - purported source filename (same as 'file' by default)
if optimize >= 0:
opt = '' if optimize == 0 else optimize
- cfile = importlib.util.cache_from_source(
- file, optimization=opt)
+ cfile = importlib.util.cache_from_source(file, optimization=opt)
else:
cfile = importlib.util.cache_from_source(file)
dfile = file
if prefix:
- if file[:len(prefix)] != prefix:
- raise ValueError("invalid prefix: filename %r doesn't start with %r"
- % (file, prefix))
- dfile = dfile[len(prefix):]
+ if file[: len(prefix)] != prefix:
+ raise ValueError(
+ "invalid prefix: filename %r doesn't start with %r"
+ % (file, prefix)
+ )
+ dfile = dfile[len(prefix) :]
if base_dir:
dfile = os.path.join(base_dir, dfile)
@@ -482,12 +508,10 @@ byte_compile(files, optimize=%r, force=%r,
if not dry_run:
compile(file, cfile, dfile)
else:
- log.debug("skipping byte-compilation of %s to %s",
- file, cfile_base)
+ log.debug("skipping byte-compilation of %s to %s", file, cfile_base)
-# byte_compile ()
-def rfc822_escape (header):
+def rfc822_escape(header):
"""Return a version of the string escaped for inclusion in an
RFC-822 header, by ensuring there are 8 spaces space after each newline.
"""
diff --git a/setuptools/_distutils/version.py b/setuptools/_distutils/version.py
index 31f504e4..a406a301 100644
--- a/setuptools/_distutils/version.py
+++ b/setuptools/_distutils/version.py
@@ -49,7 +49,7 @@ class Version:
rich comparisons to _cmp.
"""
- def __init__ (self, vstring=None):
+ def __init__(self, vstring=None):
if vstring:
self.parse(vstring)
warnings.warn(
@@ -59,7 +59,7 @@ class Version:
stacklevel=2,
)
- def __repr__ (self):
+ def __repr__(self):
return "%s ('%s')" % (self.__class__.__name__, str(self))
def __eq__(self, other):
@@ -110,7 +110,7 @@ class Version:
# instance of your version class)
-class StrictVersion (Version):
+class StrictVersion(Version):
"""Version numbering for anal retentives and software idealists.
Implements the standard interface for version number classes as
@@ -147,17 +147,16 @@ class StrictVersion (Version):
in the distutils documentation.
"""
- version_re = re.compile(r'^(\d+) \. (\d+) (\. (\d+))? ([ab](\d+))?$',
- re.VERBOSE | re.ASCII)
+ version_re = re.compile(
+ r'^(\d+) \. (\d+) (\. (\d+))? ([ab](\d+))?$', re.VERBOSE | re.ASCII
+ )
-
- def parse (self, vstring):
+ def parse(self, vstring):
match = self.version_re.match(vstring)
if not match:
raise ValueError("invalid version number '%s'" % vstring)
- (major, minor, patch, prerelease, prerelease_num) = \
- match.group(1, 2, 4, 5, 6)
+ (major, minor, patch, prerelease, prerelease_num) = match.group(1, 2, 4, 5, 6)
if patch:
self.version = tuple(map(int, [major, minor, patch]))
@@ -169,8 +168,7 @@ class StrictVersion (Version):
else:
self.prerelease = None
-
- def __str__ (self):
+ def __str__(self):
if self.version[2] == 0:
vstring = '.'.join(map(str, self.version[0:2]))
@@ -182,8 +180,7 @@ class StrictVersion (Version):
return vstring
-
- def _cmp (self, other):
+ def _cmp(self, other):
if isinstance(other, str):
with suppress_known_deprecation():
other = StrictVersion(other)
@@ -204,13 +201,13 @@ class StrictVersion (Version):
# case 3: self doesn't have prerelease, other does: self is greater
# case 4: both have prerelease: must compare them!
- if (not self.prerelease and not other.prerelease):
+ if not self.prerelease and not other.prerelease:
return 0
- elif (self.prerelease and not other.prerelease):
+ elif self.prerelease and not other.prerelease:
return -1
- elif (not self.prerelease and other.prerelease):
+ elif not self.prerelease and other.prerelease:
return 1
- elif (self.prerelease and other.prerelease):
+ elif self.prerelease and other.prerelease:
if self.prerelease == other.prerelease:
return 0
elif self.prerelease < other.prerelease:
@@ -220,6 +217,7 @@ class StrictVersion (Version):
else:
assert False, "never get here"
+
# end class StrictVersion
@@ -287,7 +285,8 @@ class StrictVersion (Version):
# the Right Thing" (ie. the code matches the conception). But I'd rather
# have a conception that matches common notions about version numbers.
-class LooseVersion (Version):
+
+class LooseVersion(Version):
"""Version numbering for anarchists and software realists.
Implements the standard interface for version number classes as
@@ -322,13 +321,12 @@ class LooseVersion (Version):
component_re = re.compile(r'(\d+ | [a-z]+ | \.)', re.VERBOSE)
- def parse (self, vstring):
+ def parse(self, vstring):
# I've given up on thinking I can reconstruct the version string
# from the parsed tuple -- so I just store the string here for
# use by __str__
self.vstring = vstring
- components = [x for x in self.component_re.split(vstring)
- if x and x != '.']
+ components = [x for x in self.component_re.split(vstring) if x and x != '.']
for i, obj in enumerate(components):
try:
components[i] = int(obj)
@@ -337,16 +335,13 @@ class LooseVersion (Version):
self.version = components
-
- def __str__ (self):
+ def __str__(self):
return self.vstring
-
- def __repr__ (self):
+ def __repr__(self):
return "LooseVersion ('%s')" % str(self)
-
- def _cmp (self, other):
+ def _cmp(self, other):
if isinstance(other, str):
other = LooseVersion(other)
elif not isinstance(other, LooseVersion):
diff --git a/setuptools/_distutils/versionpredicate.py b/setuptools/_distutils/versionpredicate.py
index 55f25d91..6ea1192d 100644
--- a/setuptools/_distutils/versionpredicate.py
+++ b/setuptools/_distutils/versionpredicate.py
@@ -5,11 +5,10 @@ import distutils.version
import operator
-re_validPackage = re.compile(r"(?i)^\s*([a-z_]\w*(?:\.[a-z_]\w*)*)(.*)",
- re.ASCII)
+re_validPackage = re.compile(r"(?i)^\s*([a-z_]\w*(?:\.[a-z_]\w*)*)(.*)", re.ASCII)
# (package) (rest)
-re_paren = re.compile(r"^\s*\((.*)\)\s*$") # (list) inside of parentheses
+re_paren = re.compile(r"^\s*\((.*)\)\s*$") # (list) inside of parentheses
re_splitComparison = re.compile(r"^\s*(<=|>=|<|>|!=|==)\s*([^\s,]+)\s*$")
# (comp) (version)
@@ -27,8 +26,16 @@ def splitUp(pred):
other = distutils.version.StrictVersion(verStr)
return (comp, other)
-compmap = {"<": operator.lt, "<=": operator.le, "==": operator.eq,
- ">": operator.gt, ">=": operator.ge, "!=": operator.ne}
+
+compmap = {
+ "<": operator.lt,
+ "<=": operator.le,
+ "==": operator.eq,
+ ">": operator.gt,
+ ">=": operator.ge,
+ "!=": operator.ne,
+}
+
class VersionPredicate:
"""Parse and test package version predicates.
@@ -96,8 +103,7 @@ class VersionPredicate:
"""
def __init__(self, versionPredicateStr):
- """Parse a version predicate string.
- """
+ """Parse a version predicate string."""
# Fields:
# name: package name
# pred: list of (comparison string, StrictVersion)
@@ -117,8 +123,7 @@ class VersionPredicate:
str = match.groups()[0]
self.pred = [splitUp(aPred) for aPred in str.split(",")]
if not self.pred:
- raise ValueError("empty parenthesized list in %r"
- % versionPredicateStr)
+ raise ValueError("empty parenthesized list in %r" % versionPredicateStr)
else:
self.pred = []
@@ -142,6 +147,7 @@ class VersionPredicate:
_provision_rx = None
+
def split_provision(value):
"""Return the name and optional version number of a provision.
@@ -156,8 +162,8 @@ def split_provision(value):
global _provision_rx
if _provision_rx is None:
_provision_rx = re.compile(
- r"([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*)(?:\s*\(\s*([^)\s]+)\s*\))?$",
- re.ASCII)
+ r"([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*)(?:\s*\(\s*([^)\s]+)\s*\))?$", re.ASCII
+ )
value = value.strip()
m = _provision_rx.match(value)
if not m:
diff --git a/setuptools/_importlib.py b/setuptools/_importlib.py
index c1ac137e..819bf5d3 100644
--- a/setuptools/_importlib.py
+++ b/setuptools/_importlib.py
@@ -12,6 +12,17 @@ def disable_importlib_metadata_finder(metadata):
import importlib_metadata
except ImportError:
return
+ except AttributeError:
+ import warnings
+
+ msg = (
+ "`importlib-metadata` version is incompatible with `setuptools`.\n"
+ "This problem is likely to be solved by installing an updated version of "
+ "`importlib-metadata`."
+ )
+ warnings.warn(msg) # Ensure a descriptive message is shown.
+ raise # This exception can be suppressed by _distutils_hack
+
if importlib_metadata is metadata:
return
to_remove = [
diff --git a/setuptools/_vendor/pyparsing-2.2.1.dist-info/DESCRIPTION.rst b/setuptools/_vendor/pyparsing-2.2.1.dist-info/DESCRIPTION.rst
deleted file mode 100644
index e1187231..00000000
--- a/setuptools/_vendor/pyparsing-2.2.1.dist-info/DESCRIPTION.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-UNKNOWN
-
-
diff --git a/setuptools/_vendor/pyparsing-2.2.1.dist-info/METADATA b/setuptools/_vendor/pyparsing-2.2.1.dist-info/METADATA
deleted file mode 100644
index a15c350e..00000000
--- a/setuptools/_vendor/pyparsing-2.2.1.dist-info/METADATA
+++ /dev/null
@@ -1,30 +0,0 @@
-Metadata-Version: 2.0
-Name: pyparsing
-Version: 2.2.1
-Summary: Python parsing module
-Home-page: https://github.com/pyparsing/pyparsing/
-Author: Paul McGuire
-Author-email: ptmcg@users.sourceforge.net
-License: MIT License
-Download-URL: https://pypi.org/project/pyparsing/
-Platform: UNKNOWN
-Classifier: Development Status :: 5 - Production/Stable
-Classifier: Intended Audience :: Developers
-Classifier: Intended Audience :: Information Technology
-Classifier: License :: OSI Approved :: MIT License
-Classifier: Operating System :: OS Independent
-Classifier: Programming Language :: Python
-Classifier: Programming Language :: Python :: 2
-Classifier: Programming Language :: Python :: 2.6
-Classifier: Programming Language :: Python :: 2.7
-Classifier: Programming Language :: Python :: 3
-Classifier: Programming Language :: Python :: 3.3
-Classifier: Programming Language :: Python :: 3.4
-Classifier: Programming Language :: Python :: 3.5
-Classifier: Programming Language :: Python :: 3.6
-Classifier: Programming Language :: Python :: 3.7
-Requires-Python: >=2.6, !=3.0.*, !=3.1.*, !=3.2.*
-
-UNKNOWN
-
-
diff --git a/setuptools/_vendor/pyparsing-2.2.1.dist-info/RECORD b/setuptools/_vendor/pyparsing-2.2.1.dist-info/RECORD
deleted file mode 100644
index 09cc30e3..00000000
--- a/setuptools/_vendor/pyparsing-2.2.1.dist-info/RECORD
+++ /dev/null
@@ -1,11 +0,0 @@
-__pycache__/pyparsing.cpython-310.pyc,,
-pyparsing-2.2.1.dist-info/DESCRIPTION.rst,sha256=OCTuuN6LcWulhHS3d5rfjdsQtW22n7HENFRh6jC6ego,10
-pyparsing-2.2.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
-pyparsing-2.2.1.dist-info/LICENSE.txt,sha256=081Pq74Spe1XdwrGkewNKSqa078kLIh7UWI-wVjdj8I,1041
-pyparsing-2.2.1.dist-info/METADATA,sha256=I0jhx9vpUYlQXjn4gVDnFFoAt3nNrxwR4iuqA_pknYs,1091
-pyparsing-2.2.1.dist-info/RECORD,,
-pyparsing-2.2.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-pyparsing-2.2.1.dist-info/WHEEL,sha256=kdsN-5OJAZIiHN-iO4Rhl82KyS0bDWf4uBwMbkNafr8,110
-pyparsing-2.2.1.dist-info/metadata.json,sha256=v1_77-dSdajUZSItSJg8Ov9M713STY3PzhyrRvs1ax4,1185
-pyparsing-2.2.1.dist-info/top_level.txt,sha256=eUOjGzJVhlQ3WS2rFAy2mN3LX_7FKTM5GSJ04jfnLmU,10
-pyparsing.py,sha256=tmrp-lu-qO1i75ZzIN5A12nKRRD1Cm4Vpk-5LR9rims,232055
diff --git a/setuptools/_vendor/pyparsing-2.2.1.dist-info/metadata.json b/setuptools/_vendor/pyparsing-2.2.1.dist-info/metadata.json
deleted file mode 100644
index b760b766..00000000
--- a/setuptools/_vendor/pyparsing-2.2.1.dist-info/metadata.json
+++ /dev/null
@@ -1 +0,0 @@
-{"classifiers": ["Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Intended Audience :: Information Technology", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7"], "download_url": "https://pypi.org/project/pyparsing/", "extensions": {"python.details": {"contacts": [{"email": "ptmcg@users.sourceforge.net", "name": "Paul McGuire", "role": "author"}], "document_names": {"description": "DESCRIPTION.rst", "license": "LICENSE.txt"}, "project_urls": {"Home": "https://github.com/pyparsing/pyparsing/"}}}, "generator": "bdist_wheel (0.30.0)", "license": "MIT License", "metadata_version": "2.0", "name": "pyparsing", "requires_python": ">=2.6, !=3.0.*, !=3.1.*, !=3.2.*", "summary": "Python parsing module", "version": "2.2.1"} \ No newline at end of file
diff --git a/setuptools/_vendor/pyparsing-2.2.1.dist-info/top_level.txt b/setuptools/_vendor/pyparsing-2.2.1.dist-info/top_level.txt
deleted file mode 100644
index 210dfec5..00000000
--- a/setuptools/_vendor/pyparsing-2.2.1.dist-info/top_level.txt
+++ /dev/null
@@ -1 +0,0 @@
-pyparsing
diff --git a/setuptools/_vendor/pyparsing-2.2.1.dist-info/INSTALLER b/setuptools/_vendor/pyparsing-3.0.8.dist-info/INSTALLER
index a1b589e3..a1b589e3 100644
--- a/setuptools/_vendor/pyparsing-2.2.1.dist-info/INSTALLER
+++ b/setuptools/_vendor/pyparsing-3.0.8.dist-info/INSTALLER
diff --git a/setuptools/_vendor/pyparsing-2.2.1.dist-info/LICENSE.txt b/setuptools/_vendor/pyparsing-3.0.8.dist-info/LICENSE
index bbc959e0..1bf98523 100644
--- a/setuptools/_vendor/pyparsing-2.2.1.dist-info/LICENSE.txt
+++ b/setuptools/_vendor/pyparsing-3.0.8.dist-info/LICENSE
@@ -1,18 +1,18 @@
-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.
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/setuptools/_vendor/pyparsing-3.0.8.dist-info/METADATA b/setuptools/_vendor/pyparsing-3.0.8.dist-info/METADATA
new file mode 100644
index 00000000..d6c8e9be
--- /dev/null
+++ b/setuptools/_vendor/pyparsing-3.0.8.dist-info/METADATA
@@ -0,0 +1,105 @@
+Metadata-Version: 2.1
+Name: pyparsing
+Version: 3.0.8
+Summary: pyparsing module - Classes and methods to define and execute parsing grammars
+Author-email: Paul McGuire <ptmcg.gm+pyparsing@gmail.com>
+Requires-Python: >=3.6.8
+Description-Content-Type: text/x-rst
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: Intended Audience :: Information Technology
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.6
+Classifier: Programming Language :: Python :: 3.7
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3 :: Only
+Classifier: Programming Language :: Python :: Implementation :: CPython
+Classifier: Programming Language :: Python :: Implementation :: PyPy
+Classifier: Typing :: Typed
+Requires-Dist: railroad-diagrams ; extra == "diagrams"
+Requires-Dist: jinja2 ; extra == "diagrams"
+Project-URL: Homepage, https://github.com/pyparsing/pyparsing/
+Provides-Extra: diagrams
+
+PyParsing -- A Python Parsing Module
+====================================
+
+|Build Status| |Coverage|
+
+Introduction
+============
+
+The pyparsing module is an alternative approach to creating and
+executing simple grammars, vs. the traditional lex/yacc approach, or the
+use of regular expressions. The pyparsing module provides a library of
+classes that client code uses to construct the grammar directly in
+Python code.
+
+*[Since first writing this description of pyparsing in late 2003, this
+technique for developing parsers has become more widespread, under the
+name Parsing Expression Grammars - PEGs. See more information on PEGs*
+`here <https://en.wikipedia.org/wiki/Parsing_expression_grammar>`__
+*.]*
+
+Here is a program to parse ``"Hello, World!"`` (or any greeting of the form
+``"salutation, addressee!"``):
+
+.. code:: python
+
+ from pyparsing import Word, alphas
+ greet = Word(alphas) + "," + Word(alphas) + "!"
+ hello = "Hello, World!"
+ print(hello, "->", greet.parseString(hello))
+
+The program outputs the following::
+
+ Hello, World! -> ['Hello', ',', 'World', '!']
+
+The Python representation of the grammar is quite readable, owing to the
+self-explanatory class names, and the use of '+', '|' and '^' operator
+definitions.
+
+The parsed results returned from ``parseString()`` is a collection of type
+``ParseResults``, which can be accessed as a
+nested list, a dictionary, or an object with named attributes.
+
+The pyparsing module handles some of the problems that are typically
+vexing when writing text parsers:
+
+- extra or missing whitespace (the above program will also handle ``"Hello,World!"``, ``"Hello , World !"``, etc.)
+- quoted strings
+- embedded comments
+
+The examples directory includes a simple SQL parser, simple CORBA IDL
+parser, a config file parser, a chemical formula parser, and a four-
+function algebraic notation parser, among many others.
+
+Documentation
+=============
+
+There are many examples in the online docstrings of the classes
+and methods in pyparsing. You can find them compiled into `online docs <https://pyparsing-docs.readthedocs.io/en/latest/>`__. Additional
+documentation resources and project info are listed in the online
+`GitHub wiki <https://github.com/pyparsing/pyparsing/wiki>`__. An
+entire directory of examples can be found `here <https://github.com/pyparsing/pyparsing/tree/master/examples>`__.
+
+License
+=======
+
+MIT License. See header of the `pyparsing.py <https://github.com/pyparsing/pyparsing/blob/master/pyparsing/__init__.py#L1-L23>`__ file.
+
+History
+=======
+
+See `CHANGES <https://github.com/pyparsing/pyparsing/blob/master/CHANGES>`__ file.
+
+.. |Build Status| image:: https://github.com/pyparsing/pyparsing/actions/workflows/ci.yml/badge.svg
+ :target: https://github.com/pyparsing/pyparsing/actions/workflows/ci.yml
+.. |Coverage| image:: https://codecov.io/gh/pyparsing/pyparsing/branch/master/graph/badge.svg
+ :target: https://codecov.io/gh/pyparsing/pyparsing
+
diff --git a/setuptools/_vendor/pyparsing-3.0.8.dist-info/RECORD b/setuptools/_vendor/pyparsing-3.0.8.dist-info/RECORD
new file mode 100644
index 00000000..72947b0b
--- /dev/null
+++ b/setuptools/_vendor/pyparsing-3.0.8.dist-info/RECORD
@@ -0,0 +1,30 @@
+pyparsing-3.0.8.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+pyparsing-3.0.8.dist-info/LICENSE,sha256=ENUSChaAWAT_2otojCIL-06POXQbVzIGBNRVowngGXI,1023
+pyparsing-3.0.8.dist-info/METADATA,sha256=dEvZBGz3Owm5LYEaqDeKb6e3ZgOrF48WaCI_PG1n5BE,4207
+pyparsing-3.0.8.dist-info/RECORD,,
+pyparsing-3.0.8.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pyparsing-3.0.8.dist-info/WHEEL,sha256=jPMR_Dzkc4X4icQtmz81lnNY_kAsfog7ry7qoRvYLXw,81
+pyparsing/__init__.py,sha256=EMa1HCuq9HJhEDR8fUThu2gD0nl6Cs8FFEWZZ0eRCM8,9159
+pyparsing/__pycache__/__init__.cpython-38.pyc,,
+pyparsing/__pycache__/actions.cpython-38.pyc,,
+pyparsing/__pycache__/common.cpython-38.pyc,,
+pyparsing/__pycache__/core.cpython-38.pyc,,
+pyparsing/__pycache__/exceptions.cpython-38.pyc,,
+pyparsing/__pycache__/helpers.cpython-38.pyc,,
+pyparsing/__pycache__/results.cpython-38.pyc,,
+pyparsing/__pycache__/testing.cpython-38.pyc,,
+pyparsing/__pycache__/unicode.cpython-38.pyc,,
+pyparsing/__pycache__/util.cpython-38.pyc,,
+pyparsing/actions.py,sha256=60v7mETOBzc01YPH_qQD5isavgcSJpAfIKpzgjM3vaU,6429
+pyparsing/common.py,sha256=lFL97ooIeR75CmW5hjURZqwDCTgruqltcTCZ-ulLO2Q,12936
+pyparsing/core.py,sha256=zBzGw5vcSd58pB1QkYpY6O_XCcHVKX_nH5xglRx_L-M,213278
+pyparsing/diagram/__init__.py,sha256=oU_UEh6O5voKSFjUdq462_mpmURLOfUIsmWvxi1qgTQ,23003
+pyparsing/diagram/__pycache__/__init__.cpython-38.pyc,,
+pyparsing/diagram/template.jinja2,sha256=SfQ8SLktSBqI5W1DGcUVH1vdflRD6x2sQBApxrcNg7s,589
+pyparsing/exceptions.py,sha256=H4D9gqMavqmAFSsdrU_J6bO-jA-T-A7yvtXWZpooIUA,9030
+pyparsing/helpers.py,sha256=EyjpgDOc3ivwRsU4VXxAWdgIs5gaqMDaLWcwRh5mqxc,39007
+pyparsing/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pyparsing/results.py,sha256=Hd6FAAh5sF8zGXpwsamdVqFUblIwyQf0FH0t7FCb1OY,25353
+pyparsing/testing.py,sha256=szs8AKZREZMhL0y0vsMfaTVAnpqPHetg6VKJBNmc4QY,13388
+pyparsing/unicode.py,sha256=IR-ioeGY29cZ49tG8Ts7ITPWWNP5G2DcZs58oa8zn44,10381
+pyparsing/util.py,sha256=kq772O5YSeXOSdP-M31EWpbH_ayj7BMHImBYo9xPD5M,6805
diff --git a/setuptools/_vendor/pyparsing-2.2.1.dist-info/REQUESTED b/setuptools/_vendor/pyparsing-3.0.8.dist-info/REQUESTED
index e69de29b..e69de29b 100644
--- a/setuptools/_vendor/pyparsing-2.2.1.dist-info/REQUESTED
+++ b/setuptools/_vendor/pyparsing-3.0.8.dist-info/REQUESTED
diff --git a/setuptools/_vendor/pyparsing-2.2.1.dist-info/WHEEL b/setuptools/_vendor/pyparsing-3.0.8.dist-info/WHEEL
index 7332a419..c727d148 100644
--- a/setuptools/_vendor/pyparsing-2.2.1.dist-info/WHEEL
+++ b/setuptools/_vendor/pyparsing-3.0.8.dist-info/WHEEL
@@ -1,6 +1,4 @@
Wheel-Version: 1.0
-Generator: bdist_wheel (0.30.0)
+Generator: flit 3.6.0
Root-Is-Purelib: true
-Tag: py2-none-any
Tag: py3-none-any
-
diff --git a/setuptools/_vendor/pyparsing.py b/setuptools/_vendor/pyparsing.py
deleted file mode 100644
index cf75e1e5..00000000
--- a/setuptools/_vendor/pyparsing.py
+++ /dev/null
@@ -1,5742 +0,0 @@
-# module pyparsing.py
-#
-# Copyright (c) 2003-2018 Paul T. McGuire
-#
-# 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.
-#
-
-__doc__ = \
-"""
-pyparsing module - Classes and methods to define and execute parsing grammars
-=============================================================================
-
-The pyparsing module is an alternative approach to creating and executing simple grammars,
-vs. the traditional lex/yacc approach, or the use of regular expressions. With pyparsing, you
-don't need to learn a new syntax for defining grammars or matching expressions - the parsing module
-provides a library of classes that you use to construct the grammar directly in Python.
-
-Here is a program to parse "Hello, World!" (or any greeting of the form
-C{"<salutation>, <addressee>!"}), built up using L{Word}, L{Literal}, and L{And} elements
-(L{'+'<ParserElement.__add__>} operator gives L{And} expressions, strings are auto-converted to
-L{Literal} expressions)::
-
- from pyparsing import Word, alphas
-
- # define grammar of a greeting
- greet = Word(alphas) + "," + Word(alphas) + "!"
-
- hello = "Hello, World!"
- print (hello, "->", greet.parseString(hello))
-
-The program outputs the following::
-
- Hello, World! -> ['Hello', ',', 'World', '!']
-
-The Python representation of the grammar is quite readable, owing to the self-explanatory
-class names, and the use of '+', '|' and '^' operators.
-
-The L{ParseResults} object returned from L{ParserElement.parseString<ParserElement.parseString>} can be accessed as a nested list, a dictionary, or an
-object with named attributes.
-
-The pyparsing module handles some of the problems that are typically vexing when writing text parsers:
- - extra or missing whitespace (the above program will also handle "Hello,World!", "Hello , World !", etc.)
- - quoted strings
- - embedded comments
-
-
-Getting Started -
------------------
-Visit the classes L{ParserElement} and L{ParseResults} to see the base classes that most other pyparsing
-classes inherit from. Use the docstrings for examples of how to:
- - construct literal match expressions from L{Literal} and L{CaselessLiteral} classes
- - construct character word-group expressions using the L{Word} class
- - see how to create repetitive expressions using L{ZeroOrMore} and L{OneOrMore} classes
- - use L{'+'<And>}, L{'|'<MatchFirst>}, L{'^'<Or>}, and L{'&'<Each>} operators to combine simple expressions into more complex ones
- - associate names with your parsed results using L{ParserElement.setResultsName}
- - find some helpful expression short-cuts like L{delimitedList} and L{oneOf}
- - find more useful common expressions in the L{pyparsing_common} namespace class
-"""
-
-__version__ = "2.2.1"
-__versionTime__ = "18 Sep 2018 00:49 UTC"
-__author__ = "Paul McGuire <ptmcg@users.sourceforge.net>"
-
-import string
-from weakref import ref as wkref
-import copy
-import sys
-import warnings
-import re
-import sre_constants
-import collections
-import pprint
-import traceback
-import types
-from datetime import datetime
-
-try:
- from _thread import RLock
-except ImportError:
- from threading import RLock
-
-try:
- # Python 3
- from collections.abc import Iterable
- from collections.abc import MutableMapping
-except ImportError:
- # Python 2.7
- from collections import Iterable
- from collections import MutableMapping
-
-try:
- from collections import OrderedDict as _OrderedDict
-except ImportError:
- try:
- from ordereddict import OrderedDict as _OrderedDict
- except ImportError:
- _OrderedDict = None
-
-#~ sys.stderr.write( "testing pyparsing module, version %s, %s\n" % (__version__,__versionTime__ ) )
-
-__all__ = [
-'And', 'CaselessKeyword', 'CaselessLiteral', 'CharsNotIn', 'Combine', 'Dict', 'Each', 'Empty',
-'FollowedBy', 'Forward', 'GoToColumn', 'Group', 'Keyword', 'LineEnd', 'LineStart', 'Literal',
-'MatchFirst', 'NoMatch', 'NotAny', 'OneOrMore', 'OnlyOnce', 'Optional', 'Or',
-'ParseBaseException', 'ParseElementEnhance', 'ParseException', 'ParseExpression', 'ParseFatalException',
-'ParseResults', 'ParseSyntaxException', 'ParserElement', 'QuotedString', 'RecursiveGrammarException',
-'Regex', 'SkipTo', 'StringEnd', 'StringStart', 'Suppress', 'Token', 'TokenConverter',
-'White', 'Word', 'WordEnd', 'WordStart', 'ZeroOrMore',
-'alphanums', 'alphas', 'alphas8bit', 'anyCloseTag', 'anyOpenTag', 'cStyleComment', 'col',
-'commaSeparatedList', 'commonHTMLEntity', 'countedArray', 'cppStyleComment', 'dblQuotedString',
-'dblSlashComment', 'delimitedList', 'dictOf', 'downcaseTokens', 'empty', 'hexnums',
-'htmlComment', 'javaStyleComment', 'line', 'lineEnd', 'lineStart', 'lineno',
-'makeHTMLTags', 'makeXMLTags', 'matchOnlyAtCol', 'matchPreviousExpr', 'matchPreviousLiteral',
-'nestedExpr', 'nullDebugAction', 'nums', 'oneOf', 'opAssoc', 'operatorPrecedence', 'printables',
-'punc8bit', 'pythonStyleComment', 'quotedString', 'removeQuotes', 'replaceHTMLEntity',
-'replaceWith', 'restOfLine', 'sglQuotedString', 'srange', 'stringEnd',
-'stringStart', 'traceParseAction', 'unicodeString', 'upcaseTokens', 'withAttribute',
-'indentedBlock', 'originalTextFor', 'ungroup', 'infixNotation','locatedExpr', 'withClass',
-'CloseMatch', 'tokenMap', 'pyparsing_common',
-]
-
-system_version = tuple(sys.version_info)[:3]
-PY_3 = system_version[0] == 3
-if PY_3:
- _MAX_INT = sys.maxsize
- basestring = str
- unichr = chr
- _ustr = str
-
- # build list of single arg builtins, that can be used as parse actions
- singleArgBuiltins = [sum, len, sorted, reversed, list, tuple, set, any, all, min, max]
-
-else:
- _MAX_INT = sys.maxint
- range = xrange
-
- def _ustr(obj):
- """Drop-in replacement for str(obj) that tries to be Unicode friendly. It first tries
- str(obj). If that fails with a UnicodeEncodeError, then it tries unicode(obj). It
- then < returns the unicode object | encodes it with the default encoding | ... >.
- """
- if isinstance(obj,unicode):
- return obj
-
- try:
- # If this works, then _ustr(obj) has the same behaviour as str(obj), so
- # it won't break any existing code.
- return str(obj)
-
- except UnicodeEncodeError:
- # Else encode it
- ret = unicode(obj).encode(sys.getdefaultencoding(), 'xmlcharrefreplace')
- xmlcharref = Regex(r'&#\d+;')
- xmlcharref.setParseAction(lambda t: '\\u' + hex(int(t[0][2:-1]))[2:])
- return xmlcharref.transformString(ret)
-
- # build list of single arg builtins, tolerant of Python version, that can be used as parse actions
- singleArgBuiltins = []
- import __builtin__
- for fname in "sum len sorted reversed list tuple set any all min max".split():
- try:
- singleArgBuiltins.append(getattr(__builtin__,fname))
- except AttributeError:
- continue
-
-_generatorType = type((y for y in range(1)))
-
-def _xml_escape(data):
- """Escape &, <, >, ", ', etc. in a string of data."""
-
- # ampersand must be replaced first
- from_symbols = '&><"\''
- to_symbols = ('&'+s+';' for s in "amp gt lt quot apos".split())
- for from_,to_ in zip(from_symbols, to_symbols):
- data = data.replace(from_, to_)
- return data
-
-class _Constants(object):
- pass
-
-alphas = string.ascii_uppercase + string.ascii_lowercase
-nums = "0123456789"
-hexnums = nums + "ABCDEFabcdef"
-alphanums = alphas + nums
-_bslash = chr(92)
-printables = "".join(c for c in string.printable if c not in string.whitespace)
-
-class ParseBaseException(Exception):
- """base exception class for all parsing runtime exceptions"""
- # Performance tuning: we construct a *lot* of these, so keep this
- # constructor as small and fast as possible
- def __init__( self, pstr, loc=0, msg=None, elem=None ):
- self.loc = loc
- if msg is None:
- self.msg = pstr
- self.pstr = ""
- else:
- self.msg = msg
- self.pstr = pstr
- self.parserElement = elem
- self.args = (pstr, loc, msg)
-
- @classmethod
- def _from_exception(cls, pe):
- """
- internal factory method to simplify creating one type of ParseException
- from another - avoids having __init__ signature conflicts among subclasses
- """
- return cls(pe.pstr, pe.loc, pe.msg, pe.parserElement)
-
- def __getattr__( self, aname ):
- """supported attributes by name are:
- - lineno - returns the line number of the exception text
- - col - returns the column number of the exception text
- - line - returns the line containing the exception text
- """
- if( aname == "lineno" ):
- return lineno( self.loc, self.pstr )
- elif( aname in ("col", "column") ):
- return col( self.loc, self.pstr )
- elif( aname == "line" ):
- return line( self.loc, self.pstr )
- else:
- raise AttributeError(aname)
-
- def __str__( self ):
- return "%s (at char %d), (line:%d, col:%d)" % \
- ( self.msg, self.loc, self.lineno, self.column )
- def __repr__( self ):
- return _ustr(self)
- def markInputline( self, markerString = ">!<" ):
- """Extracts the exception line from the input string, and marks
- the location of the exception with a special symbol.
- """
- line_str = self.line
- line_column = self.column - 1
- if markerString:
- line_str = "".join((line_str[:line_column],
- markerString, line_str[line_column:]))
- return line_str.strip()
- def __dir__(self):
- return "lineno col line".split() + dir(type(self))
-
-class ParseException(ParseBaseException):
- """
- Exception thrown when parse expressions don't match class;
- supported attributes by name are:
- - lineno - returns the line number of the exception text
- - col - returns the column number of the exception text
- - line - returns the line containing the exception text
-
- Example::
- try:
- Word(nums).setName("integer").parseString("ABC")
- except ParseException as pe:
- print(pe)
- print("column: {}".format(pe.col))
-
- prints::
- Expected integer (at char 0), (line:1, col:1)
- column: 1
- """
- pass
-
-class ParseFatalException(ParseBaseException):
- """user-throwable exception thrown when inconsistent parse content
- is found; stops all parsing immediately"""
- pass
-
-class ParseSyntaxException(ParseFatalException):
- """just like L{ParseFatalException}, but thrown internally when an
- L{ErrorStop<And._ErrorStop>} ('-' operator) indicates that parsing is to stop
- immediately because an unbacktrackable syntax error has been found"""
- pass
-
-#~ class ReparseException(ParseBaseException):
- #~ """Experimental class - parse actions can raise this exception to cause
- #~ pyparsing to reparse the input string:
- #~ - with a modified input string, and/or
- #~ - with a modified start location
- #~ Set the values of the ReparseException in the constructor, and raise the
- #~ exception in a parse action to cause pyparsing to use the new string/location.
- #~ Setting the values as None causes no change to be made.
- #~ """
- #~ def __init_( self, newstring, restartLoc ):
- #~ self.newParseText = newstring
- #~ self.reparseLoc = restartLoc
-
-class RecursiveGrammarException(Exception):
- """exception thrown by L{ParserElement.validate} if the grammar could be improperly recursive"""
- def __init__( self, parseElementList ):
- self.parseElementTrace = parseElementList
-
- def __str__( self ):
- return "RecursiveGrammarException: %s" % self.parseElementTrace
-
-class _ParseResultsWithOffset(object):
- def __init__(self,p1,p2):
- self.tup = (p1,p2)
- def __getitem__(self,i):
- return self.tup[i]
- def __repr__(self):
- return repr(self.tup[0])
- def setOffset(self,i):
- self.tup = (self.tup[0],i)
-
-class ParseResults(object):
- """
- Structured parse results, to provide multiple means of access to the parsed data:
- - as a list (C{len(results)})
- - by list index (C{results[0], results[1]}, etc.)
- - by attribute (C{results.<resultsName>} - see L{ParserElement.setResultsName})
-
- Example::
- integer = Word(nums)
- date_str = (integer.setResultsName("year") + '/'
- + integer.setResultsName("month") + '/'
- + integer.setResultsName("day"))
- # equivalent form:
- # date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
-
- # parseString returns a ParseResults object
- result = date_str.parseString("1999/12/31")
-
- def test(s, fn=repr):
- print("%s -> %s" % (s, fn(eval(s))))
- test("list(result)")
- test("result[0]")
- test("result['month']")
- test("result.day")
- test("'month' in result")
- test("'minutes' in result")
- test("result.dump()", str)
- prints::
- list(result) -> ['1999', '/', '12', '/', '31']
- result[0] -> '1999'
- result['month'] -> '12'
- result.day -> '31'
- 'month' in result -> True
- 'minutes' in result -> False
- result.dump() -> ['1999', '/', '12', '/', '31']
- - day: 31
- - month: 12
- - year: 1999
- """
- def __new__(cls, toklist=None, name=None, asList=True, modal=True ):
- if isinstance(toklist, cls):
- return toklist
- retobj = object.__new__(cls)
- retobj.__doinit = True
- return retobj
-
- # Performance tuning: we construct a *lot* of these, so keep this
- # constructor as small and fast as possible
- def __init__( self, toklist=None, name=None, asList=True, modal=True, isinstance=isinstance ):
- if self.__doinit:
- self.__doinit = False
- self.__name = None
- self.__parent = None
- self.__accumNames = {}
- self.__asList = asList
- self.__modal = modal
- if toklist is None:
- toklist = []
- if isinstance(toklist, list):
- self.__toklist = toklist[:]
- elif isinstance(toklist, _generatorType):
- self.__toklist = list(toklist)
- else:
- self.__toklist = [toklist]
- self.__tokdict = dict()
-
- if name is not None and name:
- if not modal:
- self.__accumNames[name] = 0
- if isinstance(name,int):
- name = _ustr(name) # will always return a str, but use _ustr for consistency
- self.__name = name
- if not (isinstance(toklist, (type(None), basestring, list)) and toklist in (None,'',[])):
- if isinstance(toklist,basestring):
- toklist = [ toklist ]
- if asList:
- if isinstance(toklist,ParseResults):
- self[name] = _ParseResultsWithOffset(toklist.copy(),0)
- else:
- self[name] = _ParseResultsWithOffset(ParseResults(toklist[0]),0)
- self[name].__name = name
- else:
- try:
- self[name] = toklist[0]
- except (KeyError,TypeError,IndexError):
- self[name] = toklist
-
- def __getitem__( self, i ):
- if isinstance( i, (int,slice) ):
- return self.__toklist[i]
- else:
- if i not in self.__accumNames:
- return self.__tokdict[i][-1][0]
- else:
- return ParseResults([ v[0] for v in self.__tokdict[i] ])
-
- def __setitem__( self, k, v, isinstance=isinstance ):
- if isinstance(v,_ParseResultsWithOffset):
- self.__tokdict[k] = self.__tokdict.get(k,list()) + [v]
- sub = v[0]
- elif isinstance(k,(int,slice)):
- self.__toklist[k] = v
- sub = v
- else:
- self.__tokdict[k] = self.__tokdict.get(k,list()) + [_ParseResultsWithOffset(v,0)]
- sub = v
- if isinstance(sub,ParseResults):
- sub.__parent = wkref(self)
-
- def __delitem__( self, i ):
- if isinstance(i,(int,slice)):
- mylen = len( self.__toklist )
- del self.__toklist[i]
-
- # convert int to slice
- if isinstance(i, int):
- if i < 0:
- i += mylen
- i = slice(i, i+1)
- # get removed indices
- removed = list(range(*i.indices(mylen)))
- removed.reverse()
- # fixup indices in token dictionary
- for name,occurrences in self.__tokdict.items():
- for j in removed:
- for k, (value, position) in enumerate(occurrences):
- occurrences[k] = _ParseResultsWithOffset(value, position - (position > j))
- else:
- del self.__tokdict[i]
-
- def __contains__( self, k ):
- return k in self.__tokdict
-
- def __len__( self ): return len( self.__toklist )
- def __bool__(self): return ( not not self.__toklist )
- __nonzero__ = __bool__
- def __iter__( self ): return iter( self.__toklist )
- def __reversed__( self ): return iter( self.__toklist[::-1] )
- def _iterkeys( self ):
- if hasattr(self.__tokdict, "iterkeys"):
- return self.__tokdict.iterkeys()
- else:
- return iter(self.__tokdict)
-
- def _itervalues( self ):
- return (self[k] for k in self._iterkeys())
-
- def _iteritems( self ):
- return ((k, self[k]) for k in self._iterkeys())
-
- if PY_3:
- keys = _iterkeys
- """Returns an iterator of all named result keys (Python 3.x only)."""
-
- values = _itervalues
- """Returns an iterator of all named result values (Python 3.x only)."""
-
- items = _iteritems
- """Returns an iterator of all named result key-value tuples (Python 3.x only)."""
-
- else:
- iterkeys = _iterkeys
- """Returns an iterator of all named result keys (Python 2.x only)."""
-
- itervalues = _itervalues
- """Returns an iterator of all named result values (Python 2.x only)."""
-
- iteritems = _iteritems
- """Returns an iterator of all named result key-value tuples (Python 2.x only)."""
-
- def keys( self ):
- """Returns all named result keys (as a list in Python 2.x, as an iterator in Python 3.x)."""
- return list(self.iterkeys())
-
- def values( self ):
- """Returns all named result values (as a list in Python 2.x, as an iterator in Python 3.x)."""
- return list(self.itervalues())
-
- def items( self ):
- """Returns all named result key-values (as a list of tuples in Python 2.x, as an iterator in Python 3.x)."""
- return list(self.iteritems())
-
- def haskeys( self ):
- """Since keys() returns an iterator, this method is helpful in bypassing
- code that looks for the existence of any defined results names."""
- return bool(self.__tokdict)
-
- def pop( self, *args, **kwargs):
- """
- Removes and returns item at specified index (default=C{last}).
- Supports both C{list} and C{dict} semantics for C{pop()}. If passed no
- argument or an integer argument, it will use C{list} semantics
- and pop tokens from the list of parsed tokens. If passed a
- non-integer argument (most likely a string), it will use C{dict}
- semantics and pop the corresponding value from any defined
- results names. A second default return value argument is
- supported, just as in C{dict.pop()}.
-
- Example::
- def remove_first(tokens):
- tokens.pop(0)
- print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321']
- print(OneOrMore(Word(nums)).addParseAction(remove_first).parseString("0 123 321")) # -> ['123', '321']
-
- label = Word(alphas)
- patt = label("LABEL") + OneOrMore(Word(nums))
- print(patt.parseString("AAB 123 321").dump())
-
- # Use pop() in a parse action to remove named result (note that corresponding value is not
- # removed from list form of results)
- def remove_LABEL(tokens):
- tokens.pop("LABEL")
- return tokens
- patt.addParseAction(remove_LABEL)
- print(patt.parseString("AAB 123 321").dump())
- prints::
- ['AAB', '123', '321']
- - LABEL: AAB
-
- ['AAB', '123', '321']
- """
- if not args:
- args = [-1]
- for k,v in kwargs.items():
- if k == 'default':
- args = (args[0], v)
- else:
- raise TypeError("pop() got an unexpected keyword argument '%s'" % k)
- if (isinstance(args[0], int) or
- len(args) == 1 or
- args[0] in self):
- index = args[0]
- ret = self[index]
- del self[index]
- return ret
- else:
- defaultvalue = args[1]
- return defaultvalue
-
- def get(self, key, defaultValue=None):
- """
- Returns named result matching the given key, or if there is no
- such name, then returns the given C{defaultValue} or C{None} if no
- C{defaultValue} is specified.
-
- Similar to C{dict.get()}.
-
- Example::
- integer = Word(nums)
- date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
-
- result = date_str.parseString("1999/12/31")
- print(result.get("year")) # -> '1999'
- print(result.get("hour", "not specified")) # -> 'not specified'
- print(result.get("hour")) # -> None
- """
- if key in self:
- return self[key]
- else:
- return defaultValue
-
- def insert( self, index, insStr ):
- """
- Inserts new element at location index in the list of parsed tokens.
-
- Similar to C{list.insert()}.
-
- Example::
- print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321']
-
- # use a parse action to insert the parse location in the front of the parsed results
- def insert_locn(locn, tokens):
- tokens.insert(0, locn)
- print(OneOrMore(Word(nums)).addParseAction(insert_locn).parseString("0 123 321")) # -> [0, '0', '123', '321']
- """
- self.__toklist.insert(index, insStr)
- # fixup indices in token dictionary
- for name,occurrences in self.__tokdict.items():
- for k, (value, position) in enumerate(occurrences):
- occurrences[k] = _ParseResultsWithOffset(value, position + (position > index))
-
- def append( self, item ):
- """
- Add single element to end of ParseResults list of elements.
-
- Example::
- print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321']
-
- # use a parse action to compute the sum of the parsed integers, and add it to the end
- def append_sum(tokens):
- tokens.append(sum(map(int, tokens)))
- print(OneOrMore(Word(nums)).addParseAction(append_sum).parseString("0 123 321")) # -> ['0', '123', '321', 444]
- """
- self.__toklist.append(item)
-
- def extend( self, itemseq ):
- """
- Add sequence of elements to end of ParseResults list of elements.
-
- Example::
- patt = OneOrMore(Word(alphas))
-
- # use a parse action to append the reverse of the matched strings, to make a palindrome
- def make_palindrome(tokens):
- tokens.extend(reversed([t[::-1] for t in tokens]))
- return ''.join(tokens)
- print(patt.addParseAction(make_palindrome).parseString("lskdj sdlkjf lksd")) # -> 'lskdjsdlkjflksddsklfjkldsjdksl'
- """
- if isinstance(itemseq, ParseResults):
- self += itemseq
- else:
- self.__toklist.extend(itemseq)
-
- def clear( self ):
- """
- Clear all elements and results names.
- """
- del self.__toklist[:]
- self.__tokdict.clear()
-
- def __getattr__( self, name ):
- try:
- return self[name]
- except KeyError:
- return ""
-
- if name in self.__tokdict:
- if name not in self.__accumNames:
- return self.__tokdict[name][-1][0]
- else:
- return ParseResults([ v[0] for v in self.__tokdict[name] ])
- else:
- return ""
-
- def __add__( self, other ):
- ret = self.copy()
- ret += other
- return ret
-
- def __iadd__( self, other ):
- if other.__tokdict:
- offset = len(self.__toklist)
- addoffset = lambda a: offset if a<0 else a+offset
- otheritems = other.__tokdict.items()
- otherdictitems = [(k, _ParseResultsWithOffset(v[0],addoffset(v[1])) )
- for (k,vlist) in otheritems for v in vlist]
- for k,v in otherdictitems:
- self[k] = v
- if isinstance(v[0],ParseResults):
- v[0].__parent = wkref(self)
-
- self.__toklist += other.__toklist
- self.__accumNames.update( other.__accumNames )
- return self
-
- def __radd__(self, other):
- if isinstance(other,int) and other == 0:
- # useful for merging many ParseResults using sum() builtin
- return self.copy()
- else:
- # this may raise a TypeError - so be it
- return other + self
-
- def __repr__( self ):
- return "(%s, %s)" % ( repr( self.__toklist ), repr( self.__tokdict ) )
-
- def __str__( self ):
- return '[' + ', '.join(_ustr(i) if isinstance(i, ParseResults) else repr(i) for i in self.__toklist) + ']'
-
- def _asStringList( self, sep='' ):
- out = []
- for item in self.__toklist:
- if out and sep:
- out.append(sep)
- if isinstance( item, ParseResults ):
- out += item._asStringList()
- else:
- out.append( _ustr(item) )
- return out
-
- def asList( self ):
- """
- Returns the parse results as a nested list of matching tokens, all converted to strings.
-
- Example::
- patt = OneOrMore(Word(alphas))
- result = patt.parseString("sldkj lsdkj sldkj")
- # even though the result prints in string-like form, it is actually a pyparsing ParseResults
- print(type(result), result) # -> <class 'pyparsing.ParseResults'> ['sldkj', 'lsdkj', 'sldkj']
-
- # Use asList() to create an actual list
- result_list = result.asList()
- print(type(result_list), result_list) # -> <class 'list'> ['sldkj', 'lsdkj', 'sldkj']
- """
- return [res.asList() if isinstance(res,ParseResults) else res for res in self.__toklist]
-
- def asDict( self ):
- """
- Returns the named parse results as a nested dictionary.
-
- Example::
- integer = Word(nums)
- date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
-
- result = date_str.parseString('12/31/1999')
- print(type(result), repr(result)) # -> <class 'pyparsing.ParseResults'> (['12', '/', '31', '/', '1999'], {'day': [('1999', 4)], 'year': [('12', 0)], 'month': [('31', 2)]})
-
- result_dict = result.asDict()
- print(type(result_dict), repr(result_dict)) # -> <class 'dict'> {'day': '1999', 'year': '12', 'month': '31'}
-
- # even though a ParseResults supports dict-like access, sometime you just need to have a dict
- import json
- print(json.dumps(result)) # -> Exception: TypeError: ... is not JSON serializable
- print(json.dumps(result.asDict())) # -> {"month": "31", "day": "1999", "year": "12"}
- """
- if PY_3:
- item_fn = self.items
- else:
- item_fn = self.iteritems
-
- def toItem(obj):
- if isinstance(obj, ParseResults):
- if obj.haskeys():
- return obj.asDict()
- else:
- return [toItem(v) for v in obj]
- else:
- return obj
-
- return dict((k,toItem(v)) for k,v in item_fn())
-
- def copy( self ):
- """
- Returns a new copy of a C{ParseResults} object.
- """
- ret = ParseResults( self.__toklist )
- ret.__tokdict = self.__tokdict.copy()
- ret.__parent = self.__parent
- ret.__accumNames.update( self.__accumNames )
- ret.__name = self.__name
- return ret
-
- def asXML( self, doctag=None, namedItemsOnly=False, indent="", formatted=True ):
- """
- (Deprecated) Returns the parse results as XML. Tags are created for tokens and lists that have defined results names.
- """
- nl = "\n"
- out = []
- namedItems = dict((v[1],k) for (k,vlist) in self.__tokdict.items()
- for v in vlist)
- nextLevelIndent = indent + " "
-
- # collapse out indents if formatting is not desired
- if not formatted:
- indent = ""
- nextLevelIndent = ""
- nl = ""
-
- selfTag = None
- if doctag is not None:
- selfTag = doctag
- else:
- if self.__name:
- selfTag = self.__name
-
- if not selfTag:
- if namedItemsOnly:
- return ""
- else:
- selfTag = "ITEM"
-
- out += [ nl, indent, "<", selfTag, ">" ]
-
- for i,res in enumerate(self.__toklist):
- if isinstance(res,ParseResults):
- if i in namedItems:
- out += [ res.asXML(namedItems[i],
- namedItemsOnly and doctag is None,
- nextLevelIndent,
- formatted)]
- else:
- out += [ res.asXML(None,
- namedItemsOnly and doctag is None,
- nextLevelIndent,
- formatted)]
- else:
- # individual token, see if there is a name for it
- resTag = None
- if i in namedItems:
- resTag = namedItems[i]
- if not resTag:
- if namedItemsOnly:
- continue
- else:
- resTag = "ITEM"
- xmlBodyText = _xml_escape(_ustr(res))
- out += [ nl, nextLevelIndent, "<", resTag, ">",
- xmlBodyText,
- "</", resTag, ">" ]
-
- out += [ nl, indent, "</", selfTag, ">" ]
- return "".join(out)
-
- def __lookup(self,sub):
- for k,vlist in self.__tokdict.items():
- for v,loc in vlist:
- if sub is v:
- return k
- return None
-
- def getName(self):
- r"""
- Returns the results name for this token expression. Useful when several
- different expressions might match at a particular location.
-
- Example::
- integer = Word(nums)
- ssn_expr = Regex(r"\d\d\d-\d\d-\d\d\d\d")
- house_number_expr = Suppress('#') + Word(nums, alphanums)
- user_data = (Group(house_number_expr)("house_number")
- | Group(ssn_expr)("ssn")
- | Group(integer)("age"))
- user_info = OneOrMore(user_data)
-
- result = user_info.parseString("22 111-22-3333 #221B")
- for item in result:
- print(item.getName(), ':', item[0])
- prints::
- age : 22
- ssn : 111-22-3333
- house_number : 221B
- """
- if self.__name:
- return self.__name
- elif self.__parent:
- par = self.__parent()
- if par:
- return par.__lookup(self)
- else:
- return None
- elif (len(self) == 1 and
- len(self.__tokdict) == 1 and
- next(iter(self.__tokdict.values()))[0][1] in (0,-1)):
- return next(iter(self.__tokdict.keys()))
- else:
- return None
-
- def dump(self, indent='', depth=0, full=True):
- """
- Diagnostic method for listing out the contents of a C{ParseResults}.
- Accepts an optional C{indent} argument so that this string can be embedded
- in a nested display of other data.
-
- Example::
- integer = Word(nums)
- date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
-
- result = date_str.parseString('12/31/1999')
- print(result.dump())
- prints::
- ['12', '/', '31', '/', '1999']
- - day: 1999
- - month: 31
- - year: 12
- """
- out = []
- NL = '\n'
- out.append( indent+_ustr(self.asList()) )
- if full:
- if self.haskeys():
- items = sorted((str(k), v) for k,v in self.items())
- for k,v in items:
- if out:
- out.append(NL)
- out.append( "%s%s- %s: " % (indent,(' '*depth), k) )
- if isinstance(v,ParseResults):
- if v:
- out.append( v.dump(indent,depth+1) )
- else:
- out.append(_ustr(v))
- else:
- out.append(repr(v))
- elif any(isinstance(vv,ParseResults) for vv in self):
- v = self
- for i,vv in enumerate(v):
- if isinstance(vv,ParseResults):
- out.append("\n%s%s[%d]:\n%s%s%s" % (indent,(' '*(depth)),i,indent,(' '*(depth+1)),vv.dump(indent,depth+1) ))
- else:
- out.append("\n%s%s[%d]:\n%s%s%s" % (indent,(' '*(depth)),i,indent,(' '*(depth+1)),_ustr(vv)))
-
- return "".join(out)
-
- def pprint(self, *args, **kwargs):
- """
- Pretty-printer for parsed results as a list, using the C{pprint} module.
- Accepts additional positional or keyword args as defined for the
- C{pprint.pprint} method. (U{http://docs.python.org/3/library/pprint.html#pprint.pprint})
-
- Example::
- ident = Word(alphas, alphanums)
- num = Word(nums)
- func = Forward()
- term = ident | num | Group('(' + func + ')')
- func <<= ident + Group(Optional(delimitedList(term)))
- result = func.parseString("fna a,b,(fnb c,d,200),100")
- result.pprint(width=40)
- prints::
- ['fna',
- ['a',
- 'b',
- ['(', 'fnb', ['c', 'd', '200'], ')'],
- '100']]
- """
- pprint.pprint(self.asList(), *args, **kwargs)
-
- # add support for pickle protocol
- def __getstate__(self):
- return ( self.__toklist,
- ( self.__tokdict.copy(),
- self.__parent is not None and self.__parent() or None,
- self.__accumNames,
- self.__name ) )
-
- def __setstate__(self,state):
- self.__toklist = state[0]
- (self.__tokdict,
- par,
- inAccumNames,
- self.__name) = state[1]
- self.__accumNames = {}
- self.__accumNames.update(inAccumNames)
- if par is not None:
- self.__parent = wkref(par)
- else:
- self.__parent = None
-
- def __getnewargs__(self):
- return self.__toklist, self.__name, self.__asList, self.__modal
-
- def __dir__(self):
- return (dir(type(self)) + list(self.keys()))
-
-MutableMapping.register(ParseResults)
-
-def col (loc,strg):
- """Returns current column within a string, counting newlines as line separators.
- The first column is number 1.
-
- Note: the default parsing behavior is to expand tabs in the input string
- before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information
- on parsing strings containing C{<TAB>}s, and suggested methods to maintain a
- consistent view of the parsed string, the parse location, and line and column
- positions within the parsed string.
- """
- s = strg
- return 1 if 0<loc<len(s) and s[loc-1] == '\n' else loc - s.rfind("\n", 0, loc)
-
-def lineno(loc,strg):
- """Returns current line number within a string, counting newlines as line separators.
- The first line is number 1.
-
- Note: the default parsing behavior is to expand tabs in the input string
- before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information
- on parsing strings containing C{<TAB>}s, and suggested methods to maintain a
- consistent view of the parsed string, the parse location, and line and column
- positions within the parsed string.
- """
- return strg.count("\n",0,loc) + 1
-
-def line( loc, strg ):
- """Returns the line of text containing loc within a string, counting newlines as line separators.
- """
- lastCR = strg.rfind("\n", 0, loc)
- nextCR = strg.find("\n", loc)
- if nextCR >= 0:
- return strg[lastCR+1:nextCR]
- else:
- return strg[lastCR+1:]
-
-def _defaultStartDebugAction( instring, loc, expr ):
- print (("Match " + _ustr(expr) + " at loc " + _ustr(loc) + "(%d,%d)" % ( lineno(loc,instring), col(loc,instring) )))
-
-def _defaultSuccessDebugAction( instring, startloc, endloc, expr, toks ):
- print ("Matched " + _ustr(expr) + " -> " + str(toks.asList()))
-
-def _defaultExceptionDebugAction( instring, loc, expr, exc ):
- print ("Exception raised:" + _ustr(exc))
-
-def nullDebugAction(*args):
- """'Do-nothing' debug action, to suppress debugging output during parsing."""
- pass
-
-# Only works on Python 3.x - nonlocal is toxic to Python 2 installs
-#~ 'decorator to trim function calls to match the arity of the target'
-#~ def _trim_arity(func, maxargs=3):
- #~ if func in singleArgBuiltins:
- #~ return lambda s,l,t: func(t)
- #~ limit = 0
- #~ foundArity = False
- #~ def wrapper(*args):
- #~ nonlocal limit,foundArity
- #~ while 1:
- #~ try:
- #~ ret = func(*args[limit:])
- #~ foundArity = True
- #~ return ret
- #~ except TypeError:
- #~ if limit == maxargs or foundArity:
- #~ raise
- #~ limit += 1
- #~ continue
- #~ return wrapper
-
-# this version is Python 2.x-3.x cross-compatible
-'decorator to trim function calls to match the arity of the target'
-def _trim_arity(func, maxargs=2):
- if func in singleArgBuiltins:
- return lambda s,l,t: func(t)
- limit = [0]
- foundArity = [False]
-
- # traceback return data structure changed in Py3.5 - normalize back to plain tuples
- if system_version[:2] >= (3,5):
- def extract_stack(limit=0):
- # special handling for Python 3.5.0 - extra deep call stack by 1
- offset = -3 if system_version == (3,5,0) else -2
- frame_summary = traceback.extract_stack(limit=-offset+limit-1)[offset]
- return [frame_summary[:2]]
- def extract_tb(tb, limit=0):
- frames = traceback.extract_tb(tb, limit=limit)
- frame_summary = frames[-1]
- return [frame_summary[:2]]
- else:
- extract_stack = traceback.extract_stack
- extract_tb = traceback.extract_tb
-
- # synthesize what would be returned by traceback.extract_stack at the call to
- # user's parse action 'func', so that we don't incur call penalty at parse time
-
- LINE_DIFF = 6
- # IF ANY CODE CHANGES, EVEN JUST COMMENTS OR BLANK LINES, BETWEEN THE NEXT LINE AND
- # THE CALL TO FUNC INSIDE WRAPPER, LINE_DIFF MUST BE MODIFIED!!!!
- this_line = extract_stack(limit=2)[-1]
- pa_call_line_synth = (this_line[0], this_line[1]+LINE_DIFF)
-
- def wrapper(*args):
- while 1:
- try:
- ret = func(*args[limit[0]:])
- foundArity[0] = True
- return ret
- except TypeError:
- # re-raise TypeErrors if they did not come from our arity testing
- if foundArity[0]:
- raise
- else:
- try:
- tb = sys.exc_info()[-1]
- if not extract_tb(tb, limit=2)[-1][:2] == pa_call_line_synth:
- raise
- finally:
- del tb
-
- if limit[0] <= maxargs:
- limit[0] += 1
- continue
- raise
-
- # copy func name to wrapper for sensible debug output
- func_name = "<parse action>"
- try:
- func_name = getattr(func, '__name__',
- getattr(func, '__class__').__name__)
- except Exception:
- func_name = str(func)
- wrapper.__name__ = func_name
-
- return wrapper
-
-class ParserElement(object):
- """Abstract base level parser element class."""
- DEFAULT_WHITE_CHARS = " \n\t\r"
- verbose_stacktrace = False
-
- @staticmethod
- def setDefaultWhitespaceChars( chars ):
- r"""
- Overrides the default whitespace chars
-
- Example::
- # default whitespace chars are space, <TAB> and newline
- OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def', 'ghi', 'jkl']
-
- # change to just treat newline as significant
- ParserElement.setDefaultWhitespaceChars(" \t")
- OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def']
- """
- ParserElement.DEFAULT_WHITE_CHARS = chars
-
- @staticmethod
- def inlineLiteralsUsing(cls):
- """
- Set class to be used for inclusion of string literals into a parser.
-
- Example::
- # default literal class used is Literal
- integer = Word(nums)
- date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
-
- date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31']
-
-
- # change to Suppress
- ParserElement.inlineLiteralsUsing(Suppress)
- date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
-
- date_str.parseString("1999/12/31") # -> ['1999', '12', '31']
- """
- ParserElement._literalStringClass = cls
-
- def __init__( self, savelist=False ):
- self.parseAction = list()
- self.failAction = None
- #~ self.name = "<unknown>" # don't define self.name, let subclasses try/except upcall
- self.strRepr = None
- self.resultsName = None
- self.saveAsList = savelist
- self.skipWhitespace = True
- self.whiteChars = ParserElement.DEFAULT_WHITE_CHARS
- self.copyDefaultWhiteChars = True
- self.mayReturnEmpty = False # used when checking for left-recursion
- self.keepTabs = False
- self.ignoreExprs = list()
- self.debug = False
- self.streamlined = False
- self.mayIndexError = True # used to optimize exception handling for subclasses that don't advance parse index
- self.errmsg = ""
- self.modalResults = True # used to mark results names as modal (report only last) or cumulative (list all)
- self.debugActions = ( None, None, None ) #custom debug actions
- self.re = None
- self.callPreparse = True # used to avoid redundant calls to preParse
- self.callDuringTry = False
-
- def copy( self ):
- """
- Make a copy of this C{ParserElement}. Useful for defining different parse actions
- for the same parsing pattern, using copies of the original parse element.
-
- Example::
- integer = Word(nums).setParseAction(lambda toks: int(toks[0]))
- integerK = integer.copy().addParseAction(lambda toks: toks[0]*1024) + Suppress("K")
- integerM = integer.copy().addParseAction(lambda toks: toks[0]*1024*1024) + Suppress("M")
-
- print(OneOrMore(integerK | integerM | integer).parseString("5K 100 640K 256M"))
- prints::
- [5120, 100, 655360, 268435456]
- Equivalent form of C{expr.copy()} is just C{expr()}::
- integerM = integer().addParseAction(lambda toks: toks[0]*1024*1024) + Suppress("M")
- """
- cpy = copy.copy( self )
- cpy.parseAction = self.parseAction[:]
- cpy.ignoreExprs = self.ignoreExprs[:]
- if self.copyDefaultWhiteChars:
- cpy.whiteChars = ParserElement.DEFAULT_WHITE_CHARS
- return cpy
-
- def setName( self, name ):
- """
- Define name for this expression, makes debugging and exception messages clearer.
-
- Example::
- Word(nums).parseString("ABC") # -> Exception: Expected W:(0123...) (at char 0), (line:1, col:1)
- Word(nums).setName("integer").parseString("ABC") # -> Exception: Expected integer (at char 0), (line:1, col:1)
- """
- self.name = name
- self.errmsg = "Expected " + self.name
- if hasattr(self,"exception"):
- self.exception.msg = self.errmsg
- return self
-
- def setResultsName( self, name, listAllMatches=False ):
- """
- Define name for referencing matching tokens as a nested attribute
- of the returned parse results.
- NOTE: this returns a *copy* of the original C{ParserElement} object;
- this is so that the client can define a basic element, such as an
- integer, and reference it in multiple places with different names.
-
- You can also set results names using the abbreviated syntax,
- C{expr("name")} in place of C{expr.setResultsName("name")} -
- see L{I{__call__}<__call__>}.
-
- Example::
- date_str = (integer.setResultsName("year") + '/'
- + integer.setResultsName("month") + '/'
- + integer.setResultsName("day"))
-
- # equivalent form:
- date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
- """
- newself = self.copy()
- if name.endswith("*"):
- name = name[:-1]
- listAllMatches=True
- newself.resultsName = name
- newself.modalResults = not listAllMatches
- return newself
-
- def setBreak(self,breakFlag = True):
- """Method to invoke the Python pdb debugger when this element is
- about to be parsed. Set C{breakFlag} to True to enable, False to
- disable.
- """
- if breakFlag:
- _parseMethod = self._parse
- def breaker(instring, loc, doActions=True, callPreParse=True):
- import pdb
- pdb.set_trace()
- return _parseMethod( instring, loc, doActions, callPreParse )
- breaker._originalParseMethod = _parseMethod
- self._parse = breaker
- else:
- if hasattr(self._parse,"_originalParseMethod"):
- self._parse = self._parse._originalParseMethod
- return self
-
- def setParseAction( self, *fns, **kwargs ):
- """
- Define one or more actions to perform when successfully matching parse element definition.
- Parse action fn is a callable method with 0-3 arguments, called as C{fn(s,loc,toks)},
- C{fn(loc,toks)}, C{fn(toks)}, or just C{fn()}, where:
- - s = the original string being parsed (see note below)
- - loc = the location of the matching substring
- - toks = a list of the matched tokens, packaged as a C{L{ParseResults}} object
- If the functions in fns modify the tokens, they can return them as the return
- value from fn, and the modified list of tokens will replace the original.
- Otherwise, fn does not need to return any value.
-
- Optional keyword arguments:
- - callDuringTry = (default=C{False}) indicate if parse action should be run during lookaheads and alternate testing
-
- Note: the default parsing behavior is to expand tabs in the input string
- before starting the parsing process. See L{I{parseString}<parseString>} for more information
- on parsing strings containing C{<TAB>}s, and suggested methods to maintain a
- consistent view of the parsed string, the parse location, and line and column
- positions within the parsed string.
-
- Example::
- integer = Word(nums)
- date_str = integer + '/' + integer + '/' + integer
-
- date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31']
-
- # use parse action to convert to ints at parse time
- integer = Word(nums).setParseAction(lambda toks: int(toks[0]))
- date_str = integer + '/' + integer + '/' + integer
-
- # note that integer fields are now ints, not strings
- date_str.parseString("1999/12/31") # -> [1999, '/', 12, '/', 31]
- """
- self.parseAction = list(map(_trim_arity, list(fns)))
- self.callDuringTry = kwargs.get("callDuringTry", False)
- return self
-
- def addParseAction( self, *fns, **kwargs ):
- """
- Add one or more parse actions to expression's list of parse actions. See L{I{setParseAction}<setParseAction>}.
-
- See examples in L{I{copy}<copy>}.
- """
- self.parseAction += list(map(_trim_arity, list(fns)))
- self.callDuringTry = self.callDuringTry or kwargs.get("callDuringTry", False)
- return self
-
- def addCondition(self, *fns, **kwargs):
- """Add a boolean predicate function to expression's list of parse actions. See
- L{I{setParseAction}<setParseAction>} for function call signatures. Unlike C{setParseAction},
- functions passed to C{addCondition} need to return boolean success/fail of the condition.
-
- Optional keyword arguments:
- - message = define a custom message to be used in the raised exception
- - fatal = if True, will raise ParseFatalException to stop parsing immediately; otherwise will raise ParseException
-
- Example::
- integer = Word(nums).setParseAction(lambda toks: int(toks[0]))
- year_int = integer.copy()
- year_int.addCondition(lambda toks: toks[0] >= 2000, message="Only support years 2000 and later")
- date_str = year_int + '/' + integer + '/' + integer
-
- result = date_str.parseString("1999/12/31") # -> Exception: Only support years 2000 and later (at char 0), (line:1, col:1)
- """
- msg = kwargs.get("message", "failed user-defined condition")
- exc_type = ParseFatalException if kwargs.get("fatal", False) else ParseException
- for fn in fns:
- def pa(s,l,t):
- if not bool(_trim_arity(fn)(s,l,t)):
- raise exc_type(s,l,msg)
- self.parseAction.append(pa)
- self.callDuringTry = self.callDuringTry or kwargs.get("callDuringTry", False)
- return self
-
- def setFailAction( self, fn ):
- """Define action to perform if parsing fails at this expression.
- Fail acton fn is a callable function that takes the arguments
- C{fn(s,loc,expr,err)} where:
- - s = string being parsed
- - loc = location where expression match was attempted and failed
- - expr = the parse expression that failed
- - err = the exception thrown
- The function returns no value. It may throw C{L{ParseFatalException}}
- if it is desired to stop parsing immediately."""
- self.failAction = fn
- return self
-
- def _skipIgnorables( self, instring, loc ):
- exprsFound = True
- while exprsFound:
- exprsFound = False
- for e in self.ignoreExprs:
- try:
- while 1:
- loc,dummy = e._parse( instring, loc )
- exprsFound = True
- except ParseException:
- pass
- return loc
-
- def preParse( self, instring, loc ):
- if self.ignoreExprs:
- loc = self._skipIgnorables( instring, loc )
-
- if self.skipWhitespace:
- wt = self.whiteChars
- instrlen = len(instring)
- while loc < instrlen and instring[loc] in wt:
- loc += 1
-
- return loc
-
- def parseImpl( self, instring, loc, doActions=True ):
- return loc, []
-
- def postParse( self, instring, loc, tokenlist ):
- return tokenlist
-
- #~ @profile
- def _parseNoCache( self, instring, loc, doActions=True, callPreParse=True ):
- debugging = ( self.debug ) #and doActions )
-
- if debugging or self.failAction:
- #~ print ("Match",self,"at loc",loc,"(%d,%d)" % ( lineno(loc,instring), col(loc,instring) ))
- if (self.debugActions[0] ):
- self.debugActions[0]( instring, loc, self )
- if callPreParse and self.callPreparse:
- preloc = self.preParse( instring, loc )
- else:
- preloc = loc
- tokensStart = preloc
- try:
- try:
- loc,tokens = self.parseImpl( instring, preloc, doActions )
- except IndexError:
- raise ParseException( instring, len(instring), self.errmsg, self )
- except ParseBaseException as err:
- #~ print ("Exception raised:", err)
- if self.debugActions[2]:
- self.debugActions[2]( instring, tokensStart, self, err )
- if self.failAction:
- self.failAction( instring, tokensStart, self, err )
- raise
- else:
- if callPreParse and self.callPreparse:
- preloc = self.preParse( instring, loc )
- else:
- preloc = loc
- tokensStart = preloc
- if self.mayIndexError or preloc >= len(instring):
- try:
- loc,tokens = self.parseImpl( instring, preloc, doActions )
- except IndexError:
- raise ParseException( instring, len(instring), self.errmsg, self )
- else:
- loc,tokens = self.parseImpl( instring, preloc, doActions )
-
- tokens = self.postParse( instring, loc, tokens )
-
- retTokens = ParseResults( tokens, self.resultsName, asList=self.saveAsList, modal=self.modalResults )
- if self.parseAction and (doActions or self.callDuringTry):
- if debugging:
- try:
- for fn in self.parseAction:
- tokens = fn( instring, tokensStart, retTokens )
- if tokens is not None:
- retTokens = ParseResults( tokens,
- self.resultsName,
- asList=self.saveAsList and isinstance(tokens,(ParseResults,list)),
- modal=self.modalResults )
- except ParseBaseException as err:
- #~ print "Exception raised in user parse action:", err
- if (self.debugActions[2] ):
- self.debugActions[2]( instring, tokensStart, self, err )
- raise
- else:
- for fn in self.parseAction:
- tokens = fn( instring, tokensStart, retTokens )
- if tokens is not None:
- retTokens = ParseResults( tokens,
- self.resultsName,
- asList=self.saveAsList and isinstance(tokens,(ParseResults,list)),
- modal=self.modalResults )
- if debugging:
- #~ print ("Matched",self,"->",retTokens.asList())
- if (self.debugActions[1] ):
- self.debugActions[1]( instring, tokensStart, loc, self, retTokens )
-
- return loc, retTokens
-
- def tryParse( self, instring, loc ):
- try:
- return self._parse( instring, loc, doActions=False )[0]
- except ParseFatalException:
- raise ParseException( instring, loc, self.errmsg, self)
-
- def canParseNext(self, instring, loc):
- try:
- self.tryParse(instring, loc)
- except (ParseException, IndexError):
- return False
- else:
- return True
-
- class _UnboundedCache(object):
- def __init__(self):
- cache = {}
- self.not_in_cache = not_in_cache = object()
-
- def get(self, key):
- return cache.get(key, not_in_cache)
-
- def set(self, key, value):
- cache[key] = value
-
- def clear(self):
- cache.clear()
-
- def cache_len(self):
- return len(cache)
-
- self.get = types.MethodType(get, self)
- self.set = types.MethodType(set, self)
- self.clear = types.MethodType(clear, self)
- self.__len__ = types.MethodType(cache_len, self)
-
- if _OrderedDict is not None:
- class _FifoCache(object):
- def __init__(self, size):
- self.not_in_cache = not_in_cache = object()
-
- cache = _OrderedDict()
-
- def get(self, key):
- return cache.get(key, not_in_cache)
-
- def set(self, key, value):
- cache[key] = value
- while len(cache) > size:
- try:
- cache.popitem(False)
- except KeyError:
- pass
-
- def clear(self):
- cache.clear()
-
- def cache_len(self):
- return len(cache)
-
- self.get = types.MethodType(get, self)
- self.set = types.MethodType(set, self)
- self.clear = types.MethodType(clear, self)
- self.__len__ = types.MethodType(cache_len, self)
-
- else:
- class _FifoCache(object):
- def __init__(self, size):
- self.not_in_cache = not_in_cache = object()
-
- cache = {}
- key_fifo = collections.deque([], size)
-
- def get(self, key):
- return cache.get(key, not_in_cache)
-
- def set(self, key, value):
- cache[key] = value
- while len(key_fifo) > size:
- cache.pop(key_fifo.popleft(), None)
- key_fifo.append(key)
-
- def clear(self):
- cache.clear()
- key_fifo.clear()
-
- def cache_len(self):
- return len(cache)
-
- self.get = types.MethodType(get, self)
- self.set = types.MethodType(set, self)
- self.clear = types.MethodType(clear, self)
- self.__len__ = types.MethodType(cache_len, self)
-
- # argument cache for optimizing repeated calls when backtracking through recursive expressions
- packrat_cache = {} # this is set later by enabledPackrat(); this is here so that resetCache() doesn't fail
- packrat_cache_lock = RLock()
- packrat_cache_stats = [0, 0]
-
- # this method gets repeatedly called during backtracking with the same arguments -
- # we can cache these arguments and save ourselves the trouble of re-parsing the contained expression
- def _parseCache( self, instring, loc, doActions=True, callPreParse=True ):
- HIT, MISS = 0, 1
- lookup = (self, instring, loc, callPreParse, doActions)
- with ParserElement.packrat_cache_lock:
- cache = ParserElement.packrat_cache
- value = cache.get(lookup)
- if value is cache.not_in_cache:
- ParserElement.packrat_cache_stats[MISS] += 1
- try:
- value = self._parseNoCache(instring, loc, doActions, callPreParse)
- except ParseBaseException as pe:
- # cache a copy of the exception, without the traceback
- cache.set(lookup, pe.__class__(*pe.args))
- raise
- else:
- cache.set(lookup, (value[0], value[1].copy()))
- return value
- else:
- ParserElement.packrat_cache_stats[HIT] += 1
- if isinstance(value, Exception):
- raise value
- return (value[0], value[1].copy())
-
- _parse = _parseNoCache
-
- @staticmethod
- def resetCache():
- ParserElement.packrat_cache.clear()
- ParserElement.packrat_cache_stats[:] = [0] * len(ParserElement.packrat_cache_stats)
-
- _packratEnabled = False
- @staticmethod
- def enablePackrat(cache_size_limit=128):
- """Enables "packrat" parsing, which adds memoizing to the parsing logic.
- Repeated parse attempts at the same string location (which happens
- often in many complex grammars) can immediately return a cached value,
- instead of re-executing parsing/validating code. Memoizing is done of
- both valid results and parsing exceptions.
-
- Parameters:
- - cache_size_limit - (default=C{128}) - if an integer value is provided
- will limit the size of the packrat cache; if None is passed, then
- the cache size will be unbounded; if 0 is passed, the cache will
- be effectively disabled.
-
- This speedup may break existing programs that use parse actions that
- have side-effects. For this reason, packrat parsing is disabled when
- you first import pyparsing. To activate the packrat feature, your
- program must call the class method C{ParserElement.enablePackrat()}. If
- your program uses C{psyco} to "compile as you go", you must call
- C{enablePackrat} before calling C{psyco.full()}. If you do not do this,
- Python will crash. For best results, call C{enablePackrat()} immediately
- after importing pyparsing.
-
- Example::
- import pyparsing
- pyparsing.ParserElement.enablePackrat()
- """
- if not ParserElement._packratEnabled:
- ParserElement._packratEnabled = True
- if cache_size_limit is None:
- ParserElement.packrat_cache = ParserElement._UnboundedCache()
- else:
- ParserElement.packrat_cache = ParserElement._FifoCache(cache_size_limit)
- ParserElement._parse = ParserElement._parseCache
-
- def parseString( self, instring, parseAll=False ):
- """
- Execute the parse expression with the given string.
- This is the main interface to the client code, once the complete
- expression has been built.
-
- If you want the grammar to require that the entire input string be
- successfully parsed, then set C{parseAll} to True (equivalent to ending
- the grammar with C{L{StringEnd()}}).
-
- Note: C{parseString} implicitly calls C{expandtabs()} on the input string,
- in order to report proper column numbers in parse actions.
- If the input string contains tabs and
- the grammar uses parse actions that use the C{loc} argument to index into the
- string being parsed, you can ensure you have a consistent view of the input
- string by:
- - calling C{parseWithTabs} on your grammar before calling C{parseString}
- (see L{I{parseWithTabs}<parseWithTabs>})
- - define your parse action using the full C{(s,loc,toks)} signature, and
- reference the input string using the parse action's C{s} argument
- - explictly expand the tabs in your input string before calling
- C{parseString}
-
- Example::
- Word('a').parseString('aaaaabaaa') # -> ['aaaaa']
- Word('a').parseString('aaaaabaaa', parseAll=True) # -> Exception: Expected end of text
- """
- ParserElement.resetCache()
- if not self.streamlined:
- self.streamline()
- #~ self.saveAsList = True
- for e in self.ignoreExprs:
- e.streamline()
- if not self.keepTabs:
- instring = instring.expandtabs()
- try:
- loc, tokens = self._parse( instring, 0 )
- if parseAll:
- loc = self.preParse( instring, loc )
- se = Empty() + StringEnd()
- se._parse( instring, loc )
- except ParseBaseException as exc:
- if ParserElement.verbose_stacktrace:
- raise
- else:
- # catch and re-raise exception from here, clears out pyparsing internal stack trace
- raise exc
- else:
- return tokens
-
- def scanString( self, instring, maxMatches=_MAX_INT, overlap=False ):
- """
- Scan the input string for expression matches. Each match will return the
- matching tokens, start location, and end location. May be called with optional
- C{maxMatches} argument, to clip scanning after 'n' matches are found. If
- C{overlap} is specified, then overlapping matches will be reported.
-
- Note that the start and end locations are reported relative to the string
- being parsed. See L{I{parseString}<parseString>} for more information on parsing
- strings with embedded tabs.
-
- Example::
- source = "sldjf123lsdjjkf345sldkjf879lkjsfd987"
- print(source)
- for tokens,start,end in Word(alphas).scanString(source):
- print(' '*start + '^'*(end-start))
- print(' '*start + tokens[0])
-
- prints::
-
- sldjf123lsdjjkf345sldkjf879lkjsfd987
- ^^^^^
- sldjf
- ^^^^^^^
- lsdjjkf
- ^^^^^^
- sldkjf
- ^^^^^^
- lkjsfd
- """
- if not self.streamlined:
- self.streamline()
- for e in self.ignoreExprs:
- e.streamline()
-
- if not self.keepTabs:
- instring = _ustr(instring).expandtabs()
- instrlen = len(instring)
- loc = 0
- preparseFn = self.preParse
- parseFn = self._parse
- ParserElement.resetCache()
- matches = 0
- try:
- while loc <= instrlen and matches < maxMatches:
- try:
- preloc = preparseFn( instring, loc )
- nextLoc,tokens = parseFn( instring, preloc, callPreParse=False )
- except ParseException:
- loc = preloc+1
- else:
- if nextLoc > loc:
- matches += 1
- yield tokens, preloc, nextLoc
- if overlap:
- nextloc = preparseFn( instring, loc )
- if nextloc > loc:
- loc = nextLoc
- else:
- loc += 1
- else:
- loc = nextLoc
- else:
- loc = preloc+1
- except ParseBaseException as exc:
- if ParserElement.verbose_stacktrace:
- raise
- else:
- # catch and re-raise exception from here, clears out pyparsing internal stack trace
- raise exc
-
- def transformString( self, instring ):
- """
- Extension to C{L{scanString}}, to modify matching text with modified tokens that may
- be returned from a parse action. To use C{transformString}, define a grammar and
- attach a parse action to it that modifies the returned token list.
- Invoking C{transformString()} on a target string will then scan for matches,
- and replace the matched text patterns according to the logic in the parse
- action. C{transformString()} returns the resulting transformed string.
-
- Example::
- wd = Word(alphas)
- wd.setParseAction(lambda toks: toks[0].title())
-
- print(wd.transformString("now is the winter of our discontent made glorious summer by this sun of york."))
- Prints::
- Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York.
- """
- out = []
- lastE = 0
- # force preservation of <TAB>s, to minimize unwanted transformation of string, and to
- # keep string locs straight between transformString and scanString
- self.keepTabs = True
- try:
- for t,s,e in self.scanString( instring ):
- out.append( instring[lastE:s] )
- if t:
- if isinstance(t,ParseResults):
- out += t.asList()
- elif isinstance(t,list):
- out += t
- else:
- out.append(t)
- lastE = e
- out.append(instring[lastE:])
- out = [o for o in out if o]
- return "".join(map(_ustr,_flatten(out)))
- except ParseBaseException as exc:
- if ParserElement.verbose_stacktrace:
- raise
- else:
- # catch and re-raise exception from here, clears out pyparsing internal stack trace
- raise exc
-
- def searchString( self, instring, maxMatches=_MAX_INT ):
- """
- Another extension to C{L{scanString}}, simplifying the access to the tokens found
- to match the given parse expression. May be called with optional
- C{maxMatches} argument, to clip searching after 'n' matches are found.
-
- Example::
- # a capitalized word starts with an uppercase letter, followed by zero or more lowercase letters
- cap_word = Word(alphas.upper(), alphas.lower())
-
- print(cap_word.searchString("More than Iron, more than Lead, more than Gold I need Electricity"))
-
- # the sum() builtin can be used to merge results into a single ParseResults object
- print(sum(cap_word.searchString("More than Iron, more than Lead, more than Gold I need Electricity")))
- prints::
- [['More'], ['Iron'], ['Lead'], ['Gold'], ['I'], ['Electricity']]
- ['More', 'Iron', 'Lead', 'Gold', 'I', 'Electricity']
- """
- try:
- return ParseResults([ t for t,s,e in self.scanString( instring, maxMatches ) ])
- except ParseBaseException as exc:
- if ParserElement.verbose_stacktrace:
- raise
- else:
- # catch and re-raise exception from here, clears out pyparsing internal stack trace
- raise exc
-
- def split(self, instring, maxsplit=_MAX_INT, includeSeparators=False):
- """
- Generator method to split a string using the given expression as a separator.
- May be called with optional C{maxsplit} argument, to limit the number of splits;
- and the optional C{includeSeparators} argument (default=C{False}), if the separating
- matching text should be included in the split results.
-
- Example::
- punc = oneOf(list(".,;:/-!?"))
- print(list(punc.split("This, this?, this sentence, is badly punctuated!")))
- prints::
- ['This', ' this', '', ' this sentence', ' is badly punctuated', '']
- """
- splits = 0
- last = 0
- for t,s,e in self.scanString(instring, maxMatches=maxsplit):
- yield instring[last:s]
- if includeSeparators:
- yield t[0]
- last = e
- yield instring[last:]
-
- def __add__(self, other ):
- """
- Implementation of + operator - returns C{L{And}}. Adding strings to a ParserElement
- converts them to L{Literal}s by default.
-
- Example::
- greet = Word(alphas) + "," + Word(alphas) + "!"
- hello = "Hello, World!"
- print (hello, "->", greet.parseString(hello))
- Prints::
- Hello, World! -> ['Hello', ',', 'World', '!']
- """
- if isinstance( other, basestring ):
- other = ParserElement._literalStringClass( other )
- if not isinstance( other, ParserElement ):
- warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
- SyntaxWarning, stacklevel=2)
- return None
- return And( [ self, other ] )
-
- def __radd__(self, other ):
- """
- Implementation of + operator when left operand is not a C{L{ParserElement}}
- """
- if isinstance( other, basestring ):
- other = ParserElement._literalStringClass( other )
- if not isinstance( other, ParserElement ):
- warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
- SyntaxWarning, stacklevel=2)
- return None
- return other + self
-
- def __sub__(self, other):
- """
- Implementation of - operator, returns C{L{And}} with error stop
- """
- if isinstance( other, basestring ):
- other = ParserElement._literalStringClass( other )
- if not isinstance( other, ParserElement ):
- warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
- SyntaxWarning, stacklevel=2)
- return None
- return self + And._ErrorStop() + other
-
- def __rsub__(self, other ):
- """
- Implementation of - operator when left operand is not a C{L{ParserElement}}
- """
- if isinstance( other, basestring ):
- other = ParserElement._literalStringClass( other )
- if not isinstance( other, ParserElement ):
- warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
- SyntaxWarning, stacklevel=2)
- return None
- return other - self
-
- def __mul__(self,other):
- """
- Implementation of * operator, allows use of C{expr * 3} in place of
- C{expr + expr + expr}. Expressions may also me multiplied by a 2-integer
- tuple, similar to C{{min,max}} multipliers in regular expressions. Tuples
- may also include C{None} as in:
- - C{expr*(n,None)} or C{expr*(n,)} is equivalent
- to C{expr*n + L{ZeroOrMore}(expr)}
- (read as "at least n instances of C{expr}")
- - C{expr*(None,n)} is equivalent to C{expr*(0,n)}
- (read as "0 to n instances of C{expr}")
- - C{expr*(None,None)} is equivalent to C{L{ZeroOrMore}(expr)}
- - C{expr*(1,None)} is equivalent to C{L{OneOrMore}(expr)}
-
- Note that C{expr*(None,n)} does not raise an exception if
- more than n exprs exist in the input stream; that is,
- C{expr*(None,n)} does not enforce a maximum number of expr
- occurrences. If this behavior is desired, then write
- C{expr*(None,n) + ~expr}
- """
- if isinstance(other,int):
- minElements, optElements = other,0
- elif isinstance(other,tuple):
- other = (other + (None, None))[:2]
- if other[0] is None:
- other = (0, other[1])
- if isinstance(other[0],int) and other[1] is None:
- if other[0] == 0:
- return ZeroOrMore(self)
- if other[0] == 1:
- return OneOrMore(self)
- else:
- return self*other[0] + ZeroOrMore(self)
- elif isinstance(other[0],int) and isinstance(other[1],int):
- minElements, optElements = other
- optElements -= minElements
- else:
- raise TypeError("cannot multiply 'ParserElement' and ('%s','%s') objects", type(other[0]),type(other[1]))
- else:
- raise TypeError("cannot multiply 'ParserElement' and '%s' objects", type(other))
-
- if minElements < 0:
- raise ValueError("cannot multiply ParserElement by negative value")
- if optElements < 0:
- raise ValueError("second tuple value must be greater or equal to first tuple value")
- if minElements == optElements == 0:
- raise ValueError("cannot multiply ParserElement by 0 or (0,0)")
-
- if (optElements):
- def makeOptionalList(n):
- if n>1:
- return Optional(self + makeOptionalList(n-1))
- else:
- return Optional(self)
- if minElements:
- if minElements == 1:
- ret = self + makeOptionalList(optElements)
- else:
- ret = And([self]*minElements) + makeOptionalList(optElements)
- else:
- ret = makeOptionalList(optElements)
- else:
- if minElements == 1:
- ret = self
- else:
- ret = And([self]*minElements)
- return ret
-
- def __rmul__(self, other):
- return self.__mul__(other)
-
- def __or__(self, other ):
- """
- Implementation of | operator - returns C{L{MatchFirst}}
- """
- if isinstance( other, basestring ):
- other = ParserElement._literalStringClass( other )
- if not isinstance( other, ParserElement ):
- warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
- SyntaxWarning, stacklevel=2)
- return None
- return MatchFirst( [ self, other ] )
-
- def __ror__(self, other ):
- """
- Implementation of | operator when left operand is not a C{L{ParserElement}}
- """
- if isinstance( other, basestring ):
- other = ParserElement._literalStringClass( other )
- if not isinstance( other, ParserElement ):
- warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
- SyntaxWarning, stacklevel=2)
- return None
- return other | self
-
- def __xor__(self, other ):
- """
- Implementation of ^ operator - returns C{L{Or}}
- """
- if isinstance( other, basestring ):
- other = ParserElement._literalStringClass( other )
- if not isinstance( other, ParserElement ):
- warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
- SyntaxWarning, stacklevel=2)
- return None
- return Or( [ self, other ] )
-
- def __rxor__(self, other ):
- """
- Implementation of ^ operator when left operand is not a C{L{ParserElement}}
- """
- if isinstance( other, basestring ):
- other = ParserElement._literalStringClass( other )
- if not isinstance( other, ParserElement ):
- warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
- SyntaxWarning, stacklevel=2)
- return None
- return other ^ self
-
- def __and__(self, other ):
- """
- Implementation of & operator - returns C{L{Each}}
- """
- if isinstance( other, basestring ):
- other = ParserElement._literalStringClass( other )
- if not isinstance( other, ParserElement ):
- warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
- SyntaxWarning, stacklevel=2)
- return None
- return Each( [ self, other ] )
-
- def __rand__(self, other ):
- """
- Implementation of & operator when left operand is not a C{L{ParserElement}}
- """
- if isinstance( other, basestring ):
- other = ParserElement._literalStringClass( other )
- if not isinstance( other, ParserElement ):
- warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
- SyntaxWarning, stacklevel=2)
- return None
- return other & self
-
- def __invert__( self ):
- """
- Implementation of ~ operator - returns C{L{NotAny}}
- """
- return NotAny( self )
-
- def __call__(self, name=None):
- """
- Shortcut for C{L{setResultsName}}, with C{listAllMatches=False}.
-
- If C{name} is given with a trailing C{'*'} character, then C{listAllMatches} will be
- passed as C{True}.
-
- If C{name} is omitted, same as calling C{L{copy}}.
-
- Example::
- # these are equivalent
- userdata = Word(alphas).setResultsName("name") + Word(nums+"-").setResultsName("socsecno")
- userdata = Word(alphas)("name") + Word(nums+"-")("socsecno")
- """
- if name is not None:
- return self.setResultsName(name)
- else:
- return self.copy()
-
- def suppress( self ):
- """
- Suppresses the output of this C{ParserElement}; useful to keep punctuation from
- cluttering up returned output.
- """
- return Suppress( self )
-
- def leaveWhitespace( self ):
- """
- Disables the skipping of whitespace before matching the characters in the
- C{ParserElement}'s defined pattern. This is normally only used internally by
- the pyparsing module, but may be needed in some whitespace-sensitive grammars.
- """
- self.skipWhitespace = False
- return self
-
- def setWhitespaceChars( self, chars ):
- """
- Overrides the default whitespace chars
- """
- self.skipWhitespace = True
- self.whiteChars = chars
- self.copyDefaultWhiteChars = False
- return self
-
- def parseWithTabs( self ):
- """
- Overrides default behavior to expand C{<TAB>}s to spaces before parsing the input string.
- Must be called before C{parseString} when the input grammar contains elements that
- match C{<TAB>} characters.
- """
- self.keepTabs = True
- return self
-
- def ignore( self, other ):
- """
- Define expression to be ignored (e.g., comments) while doing pattern
- matching; may be called repeatedly, to define multiple comment or other
- ignorable patterns.
-
- Example::
- patt = OneOrMore(Word(alphas))
- patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj']
-
- patt.ignore(cStyleComment)
- patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj', 'lskjd']
- """
- if isinstance(other, basestring):
- other = Suppress(other)
-
- if isinstance( other, Suppress ):
- if other not in self.ignoreExprs:
- self.ignoreExprs.append(other)
- else:
- self.ignoreExprs.append( Suppress( other.copy() ) )
- return self
-
- def setDebugActions( self, startAction, successAction, exceptionAction ):
- """
- Enable display of debugging messages while doing pattern matching.
- """
- self.debugActions = (startAction or _defaultStartDebugAction,
- successAction or _defaultSuccessDebugAction,
- exceptionAction or _defaultExceptionDebugAction)
- self.debug = True
- return self
-
- def setDebug( self, flag=True ):
- """
- Enable display of debugging messages while doing pattern matching.
- Set C{flag} to True to enable, False to disable.
-
- Example::
- wd = Word(alphas).setName("alphaword")
- integer = Word(nums).setName("numword")
- term = wd | integer
-
- # turn on debugging for wd
- wd.setDebug()
-
- OneOrMore(term).parseString("abc 123 xyz 890")
-
- prints::
- Match alphaword at loc 0(1,1)
- Matched alphaword -> ['abc']
- Match alphaword at loc 3(1,4)
- Exception raised:Expected alphaword (at char 4), (line:1, col:5)
- Match alphaword at loc 7(1,8)
- Matched alphaword -> ['xyz']
- Match alphaword at loc 11(1,12)
- Exception raised:Expected alphaword (at char 12), (line:1, col:13)
- Match alphaword at loc 15(1,16)
- Exception raised:Expected alphaword (at char 15), (line:1, col:16)
-
- The output shown is that produced by the default debug actions - custom debug actions can be
- specified using L{setDebugActions}. Prior to attempting
- to match the C{wd} expression, the debugging message C{"Match <exprname> at loc <n>(<line>,<col>)"}
- is shown. Then if the parse succeeds, a C{"Matched"} message is shown, or an C{"Exception raised"}
- message is shown. Also note the use of L{setName} to assign a human-readable name to the expression,
- which makes debugging and exception messages easier to understand - for instance, the default
- name created for the C{Word} expression without calling C{setName} is C{"W:(ABCD...)"}.
- """
- if flag:
- self.setDebugActions( _defaultStartDebugAction, _defaultSuccessDebugAction, _defaultExceptionDebugAction )
- else:
- self.debug = False
- return self
-
- def __str__( self ):
- return self.name
-
- def __repr__( self ):
- return _ustr(self)
-
- def streamline( self ):
- self.streamlined = True
- self.strRepr = None
- return self
-
- def checkRecursion( self, parseElementList ):
- pass
-
- def validate( self, validateTrace=[] ):
- """
- Check defined expressions for valid structure, check for infinite recursive definitions.
- """
- self.checkRecursion( [] )
-
- def parseFile( self, file_or_filename, parseAll=False ):
- """
- Execute the parse expression on the given file or filename.
- If a filename is specified (instead of a file object),
- the entire file is opened, read, and closed before parsing.
- """
- try:
- file_contents = file_or_filename.read()
- except AttributeError:
- with open(file_or_filename, "r") as f:
- file_contents = f.read()
- try:
- return self.parseString(file_contents, parseAll)
- except ParseBaseException as exc:
- if ParserElement.verbose_stacktrace:
- raise
- else:
- # catch and re-raise exception from here, clears out pyparsing internal stack trace
- raise exc
-
- def __eq__(self,other):
- if isinstance(other, ParserElement):
- return self is other or vars(self) == vars(other)
- elif isinstance(other, basestring):
- return self.matches(other)
- else:
- return super(ParserElement,self)==other
-
- def __ne__(self,other):
- return not (self == other)
-
- def __hash__(self):
- return hash(id(self))
-
- def __req__(self,other):
- return self == other
-
- def __rne__(self,other):
- return not (self == other)
-
- def matches(self, testString, parseAll=True):
- """
- Method for quick testing of a parser against a test string. Good for simple
- inline microtests of sub expressions while building up larger parser.
-
- Parameters:
- - testString - to test against this expression for a match
- - parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests
-
- Example::
- expr = Word(nums)
- assert expr.matches("100")
- """
- try:
- self.parseString(_ustr(testString), parseAll=parseAll)
- return True
- except ParseBaseException:
- return False
-
- def runTests(self, tests, parseAll=True, comment='#', fullDump=True, printResults=True, failureTests=False):
- """
- Execute the parse expression on a series of test strings, showing each
- test, the parsed results or where the parse failed. Quick and easy way to
- run a parse expression against a list of sample strings.
-
- Parameters:
- - tests - a list of separate test strings, or a multiline string of test strings
- - parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests
- - comment - (default=C{'#'}) - expression for indicating embedded comments in the test
- string; pass None to disable comment filtering
- - fullDump - (default=C{True}) - dump results as list followed by results names in nested outline;
- if False, only dump nested list
- - printResults - (default=C{True}) prints test output to stdout
- - failureTests - (default=C{False}) indicates if these tests are expected to fail parsing
-
- Returns: a (success, results) tuple, where success indicates that all tests succeeded
- (or failed if C{failureTests} is True), and the results contain a list of lines of each
- test's output
-
- Example::
- number_expr = pyparsing_common.number.copy()
-
- result = number_expr.runTests('''
- # unsigned integer
- 100
- # negative integer
- -100
- # float with scientific notation
- 6.02e23
- # integer with scientific notation
- 1e-12
- ''')
- print("Success" if result[0] else "Failed!")
-
- result = number_expr.runTests('''
- # stray character
- 100Z
- # missing leading digit before '.'
- -.100
- # too many '.'
- 3.14.159
- ''', failureTests=True)
- print("Success" if result[0] else "Failed!")
- prints::
- # unsigned integer
- 100
- [100]
-
- # negative integer
- -100
- [-100]
-
- # float with scientific notation
- 6.02e23
- [6.02e+23]
-
- # integer with scientific notation
- 1e-12
- [1e-12]
-
- Success
-
- # stray character
- 100Z
- ^
- FAIL: Expected end of text (at char 3), (line:1, col:4)
-
- # missing leading digit before '.'
- -.100
- ^
- FAIL: Expected {real number with scientific notation | real number | signed integer} (at char 0), (line:1, col:1)
-
- # too many '.'
- 3.14.159
- ^
- FAIL: Expected end of text (at char 4), (line:1, col:5)
-
- Success
-
- Each test string must be on a single line. If you want to test a string that spans multiple
- lines, create a test like this::
-
- expr.runTest(r"this is a test\\n of strings that spans \\n 3 lines")
-
- (Note that this is a raw string literal, you must include the leading 'r'.)
- """
- if isinstance(tests, basestring):
- tests = list(map(str.strip, tests.rstrip().splitlines()))
- if isinstance(comment, basestring):
- comment = Literal(comment)
- allResults = []
- comments = []
- success = True
- for t in tests:
- if comment is not None and comment.matches(t, False) or comments and not t:
- comments.append(t)
- continue
- if not t:
- continue
- out = ['\n'.join(comments), t]
- comments = []
- try:
- t = t.replace(r'\n','\n')
- result = self.parseString(t, parseAll=parseAll)
- out.append(result.dump(full=fullDump))
- success = success and not failureTests
- except ParseBaseException as pe:
- fatal = "(FATAL)" if isinstance(pe, ParseFatalException) else ""
- if '\n' in t:
- out.append(line(pe.loc, t))
- out.append(' '*(col(pe.loc,t)-1) + '^' + fatal)
- else:
- out.append(' '*pe.loc + '^' + fatal)
- out.append("FAIL: " + str(pe))
- success = success and failureTests
- result = pe
- except Exception as exc:
- out.append("FAIL-EXCEPTION: " + str(exc))
- success = success and failureTests
- result = exc
-
- if printResults:
- if fullDump:
- out.append('')
- print('\n'.join(out))
-
- allResults.append((t, result))
-
- return success, allResults
-
-
-class Token(ParserElement):
- """
- Abstract C{ParserElement} subclass, for defining atomic matching patterns.
- """
- def __init__( self ):
- super(Token,self).__init__( savelist=False )
-
-
-class Empty(Token):
- """
- An empty token, will always match.
- """
- def __init__( self ):
- super(Empty,self).__init__()
- self.name = "Empty"
- self.mayReturnEmpty = True
- self.mayIndexError = False
-
-
-class NoMatch(Token):
- """
- A token that will never match.
- """
- def __init__( self ):
- super(NoMatch,self).__init__()
- self.name = "NoMatch"
- self.mayReturnEmpty = True
- self.mayIndexError = False
- self.errmsg = "Unmatchable token"
-
- def parseImpl( self, instring, loc, doActions=True ):
- raise ParseException(instring, loc, self.errmsg, self)
-
-
-class Literal(Token):
- """
- Token to exactly match a specified string.
-
- Example::
- Literal('blah').parseString('blah') # -> ['blah']
- Literal('blah').parseString('blahfooblah') # -> ['blah']
- Literal('blah').parseString('bla') # -> Exception: Expected "blah"
-
- For case-insensitive matching, use L{CaselessLiteral}.
-
- For keyword matching (force word break before and after the matched string),
- use L{Keyword} or L{CaselessKeyword}.
- """
- def __init__( self, matchString ):
- super(Literal,self).__init__()
- self.match = matchString
- self.matchLen = len(matchString)
- try:
- self.firstMatchChar = matchString[0]
- except IndexError:
- warnings.warn("null string passed to Literal; use Empty() instead",
- SyntaxWarning, stacklevel=2)
- self.__class__ = Empty
- self.name = '"%s"' % _ustr(self.match)
- self.errmsg = "Expected " + self.name
- self.mayReturnEmpty = False
- self.mayIndexError = False
-
- # Performance tuning: this routine gets called a *lot*
- # if this is a single character match string and the first character matches,
- # short-circuit as quickly as possible, and avoid calling startswith
- #~ @profile
- def parseImpl( self, instring, loc, doActions=True ):
- if (instring[loc] == self.firstMatchChar and
- (self.matchLen==1 or instring.startswith(self.match,loc)) ):
- return loc+self.matchLen, self.match
- raise ParseException(instring, loc, self.errmsg, self)
-_L = Literal
-ParserElement._literalStringClass = Literal
-
-class Keyword(Token):
- """
- Token to exactly match a specified string as a keyword, that is, it must be
- immediately followed by a non-keyword character. Compare with C{L{Literal}}:
- - C{Literal("if")} will match the leading C{'if'} in C{'ifAndOnlyIf'}.
- - C{Keyword("if")} will not; it will only match the leading C{'if'} in C{'if x=1'}, or C{'if(y==2)'}
- Accepts two optional constructor arguments in addition to the keyword string:
- - C{identChars} is a string of characters that would be valid identifier characters,
- defaulting to all alphanumerics + "_" and "$"
- - C{caseless} allows case-insensitive matching, default is C{False}.
-
- Example::
- Keyword("start").parseString("start") # -> ['start']
- Keyword("start").parseString("starting") # -> Exception
-
- For case-insensitive matching, use L{CaselessKeyword}.
- """
- DEFAULT_KEYWORD_CHARS = alphanums+"_$"
-
- def __init__( self, matchString, identChars=None, caseless=False ):
- super(Keyword,self).__init__()
- if identChars is None:
- identChars = Keyword.DEFAULT_KEYWORD_CHARS
- self.match = matchString
- self.matchLen = len(matchString)
- try:
- self.firstMatchChar = matchString[0]
- except IndexError:
- warnings.warn("null string passed to Keyword; use Empty() instead",
- SyntaxWarning, stacklevel=2)
- self.name = '"%s"' % self.match
- self.errmsg = "Expected " + self.name
- self.mayReturnEmpty = False
- self.mayIndexError = False
- self.caseless = caseless
- if caseless:
- self.caselessmatch = matchString.upper()
- identChars = identChars.upper()
- self.identChars = set(identChars)
-
- def parseImpl( self, instring, loc, doActions=True ):
- if self.caseless:
- if ( (instring[ loc:loc+self.matchLen ].upper() == self.caselessmatch) and
- (loc >= len(instring)-self.matchLen or instring[loc+self.matchLen].upper() not in self.identChars) and
- (loc == 0 or instring[loc-1].upper() not in self.identChars) ):
- return loc+self.matchLen, self.match
- else:
- if (instring[loc] == self.firstMatchChar and
- (self.matchLen==1 or instring.startswith(self.match,loc)) and
- (loc >= len(instring)-self.matchLen or instring[loc+self.matchLen] not in self.identChars) and
- (loc == 0 or instring[loc-1] not in self.identChars) ):
- return loc+self.matchLen, self.match
- raise ParseException(instring, loc, self.errmsg, self)
-
- def copy(self):
- c = super(Keyword,self).copy()
- c.identChars = Keyword.DEFAULT_KEYWORD_CHARS
- return c
-
- @staticmethod
- def setDefaultKeywordChars( chars ):
- """Overrides the default Keyword chars
- """
- Keyword.DEFAULT_KEYWORD_CHARS = chars
-
-class CaselessLiteral(Literal):
- """
- Token to match a specified string, ignoring case of letters.
- Note: the matched results will always be in the case of the given
- match string, NOT the case of the input text.
-
- Example::
- OneOrMore(CaselessLiteral("CMD")).parseString("cmd CMD Cmd10") # -> ['CMD', 'CMD', 'CMD']
-
- (Contrast with example for L{CaselessKeyword}.)
- """
- def __init__( self, matchString ):
- super(CaselessLiteral,self).__init__( matchString.upper() )
- # Preserve the defining literal.
- self.returnString = matchString
- self.name = "'%s'" % self.returnString
- self.errmsg = "Expected " + self.name
-
- def parseImpl( self, instring, loc, doActions=True ):
- if instring[ loc:loc+self.matchLen ].upper() == self.match:
- return loc+self.matchLen, self.returnString
- raise ParseException(instring, loc, self.errmsg, self)
-
-class CaselessKeyword(Keyword):
- """
- Caseless version of L{Keyword}.
-
- Example::
- OneOrMore(CaselessKeyword("CMD")).parseString("cmd CMD Cmd10") # -> ['CMD', 'CMD']
-
- (Contrast with example for L{CaselessLiteral}.)
- """
- def __init__( self, matchString, identChars=None ):
- super(CaselessKeyword,self).__init__( matchString, identChars, caseless=True )
-
- def parseImpl( self, instring, loc, doActions=True ):
- if ( (instring[ loc:loc+self.matchLen ].upper() == self.caselessmatch) and
- (loc >= len(instring)-self.matchLen or instring[loc+self.matchLen].upper() not in self.identChars) ):
- return loc+self.matchLen, self.match
- raise ParseException(instring, loc, self.errmsg, self)
-
-class CloseMatch(Token):
- """
- A variation on L{Literal} which matches "close" matches, that is,
- strings with at most 'n' mismatching characters. C{CloseMatch} takes parameters:
- - C{match_string} - string to be matched
- - C{maxMismatches} - (C{default=1}) maximum number of mismatches allowed to count as a match
-
- The results from a successful parse will contain the matched text from the input string and the following named results:
- - C{mismatches} - a list of the positions within the match_string where mismatches were found
- - C{original} - the original match_string used to compare against the input string
-
- If C{mismatches} is an empty list, then the match was an exact match.
-
- Example::
- patt = CloseMatch("ATCATCGAATGGA")
- patt.parseString("ATCATCGAAXGGA") # -> (['ATCATCGAAXGGA'], {'mismatches': [[9]], 'original': ['ATCATCGAATGGA']})
- patt.parseString("ATCAXCGAAXGGA") # -> Exception: Expected 'ATCATCGAATGGA' (with up to 1 mismatches) (at char 0), (line:1, col:1)
-
- # exact match
- patt.parseString("ATCATCGAATGGA") # -> (['ATCATCGAATGGA'], {'mismatches': [[]], 'original': ['ATCATCGAATGGA']})
-
- # close match allowing up to 2 mismatches
- patt = CloseMatch("ATCATCGAATGGA", maxMismatches=2)
- patt.parseString("ATCAXCGAAXGGA") # -> (['ATCAXCGAAXGGA'], {'mismatches': [[4, 9]], 'original': ['ATCATCGAATGGA']})
- """
- def __init__(self, match_string, maxMismatches=1):
- super(CloseMatch,self).__init__()
- self.name = match_string
- self.match_string = match_string
- self.maxMismatches = maxMismatches
- self.errmsg = "Expected %r (with up to %d mismatches)" % (self.match_string, self.maxMismatches)
- self.mayIndexError = False
- self.mayReturnEmpty = False
-
- def parseImpl( self, instring, loc, doActions=True ):
- start = loc
- instrlen = len(instring)
- maxloc = start + len(self.match_string)
-
- if maxloc <= instrlen:
- match_string = self.match_string
- match_stringloc = 0
- mismatches = []
- maxMismatches = self.maxMismatches
-
- for match_stringloc,s_m in enumerate(zip(instring[loc:maxloc], self.match_string)):
- src,mat = s_m
- if src != mat:
- mismatches.append(match_stringloc)
- if len(mismatches) > maxMismatches:
- break
- else:
- loc = match_stringloc + 1
- results = ParseResults([instring[start:loc]])
- results['original'] = self.match_string
- results['mismatches'] = mismatches
- return loc, results
-
- raise ParseException(instring, loc, self.errmsg, self)
-
-
-class Word(Token):
- """
- Token for matching words composed of allowed character sets.
- Defined with string containing all allowed initial characters,
- an optional string containing allowed body characters (if omitted,
- defaults to the initial character set), and an optional minimum,
- maximum, and/or exact length. The default value for C{min} is 1 (a
- minimum value < 1 is not valid); the default values for C{max} and C{exact}
- are 0, meaning no maximum or exact length restriction. An optional
- C{excludeChars} parameter can list characters that might be found in
- the input C{bodyChars} string; useful to define a word of all printables
- except for one or two characters, for instance.
-
- L{srange} is useful for defining custom character set strings for defining
- C{Word} expressions, using range notation from regular expression character sets.
-
- A common mistake is to use C{Word} to match a specific literal string, as in
- C{Word("Address")}. Remember that C{Word} uses the string argument to define
- I{sets} of matchable characters. This expression would match "Add", "AAA",
- "dAred", or any other word made up of the characters 'A', 'd', 'r', 'e', and 's'.
- To match an exact literal string, use L{Literal} or L{Keyword}.
-
- pyparsing includes helper strings for building Words:
- - L{alphas}
- - L{nums}
- - L{alphanums}
- - L{hexnums}
- - L{alphas8bit} (alphabetic characters in ASCII range 128-255 - accented, tilded, umlauted, etc.)
- - L{punc8bit} (non-alphabetic characters in ASCII range 128-255 - currency, symbols, superscripts, diacriticals, etc.)
- - L{printables} (any non-whitespace character)
-
- Example::
- # a word composed of digits
- integer = Word(nums) # equivalent to Word("0123456789") or Word(srange("0-9"))
-
- # a word with a leading capital, and zero or more lowercase
- capital_word = Word(alphas.upper(), alphas.lower())
-
- # hostnames are alphanumeric, with leading alpha, and '-'
- hostname = Word(alphas, alphanums+'-')
-
- # roman numeral (not a strict parser, accepts invalid mix of characters)
- roman = Word("IVXLCDM")
-
- # any string of non-whitespace characters, except for ','
- csv_value = Word(printables, excludeChars=",")
- """
- def __init__( self, initChars, bodyChars=None, min=1, max=0, exact=0, asKeyword=False, excludeChars=None ):
- super(Word,self).__init__()
- if excludeChars:
- initChars = ''.join(c for c in initChars if c not in excludeChars)
- if bodyChars:
- bodyChars = ''.join(c for c in bodyChars if c not in excludeChars)
- self.initCharsOrig = initChars
- self.initChars = set(initChars)
- if bodyChars :
- self.bodyCharsOrig = bodyChars
- self.bodyChars = set(bodyChars)
- else:
- self.bodyCharsOrig = initChars
- self.bodyChars = set(initChars)
-
- self.maxSpecified = max > 0
-
- if min < 1:
- raise ValueError("cannot specify a minimum length < 1; use Optional(Word()) if zero-length word is permitted")
-
- self.minLen = min
-
- if max > 0:
- self.maxLen = max
- else:
- self.maxLen = _MAX_INT
-
- if exact > 0:
- self.maxLen = exact
- self.minLen = exact
-
- self.name = _ustr(self)
- self.errmsg = "Expected " + self.name
- self.mayIndexError = False
- self.asKeyword = asKeyword
-
- if ' ' not in self.initCharsOrig+self.bodyCharsOrig and (min==1 and max==0 and exact==0):
- if self.bodyCharsOrig == self.initCharsOrig:
- self.reString = "[%s]+" % _escapeRegexRangeChars(self.initCharsOrig)
- elif len(self.initCharsOrig) == 1:
- self.reString = "%s[%s]*" % \
- (re.escape(self.initCharsOrig),
- _escapeRegexRangeChars(self.bodyCharsOrig),)
- else:
- self.reString = "[%s][%s]*" % \
- (_escapeRegexRangeChars(self.initCharsOrig),
- _escapeRegexRangeChars(self.bodyCharsOrig),)
- if self.asKeyword:
- self.reString = r"\b"+self.reString+r"\b"
- try:
- self.re = re.compile( self.reString )
- except Exception:
- self.re = None
-
- def parseImpl( self, instring, loc, doActions=True ):
- if self.re:
- result = self.re.match(instring,loc)
- if not result:
- raise ParseException(instring, loc, self.errmsg, self)
-
- loc = result.end()
- return loc, result.group()
-
- if not(instring[ loc ] in self.initChars):
- raise ParseException(instring, loc, self.errmsg, self)
-
- start = loc
- loc += 1
- instrlen = len(instring)
- bodychars = self.bodyChars
- maxloc = start + self.maxLen
- maxloc = min( maxloc, instrlen )
- while loc < maxloc and instring[loc] in bodychars:
- loc += 1
-
- throwException = False
- if loc - start < self.minLen:
- throwException = True
- if self.maxSpecified and loc < instrlen and instring[loc] in bodychars:
- throwException = True
- if self.asKeyword:
- if (start>0 and instring[start-1] in bodychars) or (loc<instrlen and instring[loc] in bodychars):
- throwException = True
-
- if throwException:
- raise ParseException(instring, loc, self.errmsg, self)
-
- return loc, instring[start:loc]
-
- def __str__( self ):
- try:
- return super(Word,self).__str__()
- except Exception:
- pass
-
-
- if self.strRepr is None:
-
- def charsAsStr(s):
- if len(s)>4:
- return s[:4]+"..."
- else:
- return s
-
- if ( self.initCharsOrig != self.bodyCharsOrig ):
- self.strRepr = "W:(%s,%s)" % ( charsAsStr(self.initCharsOrig), charsAsStr(self.bodyCharsOrig) )
- else:
- self.strRepr = "W:(%s)" % charsAsStr(self.initCharsOrig)
-
- return self.strRepr
-
-
-class Regex(Token):
- r"""
- Token for matching strings that match a given regular expression.
- Defined with string specifying the regular expression in a form recognized by the inbuilt Python re module.
- If the given regex contains named groups (defined using C{(?P<name>...)}), these will be preserved as
- named parse results.
-
- Example::
- realnum = Regex(r"[+-]?\d+\.\d*")
- date = Regex(r'(?P<year>\d{4})-(?P<month>\d\d?)-(?P<day>\d\d?)')
- # ref: http://stackoverflow.com/questions/267399/how-do-you-match-only-valid-roman-numerals-with-a-regular-expression
- roman = Regex(r"M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})")
- """
- compiledREtype = type(re.compile("[A-Z]"))
- def __init__( self, pattern, flags=0):
- """The parameters C{pattern} and C{flags} are passed to the C{re.compile()} function as-is. See the Python C{re} module for an explanation of the acceptable patterns and flags."""
- super(Regex,self).__init__()
-
- if isinstance(pattern, basestring):
- if not pattern:
- warnings.warn("null string passed to Regex; use Empty() instead",
- SyntaxWarning, stacklevel=2)
-
- self.pattern = pattern
- self.flags = flags
-
- try:
- self.re = re.compile(self.pattern, self.flags)
- self.reString = self.pattern
- except sre_constants.error:
- warnings.warn("invalid pattern (%s) passed to Regex" % pattern,
- SyntaxWarning, stacklevel=2)
- raise
-
- elif isinstance(pattern, Regex.compiledREtype):
- self.re = pattern
- self.pattern = \
- self.reString = str(pattern)
- self.flags = flags
-
- else:
- raise ValueError("Regex may only be constructed with a string or a compiled RE object")
-
- self.name = _ustr(self)
- self.errmsg = "Expected " + self.name
- self.mayIndexError = False
- self.mayReturnEmpty = True
-
- def parseImpl( self, instring, loc, doActions=True ):
- result = self.re.match(instring,loc)
- if not result:
- raise ParseException(instring, loc, self.errmsg, self)
-
- loc = result.end()
- d = result.groupdict()
- ret = ParseResults(result.group())
- if d:
- for k in d:
- ret[k] = d[k]
- return loc,ret
-
- def __str__( self ):
- try:
- return super(Regex,self).__str__()
- except Exception:
- pass
-
- if self.strRepr is None:
- self.strRepr = "Re:(%s)" % repr(self.pattern)
-
- return self.strRepr
-
-
-class QuotedString(Token):
- r"""
- Token for matching strings that are delimited by quoting characters.
-
- Defined with the following parameters:
- - quoteChar - string of one or more characters defining the quote delimiting string
- - escChar - character to escape quotes, typically backslash (default=C{None})
- - escQuote - special quote sequence to escape an embedded quote string (such as SQL's "" to escape an embedded ") (default=C{None})
- - multiline - boolean indicating whether quotes can span multiple lines (default=C{False})
- - unquoteResults - boolean indicating whether the matched text should be unquoted (default=C{True})
- - endQuoteChar - string of one or more characters defining the end of the quote delimited string (default=C{None} => same as quoteChar)
- - convertWhitespaceEscapes - convert escaped whitespace (C{'\t'}, C{'\n'}, etc.) to actual whitespace (default=C{True})
-
- Example::
- qs = QuotedString('"')
- print(qs.searchString('lsjdf "This is the quote" sldjf'))
- complex_qs = QuotedString('{{', endQuoteChar='}}')
- print(complex_qs.searchString('lsjdf {{This is the "quote"}} sldjf'))
- sql_qs = QuotedString('"', escQuote='""')
- print(sql_qs.searchString('lsjdf "This is the quote with ""embedded"" quotes" sldjf'))
- prints::
- [['This is the quote']]
- [['This is the "quote"']]
- [['This is the quote with "embedded" quotes']]
- """
- def __init__( self, quoteChar, escChar=None, escQuote=None, multiline=False, unquoteResults=True, endQuoteChar=None, convertWhitespaceEscapes=True):
- super(QuotedString,self).__init__()
-
- # remove white space from quote chars - wont work anyway
- quoteChar = quoteChar.strip()
- if not quoteChar:
- warnings.warn("quoteChar cannot be the empty string",SyntaxWarning,stacklevel=2)
- raise SyntaxError()
-
- if endQuoteChar is None:
- endQuoteChar = quoteChar
- else:
- endQuoteChar = endQuoteChar.strip()
- if not endQuoteChar:
- warnings.warn("endQuoteChar cannot be the empty string",SyntaxWarning,stacklevel=2)
- raise SyntaxError()
-
- self.quoteChar = quoteChar
- self.quoteCharLen = len(quoteChar)
- self.firstQuoteChar = quoteChar[0]
- self.endQuoteChar = endQuoteChar
- self.endQuoteCharLen = len(endQuoteChar)
- self.escChar = escChar
- self.escQuote = escQuote
- self.unquoteResults = unquoteResults
- self.convertWhitespaceEscapes = convertWhitespaceEscapes
-
- if multiline:
- self.flags = re.MULTILINE | re.DOTALL
- self.pattern = r'%s(?:[^%s%s]' % \
- ( re.escape(self.quoteChar),
- _escapeRegexRangeChars(self.endQuoteChar[0]),
- (escChar is not None and _escapeRegexRangeChars(escChar) or '') )
- else:
- self.flags = 0
- self.pattern = r'%s(?:[^%s\n\r%s]' % \
- ( re.escape(self.quoteChar),
- _escapeRegexRangeChars(self.endQuoteChar[0]),
- (escChar is not None and _escapeRegexRangeChars(escChar) or '') )
- if len(self.endQuoteChar) > 1:
- self.pattern += (
- '|(?:' + ')|(?:'.join("%s[^%s]" % (re.escape(self.endQuoteChar[:i]),
- _escapeRegexRangeChars(self.endQuoteChar[i]))
- for i in range(len(self.endQuoteChar)-1,0,-1)) + ')'
- )
- if escQuote:
- self.pattern += (r'|(?:%s)' % re.escape(escQuote))
- if escChar:
- self.pattern += (r'|(?:%s.)' % re.escape(escChar))
- self.escCharReplacePattern = re.escape(self.escChar)+"(.)"
- self.pattern += (r')*%s' % re.escape(self.endQuoteChar))
-
- try:
- self.re = re.compile(self.pattern, self.flags)
- self.reString = self.pattern
- except sre_constants.error:
- warnings.warn("invalid pattern (%s) passed to Regex" % self.pattern,
- SyntaxWarning, stacklevel=2)
- raise
-
- self.name = _ustr(self)
- self.errmsg = "Expected " + self.name
- self.mayIndexError = False
- self.mayReturnEmpty = True
-
- def parseImpl( self, instring, loc, doActions=True ):
- result = instring[loc] == self.firstQuoteChar and self.re.match(instring,loc) or None
- if not result:
- raise ParseException(instring, loc, self.errmsg, self)
-
- loc = result.end()
- ret = result.group()
-
- if self.unquoteResults:
-
- # strip off quotes
- ret = ret[self.quoteCharLen:-self.endQuoteCharLen]
-
- if isinstance(ret,basestring):
- # replace escaped whitespace
- if '\\' in ret and self.convertWhitespaceEscapes:
- ws_map = {
- r'\t' : '\t',
- r'\n' : '\n',
- r'\f' : '\f',
- r'\r' : '\r',
- }
- for wslit,wschar in ws_map.items():
- ret = ret.replace(wslit, wschar)
-
- # replace escaped characters
- if self.escChar:
- ret = re.sub(self.escCharReplacePattern, r"\g<1>", ret)
-
- # replace escaped quotes
- if self.escQuote:
- ret = ret.replace(self.escQuote, self.endQuoteChar)
-
- return loc, ret
-
- def __str__( self ):
- try:
- return super(QuotedString,self).__str__()
- except Exception:
- pass
-
- if self.strRepr is None:
- self.strRepr = "quoted string, starting with %s ending with %s" % (self.quoteChar, self.endQuoteChar)
-
- return self.strRepr
-
-
-class CharsNotIn(Token):
- """
- Token for matching words composed of characters I{not} in a given set (will
- include whitespace in matched characters if not listed in the provided exclusion set - see example).
- Defined with string containing all disallowed characters, and an optional
- minimum, maximum, and/or exact length. The default value for C{min} is 1 (a
- minimum value < 1 is not valid); the default values for C{max} and C{exact}
- are 0, meaning no maximum or exact length restriction.
-
- Example::
- # define a comma-separated-value as anything that is not a ','
- csv_value = CharsNotIn(',')
- print(delimitedList(csv_value).parseString("dkls,lsdkjf,s12 34,@!#,213"))
- prints::
- ['dkls', 'lsdkjf', 's12 34', '@!#', '213']
- """
- def __init__( self, notChars, min=1, max=0, exact=0 ):
- super(CharsNotIn,self).__init__()
- self.skipWhitespace = False
- self.notChars = notChars
-
- if min < 1:
- raise ValueError("cannot specify a minimum length < 1; use Optional(CharsNotIn()) if zero-length char group is permitted")
-
- self.minLen = min
-
- if max > 0:
- self.maxLen = max
- else:
- self.maxLen = _MAX_INT
-
- if exact > 0:
- self.maxLen = exact
- self.minLen = exact
-
- self.name = _ustr(self)
- self.errmsg = "Expected " + self.name
- self.mayReturnEmpty = ( self.minLen == 0 )
- self.mayIndexError = False
-
- def parseImpl( self, instring, loc, doActions=True ):
- if instring[loc] in self.notChars:
- raise ParseException(instring, loc, self.errmsg, self)
-
- start = loc
- loc += 1
- notchars = self.notChars
- maxlen = min( start+self.maxLen, len(instring) )
- while loc < maxlen and \
- (instring[loc] not in notchars):
- loc += 1
-
- if loc - start < self.minLen:
- raise ParseException(instring, loc, self.errmsg, self)
-
- return loc, instring[start:loc]
-
- def __str__( self ):
- try:
- return super(CharsNotIn, self).__str__()
- except Exception:
- pass
-
- if self.strRepr is None:
- if len(self.notChars) > 4:
- self.strRepr = "!W:(%s...)" % self.notChars[:4]
- else:
- self.strRepr = "!W:(%s)" % self.notChars
-
- return self.strRepr
-
-class White(Token):
- """
- Special matching class for matching whitespace. Normally, whitespace is ignored
- by pyparsing grammars. This class is included when some whitespace structures
- are significant. Define with a string containing the whitespace characters to be
- matched; default is C{" \\t\\r\\n"}. Also takes optional C{min}, C{max}, and C{exact} arguments,
- as defined for the C{L{Word}} class.
- """
- whiteStrs = {
- " " : "<SPC>",
- "\t": "<TAB>",
- "\n": "<LF>",
- "\r": "<CR>",
- "\f": "<FF>",
- }
- def __init__(self, ws=" \t\r\n", min=1, max=0, exact=0):
- super(White,self).__init__()
- self.matchWhite = ws
- self.setWhitespaceChars( "".join(c for c in self.whiteChars if c not in self.matchWhite) )
- #~ self.leaveWhitespace()
- self.name = ("".join(White.whiteStrs[c] for c in self.matchWhite))
- self.mayReturnEmpty = True
- self.errmsg = "Expected " + self.name
-
- self.minLen = min
-
- if max > 0:
- self.maxLen = max
- else:
- self.maxLen = _MAX_INT
-
- if exact > 0:
- self.maxLen = exact
- self.minLen = exact
-
- def parseImpl( self, instring, loc, doActions=True ):
- if not(instring[ loc ] in self.matchWhite):
- raise ParseException(instring, loc, self.errmsg, self)
- start = loc
- loc += 1
- maxloc = start + self.maxLen
- maxloc = min( maxloc, len(instring) )
- while loc < maxloc and instring[loc] in self.matchWhite:
- loc += 1
-
- if loc - start < self.minLen:
- raise ParseException(instring, loc, self.errmsg, self)
-
- return loc, instring[start:loc]
-
-
-class _PositionToken(Token):
- def __init__( self ):
- super(_PositionToken,self).__init__()
- self.name=self.__class__.__name__
- self.mayReturnEmpty = True
- self.mayIndexError = False
-
-class GoToColumn(_PositionToken):
- """
- Token to advance to a specific column of input text; useful for tabular report scraping.
- """
- def __init__( self, colno ):
- super(GoToColumn,self).__init__()
- self.col = colno
-
- def preParse( self, instring, loc ):
- if col(loc,instring) != self.col:
- instrlen = len(instring)
- if self.ignoreExprs:
- loc = self._skipIgnorables( instring, loc )
- while loc < instrlen and instring[loc].isspace() and col( loc, instring ) != self.col :
- loc += 1
- return loc
-
- def parseImpl( self, instring, loc, doActions=True ):
- thiscol = col( loc, instring )
- if thiscol > self.col:
- raise ParseException( instring, loc, "Text not in expected column", self )
- newloc = loc + self.col - thiscol
- ret = instring[ loc: newloc ]
- return newloc, ret
-
-
-class LineStart(_PositionToken):
- """
- Matches if current position is at the beginning of a line within the parse string
-
- Example::
-
- test = '''\
- AAA this line
- AAA and this line
- AAA but not this one
- B AAA and definitely not this one
- '''
-
- for t in (LineStart() + 'AAA' + restOfLine).searchString(test):
- print(t)
-
- Prints::
- ['AAA', ' this line']
- ['AAA', ' and this line']
-
- """
- def __init__( self ):
- super(LineStart,self).__init__()
- self.errmsg = "Expected start of line"
-
- def parseImpl( self, instring, loc, doActions=True ):
- if col(loc, instring) == 1:
- return loc, []
- raise ParseException(instring, loc, self.errmsg, self)
-
-class LineEnd(_PositionToken):
- """
- Matches if current position is at the end of a line within the parse string
- """
- def __init__( self ):
- super(LineEnd,self).__init__()
- self.setWhitespaceChars( ParserElement.DEFAULT_WHITE_CHARS.replace("\n","") )
- self.errmsg = "Expected end of line"
-
- def parseImpl( self, instring, loc, doActions=True ):
- if loc<len(instring):
- if instring[loc] == "\n":
- return loc+1, "\n"
- else:
- raise ParseException(instring, loc, self.errmsg, self)
- elif loc == len(instring):
- return loc+1, []
- else:
- raise ParseException(instring, loc, self.errmsg, self)
-
-class StringStart(_PositionToken):
- """
- Matches if current position is at the beginning of the parse string
- """
- def __init__( self ):
- super(StringStart,self).__init__()
- self.errmsg = "Expected start of text"
-
- def parseImpl( self, instring, loc, doActions=True ):
- if loc != 0:
- # see if entire string up to here is just whitespace and ignoreables
- if loc != self.preParse( instring, 0 ):
- raise ParseException(instring, loc, self.errmsg, self)
- return loc, []
-
-class StringEnd(_PositionToken):
- """
- Matches if current position is at the end of the parse string
- """
- def __init__( self ):
- super(StringEnd,self).__init__()
- self.errmsg = "Expected end of text"
-
- def parseImpl( self, instring, loc, doActions=True ):
- if loc < len(instring):
- raise ParseException(instring, loc, self.errmsg, self)
- elif loc == len(instring):
- return loc+1, []
- elif loc > len(instring):
- return loc, []
- else:
- raise ParseException(instring, loc, self.errmsg, self)
-
-class WordStart(_PositionToken):
- """
- Matches if the current position is at the beginning of a Word, and
- is not preceded by any character in a given set of C{wordChars}
- (default=C{printables}). To emulate the C{\b} behavior of regular expressions,
- use C{WordStart(alphanums)}. C{WordStart} will also match at the beginning of
- the string being parsed, or at the beginning of a line.
- """
- def __init__(self, wordChars = printables):
- super(WordStart,self).__init__()
- self.wordChars = set(wordChars)
- self.errmsg = "Not at the start of a word"
-
- def parseImpl(self, instring, loc, doActions=True ):
- if loc != 0:
- if (instring[loc-1] in self.wordChars or
- instring[loc] not in self.wordChars):
- raise ParseException(instring, loc, self.errmsg, self)
- return loc, []
-
-class WordEnd(_PositionToken):
- """
- Matches if the current position is at the end of a Word, and
- is not followed by any character in a given set of C{wordChars}
- (default=C{printables}). To emulate the C{\b} behavior of regular expressions,
- use C{WordEnd(alphanums)}. C{WordEnd} will also match at the end of
- the string being parsed, or at the end of a line.
- """
- def __init__(self, wordChars = printables):
- super(WordEnd,self).__init__()
- self.wordChars = set(wordChars)
- self.skipWhitespace = False
- self.errmsg = "Not at the end of a word"
-
- def parseImpl(self, instring, loc, doActions=True ):
- instrlen = len(instring)
- if instrlen>0 and loc<instrlen:
- if (instring[loc] in self.wordChars or
- instring[loc-1] not in self.wordChars):
- raise ParseException(instring, loc, self.errmsg, self)
- return loc, []
-
-
-class ParseExpression(ParserElement):
- """
- Abstract subclass of ParserElement, for combining and post-processing parsed tokens.
- """
- def __init__( self, exprs, savelist = False ):
- super(ParseExpression,self).__init__(savelist)
- if isinstance( exprs, _generatorType ):
- exprs = list(exprs)
-
- if isinstance( exprs, basestring ):
- self.exprs = [ ParserElement._literalStringClass( exprs ) ]
- elif isinstance( exprs, Iterable ):
- exprs = list(exprs)
- # if sequence of strings provided, wrap with Literal
- if all(isinstance(expr, basestring) for expr in exprs):
- exprs = map(ParserElement._literalStringClass, exprs)
- self.exprs = list(exprs)
- else:
- try:
- self.exprs = list( exprs )
- except TypeError:
- self.exprs = [ exprs ]
- self.callPreparse = False
-
- def __getitem__( self, i ):
- return self.exprs[i]
-
- def append( self, other ):
- self.exprs.append( other )
- self.strRepr = None
- return self
-
- def leaveWhitespace( self ):
- """Extends C{leaveWhitespace} defined in base class, and also invokes C{leaveWhitespace} on
- all contained expressions."""
- self.skipWhitespace = False
- self.exprs = [ e.copy() for e in self.exprs ]
- for e in self.exprs:
- e.leaveWhitespace()
- return self
-
- def ignore( self, other ):
- if isinstance( other, Suppress ):
- if other not in self.ignoreExprs:
- super( ParseExpression, self).ignore( other )
- for e in self.exprs:
- e.ignore( self.ignoreExprs[-1] )
- else:
- super( ParseExpression, self).ignore( other )
- for e in self.exprs:
- e.ignore( self.ignoreExprs[-1] )
- return self
-
- def __str__( self ):
- try:
- return super(ParseExpression,self).__str__()
- except Exception:
- pass
-
- if self.strRepr is None:
- self.strRepr = "%s:(%s)" % ( self.__class__.__name__, _ustr(self.exprs) )
- return self.strRepr
-
- def streamline( self ):
- super(ParseExpression,self).streamline()
-
- for e in self.exprs:
- e.streamline()
-
- # collapse nested And's of the form And( And( And( a,b), c), d) to And( a,b,c,d )
- # but only if there are no parse actions or resultsNames on the nested And's
- # (likewise for Or's and MatchFirst's)
- if ( len(self.exprs) == 2 ):
- other = self.exprs[0]
- if ( isinstance( other, self.__class__ ) and
- not(other.parseAction) and
- other.resultsName is None and
- not other.debug ):
- self.exprs = other.exprs[:] + [ self.exprs[1] ]
- self.strRepr = None
- self.mayReturnEmpty |= other.mayReturnEmpty
- self.mayIndexError |= other.mayIndexError
-
- other = self.exprs[-1]
- if ( isinstance( other, self.__class__ ) and
- not(other.parseAction) and
- other.resultsName is None and
- not other.debug ):
- self.exprs = self.exprs[:-1] + other.exprs[:]
- self.strRepr = None
- self.mayReturnEmpty |= other.mayReturnEmpty
- self.mayIndexError |= other.mayIndexError
-
- self.errmsg = "Expected " + _ustr(self)
-
- return self
-
- def setResultsName( self, name, listAllMatches=False ):
- ret = super(ParseExpression,self).setResultsName(name,listAllMatches)
- return ret
-
- def validate( self, validateTrace=[] ):
- tmp = validateTrace[:]+[self]
- for e in self.exprs:
- e.validate(tmp)
- self.checkRecursion( [] )
-
- def copy(self):
- ret = super(ParseExpression,self).copy()
- ret.exprs = [e.copy() for e in self.exprs]
- return ret
-
-class And(ParseExpression):
- """
- Requires all given C{ParseExpression}s to be found in the given order.
- Expressions may be separated by whitespace.
- May be constructed using the C{'+'} operator.
- May also be constructed using the C{'-'} operator, which will suppress backtracking.
-
- Example::
- integer = Word(nums)
- name_expr = OneOrMore(Word(alphas))
-
- expr = And([integer("id"),name_expr("name"),integer("age")])
- # more easily written as:
- expr = integer("id") + name_expr("name") + integer("age")
- """
-
- class _ErrorStop(Empty):
- def __init__(self, *args, **kwargs):
- super(And._ErrorStop,self).__init__(*args, **kwargs)
- self.name = '-'
- self.leaveWhitespace()
-
- def __init__( self, exprs, savelist = True ):
- super(And,self).__init__(exprs, savelist)
- self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs)
- self.setWhitespaceChars( self.exprs[0].whiteChars )
- self.skipWhitespace = self.exprs[0].skipWhitespace
- self.callPreparse = True
-
- def parseImpl( self, instring, loc, doActions=True ):
- # pass False as last arg to _parse for first element, since we already
- # pre-parsed the string as part of our And pre-parsing
- loc, resultlist = self.exprs[0]._parse( instring, loc, doActions, callPreParse=False )
- errorStop = False
- for e in self.exprs[1:]:
- if isinstance(e, And._ErrorStop):
- errorStop = True
- continue
- if errorStop:
- try:
- loc, exprtokens = e._parse( instring, loc, doActions )
- except ParseSyntaxException:
- raise
- except ParseBaseException as pe:
- pe.__traceback__ = None
- raise ParseSyntaxException._from_exception(pe)
- except IndexError:
- raise ParseSyntaxException(instring, len(instring), self.errmsg, self)
- else:
- loc, exprtokens = e._parse( instring, loc, doActions )
- if exprtokens or exprtokens.haskeys():
- resultlist += exprtokens
- return loc, resultlist
-
- def __iadd__(self, other ):
- if isinstance( other, basestring ):
- other = ParserElement._literalStringClass( other )
- return self.append( other ) #And( [ self, other ] )
-
- def checkRecursion( self, parseElementList ):
- subRecCheckList = parseElementList[:] + [ self ]
- for e in self.exprs:
- e.checkRecursion( subRecCheckList )
- if not e.mayReturnEmpty:
- break
-
- def __str__( self ):
- if hasattr(self,"name"):
- return self.name
-
- if self.strRepr is None:
- self.strRepr = "{" + " ".join(_ustr(e) for e in self.exprs) + "}"
-
- return self.strRepr
-
-
-class Or(ParseExpression):
- """
- Requires that at least one C{ParseExpression} is found.
- If two expressions match, the expression that matches the longest string will be used.
- May be constructed using the C{'^'} operator.
-
- Example::
- # construct Or using '^' operator
-
- number = Word(nums) ^ Combine(Word(nums) + '.' + Word(nums))
- print(number.searchString("123 3.1416 789"))
- prints::
- [['123'], ['3.1416'], ['789']]
- """
- def __init__( self, exprs, savelist = False ):
- super(Or,self).__init__(exprs, savelist)
- if self.exprs:
- self.mayReturnEmpty = any(e.mayReturnEmpty for e in self.exprs)
- else:
- self.mayReturnEmpty = True
-
- def parseImpl( self, instring, loc, doActions=True ):
- maxExcLoc = -1
- maxException = None
- matches = []
- for e in self.exprs:
- try:
- loc2 = e.tryParse( instring, loc )
- except ParseException as err:
- err.__traceback__ = None
- if err.loc > maxExcLoc:
- maxException = err
- maxExcLoc = err.loc
- except IndexError:
- if len(instring) > maxExcLoc:
- maxException = ParseException(instring,len(instring),e.errmsg,self)
- maxExcLoc = len(instring)
- else:
- # save match among all matches, to retry longest to shortest
- matches.append((loc2, e))
-
- if matches:
- matches.sort(key=lambda x: -x[0])
- for _,e in matches:
- try:
- return e._parse( instring, loc, doActions )
- except ParseException as err:
- err.__traceback__ = None
- if err.loc > maxExcLoc:
- maxException = err
- maxExcLoc = err.loc
-
- if maxException is not None:
- maxException.msg = self.errmsg
- raise maxException
- else:
- raise ParseException(instring, loc, "no defined alternatives to match", self)
-
-
- def __ixor__(self, other ):
- if isinstance( other, basestring ):
- other = ParserElement._literalStringClass( other )
- return self.append( other ) #Or( [ self, other ] )
-
- def __str__( self ):
- if hasattr(self,"name"):
- return self.name
-
- if self.strRepr is None:
- self.strRepr = "{" + " ^ ".join(_ustr(e) for e in self.exprs) + "}"
-
- return self.strRepr
-
- def checkRecursion( self, parseElementList ):
- subRecCheckList = parseElementList[:] + [ self ]
- for e in self.exprs:
- e.checkRecursion( subRecCheckList )
-
-
-class MatchFirst(ParseExpression):
- """
- Requires that at least one C{ParseExpression} is found.
- If two expressions match, the first one listed is the one that will match.
- May be constructed using the C{'|'} operator.
-
- Example::
- # construct MatchFirst using '|' operator
-
- # watch the order of expressions to match
- number = Word(nums) | Combine(Word(nums) + '.' + Word(nums))
- print(number.searchString("123 3.1416 789")) # Fail! -> [['123'], ['3'], ['1416'], ['789']]
-
- # put more selective expression first
- number = Combine(Word(nums) + '.' + Word(nums)) | Word(nums)
- print(number.searchString("123 3.1416 789")) # Better -> [['123'], ['3.1416'], ['789']]
- """
- def __init__( self, exprs, savelist = False ):
- super(MatchFirst,self).__init__(exprs, savelist)
- if self.exprs:
- self.mayReturnEmpty = any(e.mayReturnEmpty for e in self.exprs)
- else:
- self.mayReturnEmpty = True
-
- def parseImpl( self, instring, loc, doActions=True ):
- maxExcLoc = -1
- maxException = None
- for e in self.exprs:
- try:
- ret = e._parse( instring, loc, doActions )
- return ret
- except ParseException as err:
- if err.loc > maxExcLoc:
- maxException = err
- maxExcLoc = err.loc
- except IndexError:
- if len(instring) > maxExcLoc:
- maxException = ParseException(instring,len(instring),e.errmsg,self)
- maxExcLoc = len(instring)
-
- # only got here if no expression matched, raise exception for match that made it the furthest
- else:
- if maxException is not None:
- maxException.msg = self.errmsg
- raise maxException
- else:
- raise ParseException(instring, loc, "no defined alternatives to match", self)
-
- def __ior__(self, other ):
- if isinstance( other, basestring ):
- other = ParserElement._literalStringClass( other )
- return self.append( other ) #MatchFirst( [ self, other ] )
-
- def __str__( self ):
- if hasattr(self,"name"):
- return self.name
-
- if self.strRepr is None:
- self.strRepr = "{" + " | ".join(_ustr(e) for e in self.exprs) + "}"
-
- return self.strRepr
-
- def checkRecursion( self, parseElementList ):
- subRecCheckList = parseElementList[:] + [ self ]
- for e in self.exprs:
- e.checkRecursion( subRecCheckList )
-
-
-class Each(ParseExpression):
- """
- Requires all given C{ParseExpression}s to be found, but in any order.
- Expressions may be separated by whitespace.
- May be constructed using the C{'&'} operator.
-
- Example::
- color = oneOf("RED ORANGE YELLOW GREEN BLUE PURPLE BLACK WHITE BROWN")
- shape_type = oneOf("SQUARE CIRCLE TRIANGLE STAR HEXAGON OCTAGON")
- integer = Word(nums)
- shape_attr = "shape:" + shape_type("shape")
- posn_attr = "posn:" + Group(integer("x") + ',' + integer("y"))("posn")
- color_attr = "color:" + color("color")
- size_attr = "size:" + integer("size")
-
- # use Each (using operator '&') to accept attributes in any order
- # (shape and posn are required, color and size are optional)
- shape_spec = shape_attr & posn_attr & Optional(color_attr) & Optional(size_attr)
-
- shape_spec.runTests('''
- shape: SQUARE color: BLACK posn: 100, 120
- shape: CIRCLE size: 50 color: BLUE posn: 50,80
- color:GREEN size:20 shape:TRIANGLE posn:20,40
- '''
- )
- prints::
- shape: SQUARE color: BLACK posn: 100, 120
- ['shape:', 'SQUARE', 'color:', 'BLACK', 'posn:', ['100', ',', '120']]
- - color: BLACK
- - posn: ['100', ',', '120']
- - x: 100
- - y: 120
- - shape: SQUARE
-
-
- shape: CIRCLE size: 50 color: BLUE posn: 50,80
- ['shape:', 'CIRCLE', 'size:', '50', 'color:', 'BLUE', 'posn:', ['50', ',', '80']]
- - color: BLUE
- - posn: ['50', ',', '80']
- - x: 50
- - y: 80
- - shape: CIRCLE
- - size: 50
-
-
- color: GREEN size: 20 shape: TRIANGLE posn: 20,40
- ['color:', 'GREEN', 'size:', '20', 'shape:', 'TRIANGLE', 'posn:', ['20', ',', '40']]
- - color: GREEN
- - posn: ['20', ',', '40']
- - x: 20
- - y: 40
- - shape: TRIANGLE
- - size: 20
- """
- def __init__( self, exprs, savelist = True ):
- super(Each,self).__init__(exprs, savelist)
- self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs)
- self.skipWhitespace = True
- self.initExprGroups = True
-
- def parseImpl( self, instring, loc, doActions=True ):
- if self.initExprGroups:
- self.opt1map = dict((id(e.expr),e) for e in self.exprs if isinstance(e,Optional))
- opt1 = [ e.expr for e in self.exprs if isinstance(e,Optional) ]
- opt2 = [ e for e in self.exprs if e.mayReturnEmpty and not isinstance(e,Optional)]
- self.optionals = opt1 + opt2
- self.multioptionals = [ e.expr for e in self.exprs if isinstance(e,ZeroOrMore) ]
- self.multirequired = [ e.expr for e in self.exprs if isinstance(e,OneOrMore) ]
- self.required = [ e for e in self.exprs if not isinstance(e,(Optional,ZeroOrMore,OneOrMore)) ]
- self.required += self.multirequired
- self.initExprGroups = False
- tmpLoc = loc
- tmpReqd = self.required[:]
- tmpOpt = self.optionals[:]
- matchOrder = []
-
- keepMatching = True
- while keepMatching:
- tmpExprs = tmpReqd + tmpOpt + self.multioptionals + self.multirequired
- failed = []
- for e in tmpExprs:
- try:
- tmpLoc = e.tryParse( instring, tmpLoc )
- except ParseException:
- failed.append(e)
- else:
- matchOrder.append(self.opt1map.get(id(e),e))
- if e in tmpReqd:
- tmpReqd.remove(e)
- elif e in tmpOpt:
- tmpOpt.remove(e)
- if len(failed) == len(tmpExprs):
- keepMatching = False
-
- if tmpReqd:
- missing = ", ".join(_ustr(e) for e in tmpReqd)
- raise ParseException(instring,loc,"Missing one or more required elements (%s)" % missing )
-
- # add any unmatched Optionals, in case they have default values defined
- matchOrder += [e for e in self.exprs if isinstance(e,Optional) and e.expr in tmpOpt]
-
- resultlist = []
- for e in matchOrder:
- loc,results = e._parse(instring,loc,doActions)
- resultlist.append(results)
-
- finalResults = sum(resultlist, ParseResults([]))
- return loc, finalResults
-
- def __str__( self ):
- if hasattr(self,"name"):
- return self.name
-
- if self.strRepr is None:
- self.strRepr = "{" + " & ".join(_ustr(e) for e in self.exprs) + "}"
-
- return self.strRepr
-
- def checkRecursion( self, parseElementList ):
- subRecCheckList = parseElementList[:] + [ self ]
- for e in self.exprs:
- e.checkRecursion( subRecCheckList )
-
-
-class ParseElementEnhance(ParserElement):
- """
- Abstract subclass of C{ParserElement}, for combining and post-processing parsed tokens.
- """
- def __init__( self, expr, savelist=False ):
- super(ParseElementEnhance,self).__init__(savelist)
- if isinstance( expr, basestring ):
- if issubclass(ParserElement._literalStringClass, Token):
- expr = ParserElement._literalStringClass(expr)
- else:
- expr = ParserElement._literalStringClass(Literal(expr))
- self.expr = expr
- self.strRepr = None
- if expr is not None:
- self.mayIndexError = expr.mayIndexError
- self.mayReturnEmpty = expr.mayReturnEmpty
- self.setWhitespaceChars( expr.whiteChars )
- self.skipWhitespace = expr.skipWhitespace
- self.saveAsList = expr.saveAsList
- self.callPreparse = expr.callPreparse
- self.ignoreExprs.extend(expr.ignoreExprs)
-
- def parseImpl( self, instring, loc, doActions=True ):
- if self.expr is not None:
- return self.expr._parse( instring, loc, doActions, callPreParse=False )
- else:
- raise ParseException("",loc,self.errmsg,self)
-
- def leaveWhitespace( self ):
- self.skipWhitespace = False
- self.expr = self.expr.copy()
- if self.expr is not None:
- self.expr.leaveWhitespace()
- return self
-
- def ignore( self, other ):
- if isinstance( other, Suppress ):
- if other not in self.ignoreExprs:
- super( ParseElementEnhance, self).ignore( other )
- if self.expr is not None:
- self.expr.ignore( self.ignoreExprs[-1] )
- else:
- super( ParseElementEnhance, self).ignore( other )
- if self.expr is not None:
- self.expr.ignore( self.ignoreExprs[-1] )
- return self
-
- def streamline( self ):
- super(ParseElementEnhance,self).streamline()
- if self.expr is not None:
- self.expr.streamline()
- return self
-
- def checkRecursion( self, parseElementList ):
- if self in parseElementList:
- raise RecursiveGrammarException( parseElementList+[self] )
- subRecCheckList = parseElementList[:] + [ self ]
- if self.expr is not None:
- self.expr.checkRecursion( subRecCheckList )
-
- def validate( self, validateTrace=[] ):
- tmp = validateTrace[:]+[self]
- if self.expr is not None:
- self.expr.validate(tmp)
- self.checkRecursion( [] )
-
- def __str__( self ):
- try:
- return super(ParseElementEnhance,self).__str__()
- except Exception:
- pass
-
- if self.strRepr is None and self.expr is not None:
- self.strRepr = "%s:(%s)" % ( self.__class__.__name__, _ustr(self.expr) )
- return self.strRepr
-
-
-class FollowedBy(ParseElementEnhance):
- """
- Lookahead matching of the given parse expression. C{FollowedBy}
- does I{not} advance the parsing position within the input string, it only
- verifies that the specified parse expression matches at the current
- position. C{FollowedBy} always returns a null token list.
-
- Example::
- # use FollowedBy to match a label only if it is followed by a ':'
- data_word = Word(alphas)
- label = data_word + FollowedBy(':')
- attr_expr = Group(label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join))
-
- OneOrMore(attr_expr).parseString("shape: SQUARE color: BLACK posn: upper left").pprint()
- prints::
- [['shape', 'SQUARE'], ['color', 'BLACK'], ['posn', 'upper left']]
- """
- def __init__( self, expr ):
- super(FollowedBy,self).__init__(expr)
- self.mayReturnEmpty = True
-
- def parseImpl( self, instring, loc, doActions=True ):
- self.expr.tryParse( instring, loc )
- return loc, []
-
-
-class NotAny(ParseElementEnhance):
- """
- Lookahead to disallow matching with the given parse expression. C{NotAny}
- does I{not} advance the parsing position within the input string, it only
- verifies that the specified parse expression does I{not} match at the current
- position. Also, C{NotAny} does I{not} skip over leading whitespace. C{NotAny}
- always returns a null token list. May be constructed using the '~' operator.
-
- Example::
-
- """
- def __init__( self, expr ):
- super(NotAny,self).__init__(expr)
- #~ self.leaveWhitespace()
- self.skipWhitespace = False # do NOT use self.leaveWhitespace(), don't want to propagate to exprs
- self.mayReturnEmpty = True
- self.errmsg = "Found unwanted token, "+_ustr(self.expr)
-
- def parseImpl( self, instring, loc, doActions=True ):
- if self.expr.canParseNext(instring, loc):
- raise ParseException(instring, loc, self.errmsg, self)
- return loc, []
-
- def __str__( self ):
- if hasattr(self,"name"):
- return self.name
-
- if self.strRepr is None:
- self.strRepr = "~{" + _ustr(self.expr) + "}"
-
- return self.strRepr
-
-class _MultipleMatch(ParseElementEnhance):
- def __init__( self, expr, stopOn=None):
- super(_MultipleMatch, self).__init__(expr)
- self.saveAsList = True
- ender = stopOn
- if isinstance(ender, basestring):
- ender = ParserElement._literalStringClass(ender)
- self.not_ender = ~ender if ender is not None else None
-
- def parseImpl( self, instring, loc, doActions=True ):
- self_expr_parse = self.expr._parse
- self_skip_ignorables = self._skipIgnorables
- check_ender = self.not_ender is not None
- if check_ender:
- try_not_ender = self.not_ender.tryParse
-
- # must be at least one (but first see if we are the stopOn sentinel;
- # if so, fail)
- if check_ender:
- try_not_ender(instring, loc)
- loc, tokens = self_expr_parse( instring, loc, doActions, callPreParse=False )
- try:
- hasIgnoreExprs = (not not self.ignoreExprs)
- while 1:
- if check_ender:
- try_not_ender(instring, loc)
- if hasIgnoreExprs:
- preloc = self_skip_ignorables( instring, loc )
- else:
- preloc = loc
- loc, tmptokens = self_expr_parse( instring, preloc, doActions )
- if tmptokens or tmptokens.haskeys():
- tokens += tmptokens
- except (ParseException,IndexError):
- pass
-
- return loc, tokens
-
-class OneOrMore(_MultipleMatch):
- """
- Repetition of one or more of the given expression.
-
- Parameters:
- - expr - expression that must match one or more times
- - stopOn - (default=C{None}) - expression for a terminating sentinel
- (only required if the sentinel would ordinarily match the repetition
- expression)
-
- Example::
- data_word = Word(alphas)
- label = data_word + FollowedBy(':')
- attr_expr = Group(label + Suppress(':') + OneOrMore(data_word).setParseAction(' '.join))
-
- text = "shape: SQUARE posn: upper left color: BLACK"
- OneOrMore(attr_expr).parseString(text).pprint() # Fail! read 'color' as data instead of next label -> [['shape', 'SQUARE color']]
-
- # use stopOn attribute for OneOrMore to avoid reading label string as part of the data
- attr_expr = Group(label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join))
- OneOrMore(attr_expr).parseString(text).pprint() # Better -> [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'BLACK']]
-
- # could also be written as
- (attr_expr * (1,)).parseString(text).pprint()
- """
-
- def __str__( self ):
- if hasattr(self,"name"):
- return self.name
-
- if self.strRepr is None:
- self.strRepr = "{" + _ustr(self.expr) + "}..."
-
- return self.strRepr
-
-class ZeroOrMore(_MultipleMatch):
- """
- Optional repetition of zero or more of the given expression.
-
- Parameters:
- - expr - expression that must match zero or more times
- - stopOn - (default=C{None}) - expression for a terminating sentinel
- (only required if the sentinel would ordinarily match the repetition
- expression)
-
- Example: similar to L{OneOrMore}
- """
- def __init__( self, expr, stopOn=None):
- super(ZeroOrMore,self).__init__(expr, stopOn=stopOn)
- self.mayReturnEmpty = True
-
- def parseImpl( self, instring, loc, doActions=True ):
- try:
- return super(ZeroOrMore, self).parseImpl(instring, loc, doActions)
- except (ParseException,IndexError):
- return loc, []
-
- def __str__( self ):
- if hasattr(self,"name"):
- return self.name
-
- if self.strRepr is None:
- self.strRepr = "[" + _ustr(self.expr) + "]..."
-
- return self.strRepr
-
-class _NullToken(object):
- def __bool__(self):
- return False
- __nonzero__ = __bool__
- def __str__(self):
- return ""
-
-_optionalNotMatched = _NullToken()
-class Optional(ParseElementEnhance):
- """
- Optional matching of the given expression.
-
- Parameters:
- - expr - expression that must match zero or more times
- - default (optional) - value to be returned if the optional expression is not found.
-
- Example::
- # US postal code can be a 5-digit zip, plus optional 4-digit qualifier
- zip = Combine(Word(nums, exact=5) + Optional('-' + Word(nums, exact=4)))
- zip.runTests('''
- # traditional ZIP code
- 12345
-
- # ZIP+4 form
- 12101-0001
-
- # invalid ZIP
- 98765-
- ''')
- prints::
- # traditional ZIP code
- 12345
- ['12345']
-
- # ZIP+4 form
- 12101-0001
- ['12101-0001']
-
- # invalid ZIP
- 98765-
- ^
- FAIL: Expected end of text (at char 5), (line:1, col:6)
- """
- def __init__( self, expr, default=_optionalNotMatched ):
- super(Optional,self).__init__( expr, savelist=False )
- self.saveAsList = self.expr.saveAsList
- self.defaultValue = default
- self.mayReturnEmpty = True
-
- def parseImpl( self, instring, loc, doActions=True ):
- try:
- loc, tokens = self.expr._parse( instring, loc, doActions, callPreParse=False )
- except (ParseException,IndexError):
- if self.defaultValue is not _optionalNotMatched:
- if self.expr.resultsName:
- tokens = ParseResults([ self.defaultValue ])
- tokens[self.expr.resultsName] = self.defaultValue
- else:
- tokens = [ self.defaultValue ]
- else:
- tokens = []
- return loc, tokens
-
- def __str__( self ):
- if hasattr(self,"name"):
- return self.name
-
- if self.strRepr is None:
- self.strRepr = "[" + _ustr(self.expr) + "]"
-
- return self.strRepr
-
-class SkipTo(ParseElementEnhance):
- """
- Token for skipping over all undefined text until the matched expression is found.
-
- Parameters:
- - expr - target expression marking the end of the data to be skipped
- - include - (default=C{False}) if True, the target expression is also parsed
- (the skipped text and target expression are returned as a 2-element list).
- - ignore - (default=C{None}) used to define grammars (typically quoted strings and
- comments) that might contain false matches to the target expression
- - failOn - (default=C{None}) define expressions that are not allowed to be
- included in the skipped test; if found before the target expression is found,
- the SkipTo is not a match
-
- Example::
- report = '''
- Outstanding Issues Report - 1 Jan 2000
-
- # | Severity | Description | Days Open
- -----+----------+-------------------------------------------+-----------
- 101 | Critical | Intermittent system crash | 6
- 94 | Cosmetic | Spelling error on Login ('log|n') | 14
- 79 | Minor | System slow when running too many reports | 47
- '''
- integer = Word(nums)
- SEP = Suppress('|')
- # use SkipTo to simply match everything up until the next SEP
- # - ignore quoted strings, so that a '|' character inside a quoted string does not match
- # - parse action will call token.strip() for each matched token, i.e., the description body
- string_data = SkipTo(SEP, ignore=quotedString)
- string_data.setParseAction(tokenMap(str.strip))
- ticket_expr = (integer("issue_num") + SEP
- + string_data("sev") + SEP
- + string_data("desc") + SEP
- + integer("days_open"))
-
- for tkt in ticket_expr.searchString(report):
- print tkt.dump()
- prints::
- ['101', 'Critical', 'Intermittent system crash', '6']
- - days_open: 6
- - desc: Intermittent system crash
- - issue_num: 101
- - sev: Critical
- ['94', 'Cosmetic', "Spelling error on Login ('log|n')", '14']
- - days_open: 14
- - desc: Spelling error on Login ('log|n')
- - issue_num: 94
- - sev: Cosmetic
- ['79', 'Minor', 'System slow when running too many reports', '47']
- - days_open: 47
- - desc: System slow when running too many reports
- - issue_num: 79
- - sev: Minor
- """
- def __init__( self, other, include=False, ignore=None, failOn=None ):
- super( SkipTo, self ).__init__( other )
- self.ignoreExpr = ignore
- self.mayReturnEmpty = True
- self.mayIndexError = False
- self.includeMatch = include
- self.asList = False
- if isinstance(failOn, basestring):
- self.failOn = ParserElement._literalStringClass(failOn)
- else:
- self.failOn = failOn
- self.errmsg = "No match found for "+_ustr(self.expr)
-
- def parseImpl( self, instring, loc, doActions=True ):
- startloc = loc
- instrlen = len(instring)
- expr = self.expr
- expr_parse = self.expr._parse
- self_failOn_canParseNext = self.failOn.canParseNext if self.failOn is not None else None
- self_ignoreExpr_tryParse = self.ignoreExpr.tryParse if self.ignoreExpr is not None else None
-
- tmploc = loc
- while tmploc <= instrlen:
- if self_failOn_canParseNext is not None:
- # break if failOn expression matches
- if self_failOn_canParseNext(instring, tmploc):
- break
-
- if self_ignoreExpr_tryParse is not None:
- # advance past ignore expressions
- while 1:
- try:
- tmploc = self_ignoreExpr_tryParse(instring, tmploc)
- except ParseBaseException:
- break
-
- try:
- expr_parse(instring, tmploc, doActions=False, callPreParse=False)
- except (ParseException, IndexError):
- # no match, advance loc in string
- tmploc += 1
- else:
- # matched skipto expr, done
- break
-
- else:
- # ran off the end of the input string without matching skipto expr, fail
- raise ParseException(instring, loc, self.errmsg, self)
-
- # build up return values
- loc = tmploc
- skiptext = instring[startloc:loc]
- skipresult = ParseResults(skiptext)
-
- if self.includeMatch:
- loc, mat = expr_parse(instring,loc,doActions,callPreParse=False)
- skipresult += mat
-
- return loc, skipresult
-
-class Forward(ParseElementEnhance):
- """
- Forward declaration of an expression to be defined later -
- used for recursive grammars, such as algebraic infix notation.
- When the expression is known, it is assigned to the C{Forward} variable using the '<<' operator.
-
- Note: take care when assigning to C{Forward} not to overlook precedence of operators.
- Specifically, '|' has a lower precedence than '<<', so that::
- fwdExpr << a | b | c
- will actually be evaluated as::
- (fwdExpr << a) | b | c
- thereby leaving b and c out as parseable alternatives. It is recommended that you
- explicitly group the values inserted into the C{Forward}::
- fwdExpr << (a | b | c)
- Converting to use the '<<=' operator instead will avoid this problem.
-
- See L{ParseResults.pprint} for an example of a recursive parser created using
- C{Forward}.
- """
- def __init__( self, other=None ):
- super(Forward,self).__init__( other, savelist=False )
-
- def __lshift__( self, other ):
- if isinstance( other, basestring ):
- other = ParserElement._literalStringClass(other)
- self.expr = other
- self.strRepr = None
- self.mayIndexError = self.expr.mayIndexError
- self.mayReturnEmpty = self.expr.mayReturnEmpty
- self.setWhitespaceChars( self.expr.whiteChars )
- self.skipWhitespace = self.expr.skipWhitespace
- self.saveAsList = self.expr.saveAsList
- self.ignoreExprs.extend(self.expr.ignoreExprs)
- return self
-
- def __ilshift__(self, other):
- return self << other
-
- def leaveWhitespace( self ):
- self.skipWhitespace = False
- return self
-
- def streamline( self ):
- if not self.streamlined:
- self.streamlined = True
- if self.expr is not None:
- self.expr.streamline()
- return self
-
- def validate( self, validateTrace=[] ):
- if self not in validateTrace:
- tmp = validateTrace[:]+[self]
- if self.expr is not None:
- self.expr.validate(tmp)
- self.checkRecursion([])
-
- def __str__( self ):
- if hasattr(self,"name"):
- return self.name
- return self.__class__.__name__ + ": ..."
-
- # stubbed out for now - creates awful memory and perf issues
- self._revertClass = self.__class__
- self.__class__ = _ForwardNoRecurse
- try:
- if self.expr is not None:
- retString = _ustr(self.expr)
- else:
- retString = "None"
- finally:
- self.__class__ = self._revertClass
- return self.__class__.__name__ + ": " + retString
-
- def copy(self):
- if self.expr is not None:
- return super(Forward,self).copy()
- else:
- ret = Forward()
- ret <<= self
- return ret
-
-class _ForwardNoRecurse(Forward):
- def __str__( self ):
- return "..."
-
-class TokenConverter(ParseElementEnhance):
- """
- Abstract subclass of C{ParseExpression}, for converting parsed results.
- """
- def __init__( self, expr, savelist=False ):
- super(TokenConverter,self).__init__( expr )#, savelist )
- self.saveAsList = False
-
-class Combine(TokenConverter):
- """
- Converter to concatenate all matching tokens to a single string.
- By default, the matching patterns must also be contiguous in the input string;
- this can be disabled by specifying C{'adjacent=False'} in the constructor.
-
- Example::
- real = Word(nums) + '.' + Word(nums)
- print(real.parseString('3.1416')) # -> ['3', '.', '1416']
- # will also erroneously match the following
- print(real.parseString('3. 1416')) # -> ['3', '.', '1416']
-
- real = Combine(Word(nums) + '.' + Word(nums))
- print(real.parseString('3.1416')) # -> ['3.1416']
- # no match when there are internal spaces
- print(real.parseString('3. 1416')) # -> Exception: Expected W:(0123...)
- """
- def __init__( self, expr, joinString="", adjacent=True ):
- super(Combine,self).__init__( expr )
- # suppress whitespace-stripping in contained parse expressions, but re-enable it on the Combine itself
- if adjacent:
- self.leaveWhitespace()
- self.adjacent = adjacent
- self.skipWhitespace = True
- self.joinString = joinString
- self.callPreparse = True
-
- def ignore( self, other ):
- if self.adjacent:
- ParserElement.ignore(self, other)
- else:
- super( Combine, self).ignore( other )
- return self
-
- def postParse( self, instring, loc, tokenlist ):
- retToks = tokenlist.copy()
- del retToks[:]
- retToks += ParseResults([ "".join(tokenlist._asStringList(self.joinString)) ], modal=self.modalResults)
-
- if self.resultsName and retToks.haskeys():
- return [ retToks ]
- else:
- return retToks
-
-class Group(TokenConverter):
- """
- Converter to return the matched tokens as a list - useful for returning tokens of C{L{ZeroOrMore}} and C{L{OneOrMore}} expressions.
-
- Example::
- ident = Word(alphas)
- num = Word(nums)
- term = ident | num
- func = ident + Optional(delimitedList(term))
- print(func.parseString("fn a,b,100")) # -> ['fn', 'a', 'b', '100']
-
- func = ident + Group(Optional(delimitedList(term)))
- print(func.parseString("fn a,b,100")) # -> ['fn', ['a', 'b', '100']]
- """
- def __init__( self, expr ):
- super(Group,self).__init__( expr )
- self.saveAsList = True
-
- def postParse( self, instring, loc, tokenlist ):
- return [ tokenlist ]
-
-class Dict(TokenConverter):
- """
- Converter to return a repetitive expression as a list, but also as a dictionary.
- Each element can also be referenced using the first token in the expression as its key.
- Useful for tabular report scraping when the first column can be used as a item key.
-
- Example::
- data_word = Word(alphas)
- label = data_word + FollowedBy(':')
- attr_expr = Group(label + Suppress(':') + OneOrMore(data_word).setParseAction(' '.join))
-
- text = "shape: SQUARE posn: upper left color: light blue texture: burlap"
- attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join))
-
- # print attributes as plain groups
- print(OneOrMore(attr_expr).parseString(text).dump())
-
- # instead of OneOrMore(expr), parse using Dict(OneOrMore(Group(expr))) - Dict will auto-assign names
- result = Dict(OneOrMore(Group(attr_expr))).parseString(text)
- print(result.dump())
-
- # access named fields as dict entries, or output as dict
- print(result['shape'])
- print(result.asDict())
- prints::
- ['shape', 'SQUARE', 'posn', 'upper left', 'color', 'light blue', 'texture', 'burlap']
-
- [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']]
- - color: light blue
- - posn: upper left
- - shape: SQUARE
- - texture: burlap
- SQUARE
- {'color': 'light blue', 'posn': 'upper left', 'texture': 'burlap', 'shape': 'SQUARE'}
- See more examples at L{ParseResults} of accessing fields by results name.
- """
- def __init__( self, expr ):
- super(Dict,self).__init__( expr )
- self.saveAsList = True
-
- def postParse( self, instring, loc, tokenlist ):
- for i,tok in enumerate(tokenlist):
- if len(tok) == 0:
- continue
- ikey = tok[0]
- if isinstance(ikey,int):
- ikey = _ustr(tok[0]).strip()
- if len(tok)==1:
- tokenlist[ikey] = _ParseResultsWithOffset("",i)
- elif len(tok)==2 and not isinstance(tok[1],ParseResults):
- tokenlist[ikey] = _ParseResultsWithOffset(tok[1],i)
- else:
- dictvalue = tok.copy() #ParseResults(i)
- del dictvalue[0]
- if len(dictvalue)!= 1 or (isinstance(dictvalue,ParseResults) and dictvalue.haskeys()):
- tokenlist[ikey] = _ParseResultsWithOffset(dictvalue,i)
- else:
- tokenlist[ikey] = _ParseResultsWithOffset(dictvalue[0],i)
-
- if self.resultsName:
- return [ tokenlist ]
- else:
- return tokenlist
-
-
-class Suppress(TokenConverter):
- """
- Converter for ignoring the results of a parsed expression.
-
- Example::
- source = "a, b, c,d"
- wd = Word(alphas)
- wd_list1 = wd + ZeroOrMore(',' + wd)
- print(wd_list1.parseString(source))
-
- # often, delimiters that are useful during parsing are just in the
- # way afterward - use Suppress to keep them out of the parsed output
- wd_list2 = wd + ZeroOrMore(Suppress(',') + wd)
- print(wd_list2.parseString(source))
- prints::
- ['a', ',', 'b', ',', 'c', ',', 'd']
- ['a', 'b', 'c', 'd']
- (See also L{delimitedList}.)
- """
- def postParse( self, instring, loc, tokenlist ):
- return []
-
- def suppress( self ):
- return self
-
-
-class OnlyOnce(object):
- """
- Wrapper for parse actions, to ensure they are only called once.
- """
- def __init__(self, methodCall):
- self.callable = _trim_arity(methodCall)
- self.called = False
- def __call__(self,s,l,t):
- if not self.called:
- results = self.callable(s,l,t)
- self.called = True
- return results
- raise ParseException(s,l,"")
- def reset(self):
- self.called = False
-
-def traceParseAction(f):
- """
- Decorator for debugging parse actions.
-
- When the parse action is called, this decorator will print C{">> entering I{method-name}(line:I{current_source_line}, I{parse_location}, I{matched_tokens})".}
- When the parse action completes, the decorator will print C{"<<"} followed by the returned value, or any exception that the parse action raised.
-
- Example::
- wd = Word(alphas)
-
- @traceParseAction
- def remove_duplicate_chars(tokens):
- return ''.join(sorted(set(''.join(tokens))))
-
- wds = OneOrMore(wd).setParseAction(remove_duplicate_chars)
- print(wds.parseString("slkdjs sld sldd sdlf sdljf"))
- prints::
- >>entering remove_duplicate_chars(line: 'slkdjs sld sldd sdlf sdljf', 0, (['slkdjs', 'sld', 'sldd', 'sdlf', 'sdljf'], {}))
- <<leaving remove_duplicate_chars (ret: 'dfjkls')
- ['dfjkls']
- """
- f = _trim_arity(f)
- def z(*paArgs):
- thisFunc = f.__name__
- s,l,t = paArgs[-3:]
- if len(paArgs)>3:
- thisFunc = paArgs[0].__class__.__name__ + '.' + thisFunc
- sys.stderr.write( ">>entering %s(line: '%s', %d, %r)\n" % (thisFunc,line(l,s),l,t) )
- try:
- ret = f(*paArgs)
- except Exception as exc:
- sys.stderr.write( "<<leaving %s (exception: %s)\n" % (thisFunc,exc) )
- raise
- sys.stderr.write( "<<leaving %s (ret: %r)\n" % (thisFunc,ret) )
- return ret
- try:
- z.__name__ = f.__name__
- except AttributeError:
- pass
- return z
-
-#
-# global helpers
-#
-def delimitedList( expr, delim=",", combine=False ):
- """
- Helper to define a delimited list of expressions - the delimiter defaults to ','.
- By default, the list elements and delimiters can have intervening whitespace, and
- comments, but this can be overridden by passing C{combine=True} in the constructor.
- If C{combine} is set to C{True}, the matching tokens are returned as a single token
- string, with the delimiters included; otherwise, the matching tokens are returned
- as a list of tokens, with the delimiters suppressed.
-
- Example::
- delimitedList(Word(alphas)).parseString("aa,bb,cc") # -> ['aa', 'bb', 'cc']
- delimitedList(Word(hexnums), delim=':', combine=True).parseString("AA:BB:CC:DD:EE") # -> ['AA:BB:CC:DD:EE']
- """
- dlName = _ustr(expr)+" ["+_ustr(delim)+" "+_ustr(expr)+"]..."
- if combine:
- return Combine( expr + ZeroOrMore( delim + expr ) ).setName(dlName)
- else:
- return ( expr + ZeroOrMore( Suppress( delim ) + expr ) ).setName(dlName)
-
-def countedArray( expr, intExpr=None ):
- """
- Helper to define a counted list of expressions.
- This helper defines a pattern of the form::
- integer expr expr expr...
- where the leading integer tells how many expr expressions follow.
- The matched tokens returns the array of expr tokens as a list - the leading count token is suppressed.
-
- If C{intExpr} is specified, it should be a pyparsing expression that produces an integer value.
-
- Example::
- countedArray(Word(alphas)).parseString('2 ab cd ef') # -> ['ab', 'cd']
-
- # in this parser, the leading integer value is given in binary,
- # '10' indicating that 2 values are in the array
- binaryConstant = Word('01').setParseAction(lambda t: int(t[0], 2))
- countedArray(Word(alphas), intExpr=binaryConstant).parseString('10 ab cd ef') # -> ['ab', 'cd']
- """
- arrayExpr = Forward()
- def countFieldParseAction(s,l,t):
- n = t[0]
- arrayExpr << (n and Group(And([expr]*n)) or Group(empty))
- return []
- if intExpr is None:
- intExpr = Word(nums).setParseAction(lambda t:int(t[0]))
- else:
- intExpr = intExpr.copy()
- intExpr.setName("arrayLen")
- intExpr.addParseAction(countFieldParseAction, callDuringTry=True)
- return ( intExpr + arrayExpr ).setName('(len) ' + _ustr(expr) + '...')
-
-def _flatten(L):
- ret = []
- for i in L:
- if isinstance(i,list):
- ret.extend(_flatten(i))
- else:
- ret.append(i)
- return ret
-
-def matchPreviousLiteral(expr):
- """
- Helper to define an expression that is indirectly defined from
- the tokens matched in a previous expression, that is, it looks
- for a 'repeat' of a previous expression. For example::
- first = Word(nums)
- second = matchPreviousLiteral(first)
- matchExpr = first + ":" + second
- will match C{"1:1"}, but not C{"1:2"}. Because this matches a
- previous literal, will also match the leading C{"1:1"} in C{"1:10"}.
- If this is not desired, use C{matchPreviousExpr}.
- Do I{not} use with packrat parsing enabled.
- """
- rep = Forward()
- def copyTokenToRepeater(s,l,t):
- if t:
- if len(t) == 1:
- rep << t[0]
- else:
- # flatten t tokens
- tflat = _flatten(t.asList())
- rep << And(Literal(tt) for tt in tflat)
- else:
- rep << Empty()
- expr.addParseAction(copyTokenToRepeater, callDuringTry=True)
- rep.setName('(prev) ' + _ustr(expr))
- return rep
-
-def matchPreviousExpr(expr):
- """
- Helper to define an expression that is indirectly defined from
- the tokens matched in a previous expression, that is, it looks
- for a 'repeat' of a previous expression. For example::
- first = Word(nums)
- second = matchPreviousExpr(first)
- matchExpr = first + ":" + second
- will match C{"1:1"}, but not C{"1:2"}. Because this matches by
- expressions, will I{not} match the leading C{"1:1"} in C{"1:10"};
- the expressions are evaluated first, and then compared, so
- C{"1"} is compared with C{"10"}.
- Do I{not} use with packrat parsing enabled.
- """
- rep = Forward()
- e2 = expr.copy()
- rep <<= e2
- def copyTokenToRepeater(s,l,t):
- matchTokens = _flatten(t.asList())
- def mustMatchTheseTokens(s,l,t):
- theseTokens = _flatten(t.asList())
- if theseTokens != matchTokens:
- raise ParseException("",0,"")
- rep.setParseAction( mustMatchTheseTokens, callDuringTry=True )
- expr.addParseAction(copyTokenToRepeater, callDuringTry=True)
- rep.setName('(prev) ' + _ustr(expr))
- return rep
-
-def _escapeRegexRangeChars(s):
- #~ escape these chars: ^-]
- for c in r"\^-]":
- s = s.replace(c,_bslash+c)
- s = s.replace("\n",r"\n")
- s = s.replace("\t",r"\t")
- return _ustr(s)
-
-def oneOf( strs, caseless=False, useRegex=True ):
- """
- Helper to quickly define a set of alternative Literals, and makes sure to do
- longest-first testing when there is a conflict, regardless of the input order,
- but returns a C{L{MatchFirst}} for best performance.
-
- Parameters:
- - strs - a string of space-delimited literals, or a collection of string literals
- - caseless - (default=C{False}) - treat all literals as caseless
- - useRegex - (default=C{True}) - as an optimization, will generate a Regex
- object; otherwise, will generate a C{MatchFirst} object (if C{caseless=True}, or
- if creating a C{Regex} raises an exception)
-
- Example::
- comp_oper = oneOf("< = > <= >= !=")
- var = Word(alphas)
- number = Word(nums)
- term = var | number
- comparison_expr = term + comp_oper + term
- print(comparison_expr.searchString("B = 12 AA=23 B<=AA AA>12"))
- prints::
- [['B', '=', '12'], ['AA', '=', '23'], ['B', '<=', 'AA'], ['AA', '>', '12']]
- """
- if caseless:
- isequal = ( lambda a,b: a.upper() == b.upper() )
- masks = ( lambda a,b: b.upper().startswith(a.upper()) )
- parseElementClass = CaselessLiteral
- else:
- isequal = ( lambda a,b: a == b )
- masks = ( lambda a,b: b.startswith(a) )
- parseElementClass = Literal
-
- symbols = []
- if isinstance(strs,basestring):
- symbols = strs.split()
- elif isinstance(strs, Iterable):
- symbols = list(strs)
- else:
- warnings.warn("Invalid argument to oneOf, expected string or iterable",
- SyntaxWarning, stacklevel=2)
- if not symbols:
- return NoMatch()
-
- i = 0
- while i < len(symbols)-1:
- cur = symbols[i]
- for j,other in enumerate(symbols[i+1:]):
- if ( isequal(other, cur) ):
- del symbols[i+j+1]
- break
- elif ( masks(cur, other) ):
- del symbols[i+j+1]
- symbols.insert(i,other)
- cur = other
- break
- else:
- i += 1
-
- if not caseless and useRegex:
- #~ print (strs,"->", "|".join( [ _escapeRegexChars(sym) for sym in symbols] ))
- try:
- if len(symbols)==len("".join(symbols)):
- return Regex( "[%s]" % "".join(_escapeRegexRangeChars(sym) for sym in symbols) ).setName(' | '.join(symbols))
- else:
- return Regex( "|".join(re.escape(sym) for sym in symbols) ).setName(' | '.join(symbols))
- except Exception:
- warnings.warn("Exception creating Regex for oneOf, building MatchFirst",
- SyntaxWarning, stacklevel=2)
-
-
- # last resort, just use MatchFirst
- return MatchFirst(parseElementClass(sym) for sym in symbols).setName(' | '.join(symbols))
-
-def dictOf( key, value ):
- """
- Helper to easily and clearly define a dictionary by specifying the respective patterns
- for the key and value. Takes care of defining the C{L{Dict}}, C{L{ZeroOrMore}}, and C{L{Group}} tokens
- in the proper order. The key pattern can include delimiting markers or punctuation,
- as long as they are suppressed, thereby leaving the significant key text. The value
- pattern can include named results, so that the C{Dict} results can include named token
- fields.
-
- Example::
- text = "shape: SQUARE posn: upper left color: light blue texture: burlap"
- attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join))
- print(OneOrMore(attr_expr).parseString(text).dump())
-
- attr_label = label
- attr_value = Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)
-
- # similar to Dict, but simpler call format
- result = dictOf(attr_label, attr_value).parseString(text)
- print(result.dump())
- print(result['shape'])
- print(result.shape) # object attribute access works too
- print(result.asDict())
- prints::
- [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']]
- - color: light blue
- - posn: upper left
- - shape: SQUARE
- - texture: burlap
- SQUARE
- SQUARE
- {'color': 'light blue', 'shape': 'SQUARE', 'posn': 'upper left', 'texture': 'burlap'}
- """
- return Dict( ZeroOrMore( Group ( key + value ) ) )
-
-def originalTextFor(expr, asString=True):
- """
- Helper to return the original, untokenized text for a given expression. Useful to
- restore the parsed fields of an HTML start tag into the raw tag text itself, or to
- revert separate tokens with intervening whitespace back to the original matching
- input text. By default, returns astring containing the original parsed text.
-
- If the optional C{asString} argument is passed as C{False}, then the return value is a
- C{L{ParseResults}} containing any results names that were originally matched, and a
- single token containing the original matched text from the input string. So if
- the expression passed to C{L{originalTextFor}} contains expressions with defined
- results names, you must set C{asString} to C{False} if you want to preserve those
- results name values.
-
- Example::
- src = "this is test <b> bold <i>text</i> </b> normal text "
- for tag in ("b","i"):
- opener,closer = makeHTMLTags(tag)
- patt = originalTextFor(opener + SkipTo(closer) + closer)
- print(patt.searchString(src)[0])
- prints::
- ['<b> bold <i>text</i> </b>']
- ['<i>text</i>']
- """
- locMarker = Empty().setParseAction(lambda s,loc,t: loc)
- endlocMarker = locMarker.copy()
- endlocMarker.callPreparse = False
- matchExpr = locMarker("_original_start") + expr + endlocMarker("_original_end")
- if asString:
- extractText = lambda s,l,t: s[t._original_start:t._original_end]
- else:
- def extractText(s,l,t):
- t[:] = [s[t.pop('_original_start'):t.pop('_original_end')]]
- matchExpr.setParseAction(extractText)
- matchExpr.ignoreExprs = expr.ignoreExprs
- return matchExpr
-
-def ungroup(expr):
- """
- Helper to undo pyparsing's default grouping of And expressions, even
- if all but one are non-empty.
- """
- return TokenConverter(expr).setParseAction(lambda t:t[0])
-
-def locatedExpr(expr):
- """
- Helper to decorate a returned token with its starting and ending locations in the input string.
- This helper adds the following results names:
- - locn_start = location where matched expression begins
- - locn_end = location where matched expression ends
- - value = the actual parsed results
-
- Be careful if the input text contains C{<TAB>} characters, you may want to call
- C{L{ParserElement.parseWithTabs}}
-
- Example::
- wd = Word(alphas)
- for match in locatedExpr(wd).searchString("ljsdf123lksdjjf123lkkjj1222"):
- print(match)
- prints::
- [[0, 'ljsdf', 5]]
- [[8, 'lksdjjf', 15]]
- [[18, 'lkkjj', 23]]
- """
- locator = Empty().setParseAction(lambda s,l,t: l)
- return Group(locator("locn_start") + expr("value") + locator.copy().leaveWhitespace()("locn_end"))
-
-
-# convenience constants for positional expressions
-empty = Empty().setName("empty")
-lineStart = LineStart().setName("lineStart")
-lineEnd = LineEnd().setName("lineEnd")
-stringStart = StringStart().setName("stringStart")
-stringEnd = StringEnd().setName("stringEnd")
-
-_escapedPunc = Word( _bslash, r"\[]-*.$+^?()~ ", exact=2 ).setParseAction(lambda s,l,t:t[0][1])
-_escapedHexChar = Regex(r"\\0?[xX][0-9a-fA-F]+").setParseAction(lambda s,l,t:unichr(int(t[0].lstrip(r'\0x'),16)))
-_escapedOctChar = Regex(r"\\0[0-7]+").setParseAction(lambda s,l,t:unichr(int(t[0][1:],8)))
-_singleChar = _escapedPunc | _escapedHexChar | _escapedOctChar | CharsNotIn(r'\]', exact=1)
-_charRange = Group(_singleChar + Suppress("-") + _singleChar)
-_reBracketExpr = Literal("[") + Optional("^").setResultsName("negate") + Group( OneOrMore( _charRange | _singleChar ) ).setResultsName("body") + "]"
-
-def srange(s):
- r"""
- Helper to easily define string ranges for use in Word construction. Borrows
- syntax from regexp '[]' string range definitions::
- srange("[0-9]") -> "0123456789"
- srange("[a-z]") -> "abcdefghijklmnopqrstuvwxyz"
- srange("[a-z$_]") -> "abcdefghijklmnopqrstuvwxyz$_"
- The input string must be enclosed in []'s, and the returned string is the expanded
- character set joined into a single string.
- The values enclosed in the []'s may be:
- - a single character
- - an escaped character with a leading backslash (such as C{\-} or C{\]})
- - an escaped hex character with a leading C{'\x'} (C{\x21}, which is a C{'!'} character)
- (C{\0x##} is also supported for backwards compatibility)
- - an escaped octal character with a leading C{'\0'} (C{\041}, which is a C{'!'} character)
- - a range of any of the above, separated by a dash (C{'a-z'}, etc.)
- - any combination of the above (C{'aeiouy'}, C{'a-zA-Z0-9_$'}, etc.)
- """
- _expanded = lambda p: p if not isinstance(p,ParseResults) else ''.join(unichr(c) for c in range(ord(p[0]),ord(p[1])+1))
- try:
- return "".join(_expanded(part) for part in _reBracketExpr.parseString(s).body)
- except Exception:
- return ""
-
-def matchOnlyAtCol(n):
- """
- Helper method for defining parse actions that require matching at a specific
- column in the input text.
- """
- def verifyCol(strg,locn,toks):
- if col(locn,strg) != n:
- raise ParseException(strg,locn,"matched token not at column %d" % n)
- return verifyCol
-
-def replaceWith(replStr):
- """
- Helper method for common parse actions that simply return a literal value. Especially
- useful when used with C{L{transformString<ParserElement.transformString>}()}.
-
- Example::
- num = Word(nums).setParseAction(lambda toks: int(toks[0]))
- na = oneOf("N/A NA").setParseAction(replaceWith(math.nan))
- term = na | num
-
- OneOrMore(term).parseString("324 234 N/A 234") # -> [324, 234, nan, 234]
- """
- return lambda s,l,t: [replStr]
-
-def removeQuotes(s,l,t):
- """
- Helper parse action for removing quotation marks from parsed quoted strings.
-
- Example::
- # by default, quotation marks are included in parsed results
- quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["'Now is the Winter of our Discontent'"]
-
- # use removeQuotes to strip quotation marks from parsed results
- quotedString.setParseAction(removeQuotes)
- quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["Now is the Winter of our Discontent"]
- """
- return t[0][1:-1]
-
-def tokenMap(func, *args):
- """
- Helper to define a parse action by mapping a function to all elements of a ParseResults list.If any additional
- args are passed, they are forwarded to the given function as additional arguments after
- the token, as in C{hex_integer = Word(hexnums).setParseAction(tokenMap(int, 16))}, which will convert the
- parsed data to an integer using base 16.
-
- Example (compare the last to example in L{ParserElement.transformString}::
- hex_ints = OneOrMore(Word(hexnums)).setParseAction(tokenMap(int, 16))
- hex_ints.runTests('''
- 00 11 22 aa FF 0a 0d 1a
- ''')
-
- upperword = Word(alphas).setParseAction(tokenMap(str.upper))
- OneOrMore(upperword).runTests('''
- my kingdom for a horse
- ''')
-
- wd = Word(alphas).setParseAction(tokenMap(str.title))
- OneOrMore(wd).setParseAction(' '.join).runTests('''
- now is the winter of our discontent made glorious summer by this sun of york
- ''')
- prints::
- 00 11 22 aa FF 0a 0d 1a
- [0, 17, 34, 170, 255, 10, 13, 26]
-
- my kingdom for a horse
- ['MY', 'KINGDOM', 'FOR', 'A', 'HORSE']
-
- now is the winter of our discontent made glorious summer by this sun of york
- ['Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York']
- """
- def pa(s,l,t):
- return [func(tokn, *args) for tokn in t]
-
- try:
- func_name = getattr(func, '__name__',
- getattr(func, '__class__').__name__)
- except Exception:
- func_name = str(func)
- pa.__name__ = func_name
-
- return pa
-
-upcaseTokens = tokenMap(lambda t: _ustr(t).upper())
-"""(Deprecated) Helper parse action to convert tokens to upper case. Deprecated in favor of L{pyparsing_common.upcaseTokens}"""
-
-downcaseTokens = tokenMap(lambda t: _ustr(t).lower())
-"""(Deprecated) Helper parse action to convert tokens to lower case. Deprecated in favor of L{pyparsing_common.downcaseTokens}"""
-
-def _makeTags(tagStr, xml):
- """Internal helper to construct opening and closing tag expressions, given a tag name"""
- if isinstance(tagStr,basestring):
- resname = tagStr
- tagStr = Keyword(tagStr, caseless=not xml)
- else:
- resname = tagStr.name
-
- tagAttrName = Word(alphas,alphanums+"_-:")
- if (xml):
- tagAttrValue = dblQuotedString.copy().setParseAction( removeQuotes )
- openTag = Suppress("<") + tagStr("tag") + \
- Dict(ZeroOrMore(Group( tagAttrName + Suppress("=") + tagAttrValue ))) + \
- Optional("/",default=[False]).setResultsName("empty").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(">")
- else:
- printablesLessRAbrack = "".join(c for c in printables if c not in ">")
- tagAttrValue = quotedString.copy().setParseAction( removeQuotes ) | Word(printablesLessRAbrack)
- openTag = Suppress("<") + tagStr("tag") + \
- Dict(ZeroOrMore(Group( tagAttrName.setParseAction(downcaseTokens) + \
- Optional( Suppress("=") + tagAttrValue ) ))) + \
- Optional("/",default=[False]).setResultsName("empty").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(">")
- closeTag = Combine(_L("</") + tagStr + ">")
-
- openTag = openTag.setResultsName("start"+"".join(resname.replace(":"," ").title().split())).setName("<%s>" % resname)
- closeTag = closeTag.setResultsName("end"+"".join(resname.replace(":"," ").title().split())).setName("</%s>" % resname)
- openTag.tag = resname
- closeTag.tag = resname
- return openTag, closeTag
-
-def makeHTMLTags(tagStr):
- """
- Helper to construct opening and closing tag expressions for HTML, given a tag name. Matches
- tags in either upper or lower case, attributes with namespaces and with quoted or unquoted values.
-
- Example::
- text = '<td>More info at the <a href="http://pyparsing.wikispaces.com">pyparsing</a> wiki page</td>'
- # makeHTMLTags returns pyparsing expressions for the opening and closing tags as a 2-tuple
- a,a_end = makeHTMLTags("A")
- link_expr = a + SkipTo(a_end)("link_text") + a_end
-
- for link in link_expr.searchString(text):
- # attributes in the <A> tag (like "href" shown here) are also accessible as named results
- print(link.link_text, '->', link.href)
- prints::
- pyparsing -> http://pyparsing.wikispaces.com
- """
- return _makeTags( tagStr, False )
-
-def makeXMLTags(tagStr):
- """
- Helper to construct opening and closing tag expressions for XML, given a tag name. Matches
- tags only in the given upper/lower case.
-
- Example: similar to L{makeHTMLTags}
- """
- return _makeTags( tagStr, True )
-
-def withAttribute(*args,**attrDict):
- """
- Helper to create a validating parse action to be used with start tags created
- with C{L{makeXMLTags}} or C{L{makeHTMLTags}}. Use C{withAttribute} to qualify a starting tag
- with a required attribute value, to avoid false matches on common tags such as
- C{<TD>} or C{<DIV>}.
-
- Call C{withAttribute} with a series of attribute names and values. Specify the list
- of filter attributes names and values as:
- - keyword arguments, as in C{(align="right")}, or
- - as an explicit dict with C{**} operator, when an attribute name is also a Python
- reserved word, as in C{**{"class":"Customer", "align":"right"}}
- - a list of name-value tuples, as in ( ("ns1:class", "Customer"), ("ns2:align","right") )
- For attribute names with a namespace prefix, you must use the second form. Attribute
- names are matched insensitive to upper/lower case.
-
- If just testing for C{class} (with or without a namespace), use C{L{withClass}}.
-
- To verify that the attribute exists, but without specifying a value, pass
- C{withAttribute.ANY_VALUE} as the value.
-
- Example::
- html = '''
- <div>
- Some text
- <div type="grid">1 4 0 1 0</div>
- <div type="graph">1,3 2,3 1,1</div>
- <div>this has no type</div>
- </div>
-
- '''
- div,div_end = makeHTMLTags("div")
-
- # only match div tag having a type attribute with value "grid"
- div_grid = div().setParseAction(withAttribute(type="grid"))
- grid_expr = div_grid + SkipTo(div | div_end)("body")
- for grid_header in grid_expr.searchString(html):
- print(grid_header.body)
-
- # construct a match with any div tag having a type attribute, regardless of the value
- div_any_type = div().setParseAction(withAttribute(type=withAttribute.ANY_VALUE))
- div_expr = div_any_type + SkipTo(div | div_end)("body")
- for div_header in div_expr.searchString(html):
- print(div_header.body)
- prints::
- 1 4 0 1 0
-
- 1 4 0 1 0
- 1,3 2,3 1,1
- """
- if args:
- attrs = args[:]
- else:
- attrs = attrDict.items()
- attrs = [(k,v) for k,v in attrs]
- def pa(s,l,tokens):
- for attrName,attrValue in attrs:
- if attrName not in tokens:
- raise ParseException(s,l,"no matching attribute " + attrName)
- if attrValue != withAttribute.ANY_VALUE and tokens[attrName] != attrValue:
- raise ParseException(s,l,"attribute '%s' has value '%s', must be '%s'" %
- (attrName, tokens[attrName], attrValue))
- return pa
-withAttribute.ANY_VALUE = object()
-
-def withClass(classname, namespace=''):
- """
- Simplified version of C{L{withAttribute}} when matching on a div class - made
- difficult because C{class} is a reserved word in Python.
-
- Example::
- html = '''
- <div>
- Some text
- <div class="grid">1 4 0 1 0</div>
- <div class="graph">1,3 2,3 1,1</div>
- <div>this &lt;div&gt; has no class</div>
- </div>
-
- '''
- div,div_end = makeHTMLTags("div")
- div_grid = div().setParseAction(withClass("grid"))
-
- grid_expr = div_grid + SkipTo(div | div_end)("body")
- for grid_header in grid_expr.searchString(html):
- print(grid_header.body)
-
- div_any_type = div().setParseAction(withClass(withAttribute.ANY_VALUE))
- div_expr = div_any_type + SkipTo(div | div_end)("body")
- for div_header in div_expr.searchString(html):
- print(div_header.body)
- prints::
- 1 4 0 1 0
-
- 1 4 0 1 0
- 1,3 2,3 1,1
- """
- classattr = "%s:class" % namespace if namespace else "class"
- return withAttribute(**{classattr : classname})
-
-opAssoc = _Constants()
-opAssoc.LEFT = object()
-opAssoc.RIGHT = object()
-
-def infixNotation( baseExpr, opList, lpar=Suppress('('), rpar=Suppress(')') ):
- """
- Helper method for constructing grammars of expressions made up of
- operators working in a precedence hierarchy. Operators may be unary or
- binary, left- or right-associative. Parse actions can also be attached
- to operator expressions. The generated parser will also recognize the use
- of parentheses to override operator precedences (see example below).
-
- Note: if you define a deep operator list, you may see performance issues
- when using infixNotation. See L{ParserElement.enablePackrat} for a
- mechanism to potentially improve your parser performance.
-
- Parameters:
- - baseExpr - expression representing the most basic element for the nested
- - opList - list of tuples, one for each operator precedence level in the
- expression grammar; each tuple is of the form
- (opExpr, numTerms, rightLeftAssoc, parseAction), where:
- - opExpr is the pyparsing expression for the operator;
- may also be a string, which will be converted to a Literal;
- if numTerms is 3, opExpr is a tuple of two expressions, for the
- two operators separating the 3 terms
- - numTerms is the number of terms for this operator (must
- be 1, 2, or 3)
- - rightLeftAssoc is the indicator whether the operator is
- right or left associative, using the pyparsing-defined
- constants C{opAssoc.RIGHT} and C{opAssoc.LEFT}.
- - parseAction is the parse action to be associated with
- expressions matching this operator expression (the
- parse action tuple member may be omitted); if the parse action
- is passed a tuple or list of functions, this is equivalent to
- calling C{setParseAction(*fn)} (L{ParserElement.setParseAction})
- - lpar - expression for matching left-parentheses (default=C{Suppress('(')})
- - rpar - expression for matching right-parentheses (default=C{Suppress(')')})
-
- Example::
- # simple example of four-function arithmetic with ints and variable names
- integer = pyparsing_common.signed_integer
- varname = pyparsing_common.identifier
-
- arith_expr = infixNotation(integer | varname,
- [
- ('-', 1, opAssoc.RIGHT),
- (oneOf('* /'), 2, opAssoc.LEFT),
- (oneOf('+ -'), 2, opAssoc.LEFT),
- ])
-
- arith_expr.runTests('''
- 5+3*6
- (5+3)*6
- -2--11
- ''', fullDump=False)
- prints::
- 5+3*6
- [[5, '+', [3, '*', 6]]]
-
- (5+3)*6
- [[[5, '+', 3], '*', 6]]
-
- -2--11
- [[['-', 2], '-', ['-', 11]]]
- """
- ret = Forward()
- lastExpr = baseExpr | ( lpar + ret + rpar )
- for i,operDef in enumerate(opList):
- opExpr,arity,rightLeftAssoc,pa = (operDef + (None,))[:4]
- termName = "%s term" % opExpr if arity < 3 else "%s%s term" % opExpr
- if arity == 3:
- if opExpr is None or len(opExpr) != 2:
- raise ValueError("if numterms=3, opExpr must be a tuple or list of two expressions")
- opExpr1, opExpr2 = opExpr
- thisExpr = Forward().setName(termName)
- if rightLeftAssoc == opAssoc.LEFT:
- if arity == 1:
- matchExpr = FollowedBy(lastExpr + opExpr) + Group( lastExpr + OneOrMore( opExpr ) )
- elif arity == 2:
- if opExpr is not None:
- matchExpr = FollowedBy(lastExpr + opExpr + lastExpr) + Group( lastExpr + OneOrMore( opExpr + lastExpr ) )
- else:
- matchExpr = FollowedBy(lastExpr+lastExpr) + Group( lastExpr + OneOrMore(lastExpr) )
- elif arity == 3:
- matchExpr = FollowedBy(lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr) + \
- Group( lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr )
- else:
- raise ValueError("operator must be unary (1), binary (2), or ternary (3)")
- elif rightLeftAssoc == opAssoc.RIGHT:
- if arity == 1:
- # try to avoid LR with this extra test
- if not isinstance(opExpr, Optional):
- opExpr = Optional(opExpr)
- matchExpr = FollowedBy(opExpr.expr + thisExpr) + Group( opExpr + thisExpr )
- elif arity == 2:
- if opExpr is not None:
- matchExpr = FollowedBy(lastExpr + opExpr + thisExpr) + Group( lastExpr + OneOrMore( opExpr + thisExpr ) )
- else:
- matchExpr = FollowedBy(lastExpr + thisExpr) + Group( lastExpr + OneOrMore( thisExpr ) )
- elif arity == 3:
- matchExpr = FollowedBy(lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr) + \
- Group( lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr )
- else:
- raise ValueError("operator must be unary (1), binary (2), or ternary (3)")
- else:
- raise ValueError("operator must indicate right or left associativity")
- if pa:
- if isinstance(pa, (tuple, list)):
- matchExpr.setParseAction(*pa)
- else:
- matchExpr.setParseAction(pa)
- thisExpr <<= ( matchExpr.setName(termName) | lastExpr )
- lastExpr = thisExpr
- ret <<= lastExpr
- return ret
-
-operatorPrecedence = infixNotation
-"""(Deprecated) Former name of C{L{infixNotation}}, will be dropped in a future release."""
-
-dblQuotedString = Combine(Regex(r'"(?:[^"\n\r\\]|(?:"")|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*')+'"').setName("string enclosed in double quotes")
-sglQuotedString = Combine(Regex(r"'(?:[^'\n\r\\]|(?:'')|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*")+"'").setName("string enclosed in single quotes")
-quotedString = Combine(Regex(r'"(?:[^"\n\r\\]|(?:"")|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*')+'"'|
- Regex(r"'(?:[^'\n\r\\]|(?:'')|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*")+"'").setName("quotedString using single or double quotes")
-unicodeString = Combine(_L('u') + quotedString.copy()).setName("unicode string literal")
-
-def nestedExpr(opener="(", closer=")", content=None, ignoreExpr=quotedString.copy()):
- """
- Helper method for defining nested lists enclosed in opening and closing
- delimiters ("(" and ")" are the default).
-
- Parameters:
- - opener - opening character for a nested list (default=C{"("}); can also be a pyparsing expression
- - closer - closing character for a nested list (default=C{")"}); can also be a pyparsing expression
- - content - expression for items within the nested lists (default=C{None})
- - ignoreExpr - expression for ignoring opening and closing delimiters (default=C{quotedString})
-
- If an expression is not provided for the content argument, the nested
- expression will capture all whitespace-delimited content between delimiters
- as a list of separate values.
-
- Use the C{ignoreExpr} argument to define expressions that may contain
- opening or closing characters that should not be treated as opening
- or closing characters for nesting, such as quotedString or a comment
- expression. Specify multiple expressions using an C{L{Or}} or C{L{MatchFirst}}.
- The default is L{quotedString}, but if no expressions are to be ignored,
- then pass C{None} for this argument.
-
- Example::
- data_type = oneOf("void int short long char float double")
- decl_data_type = Combine(data_type + Optional(Word('*')))
- ident = Word(alphas+'_', alphanums+'_')
- number = pyparsing_common.number
- arg = Group(decl_data_type + ident)
- LPAR,RPAR = map(Suppress, "()")
-
- code_body = nestedExpr('{', '}', ignoreExpr=(quotedString | cStyleComment))
-
- c_function = (decl_data_type("type")
- + ident("name")
- + LPAR + Optional(delimitedList(arg), [])("args") + RPAR
- + code_body("body"))
- c_function.ignore(cStyleComment)
-
- source_code = '''
- int is_odd(int x) {
- return (x%2);
- }
-
- int dec_to_hex(char hchar) {
- if (hchar >= '0' && hchar <= '9') {
- return (ord(hchar)-ord('0'));
- } else {
- return (10+ord(hchar)-ord('A'));
- }
- }
- '''
- for func in c_function.searchString(source_code):
- print("%(name)s (%(type)s) args: %(args)s" % func)
-
- prints::
- is_odd (int) args: [['int', 'x']]
- dec_to_hex (int) args: [['char', 'hchar']]
- """
- if opener == closer:
- raise ValueError("opening and closing strings cannot be the same")
- if content is None:
- if isinstance(opener,basestring) and isinstance(closer,basestring):
- if len(opener) == 1 and len(closer)==1:
- if ignoreExpr is not None:
- content = (Combine(OneOrMore(~ignoreExpr +
- CharsNotIn(opener+closer+ParserElement.DEFAULT_WHITE_CHARS,exact=1))
- ).setParseAction(lambda t:t[0].strip()))
- else:
- content = (empty.copy()+CharsNotIn(opener+closer+ParserElement.DEFAULT_WHITE_CHARS
- ).setParseAction(lambda t:t[0].strip()))
- else:
- if ignoreExpr is not None:
- content = (Combine(OneOrMore(~ignoreExpr +
- ~Literal(opener) + ~Literal(closer) +
- CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS,exact=1))
- ).setParseAction(lambda t:t[0].strip()))
- else:
- content = (Combine(OneOrMore(~Literal(opener) + ~Literal(closer) +
- CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS,exact=1))
- ).setParseAction(lambda t:t[0].strip()))
- else:
- raise ValueError("opening and closing arguments must be strings if no content expression is given")
- ret = Forward()
- if ignoreExpr is not None:
- ret <<= Group( Suppress(opener) + ZeroOrMore( ignoreExpr | ret | content ) + Suppress(closer) )
- else:
- ret <<= Group( Suppress(opener) + ZeroOrMore( ret | content ) + Suppress(closer) )
- ret.setName('nested %s%s expression' % (opener,closer))
- return ret
-
-def indentedBlock(blockStatementExpr, indentStack, indent=True):
- """
- Helper method for defining space-delimited indentation blocks, such as
- those used to define block statements in Python source code.
-
- Parameters:
- - blockStatementExpr - expression defining syntax of statement that
- is repeated within the indented block
- - indentStack - list created by caller to manage indentation stack
- (multiple statementWithIndentedBlock expressions within a single grammar
- should share a common indentStack)
- - indent - boolean indicating whether block must be indented beyond the
- the current level; set to False for block of left-most statements
- (default=C{True})
-
- A valid block must contain at least one C{blockStatement}.
-
- Example::
- data = '''
- def A(z):
- A1
- B = 100
- G = A2
- A2
- A3
- B
- def BB(a,b,c):
- BB1
- def BBA():
- bba1
- bba2
- bba3
- C
- D
- def spam(x,y):
- def eggs(z):
- pass
- '''
-
-
- indentStack = [1]
- stmt = Forward()
-
- identifier = Word(alphas, alphanums)
- funcDecl = ("def" + identifier + Group( "(" + Optional( delimitedList(identifier) ) + ")" ) + ":")
- func_body = indentedBlock(stmt, indentStack)
- funcDef = Group( funcDecl + func_body )
-
- rvalue = Forward()
- funcCall = Group(identifier + "(" + Optional(delimitedList(rvalue)) + ")")
- rvalue << (funcCall | identifier | Word(nums))
- assignment = Group(identifier + "=" + rvalue)
- stmt << ( funcDef | assignment | identifier )
-
- module_body = OneOrMore(stmt)
-
- parseTree = module_body.parseString(data)
- parseTree.pprint()
- prints::
- [['def',
- 'A',
- ['(', 'z', ')'],
- ':',
- [['A1'], [['B', '=', '100']], [['G', '=', 'A2']], ['A2'], ['A3']]],
- 'B',
- ['def',
- 'BB',
- ['(', 'a', 'b', 'c', ')'],
- ':',
- [['BB1'], [['def', 'BBA', ['(', ')'], ':', [['bba1'], ['bba2'], ['bba3']]]]]],
- 'C',
- 'D',
- ['def',
- 'spam',
- ['(', 'x', 'y', ')'],
- ':',
- [[['def', 'eggs', ['(', 'z', ')'], ':', [['pass']]]]]]]
- """
- def checkPeerIndent(s,l,t):
- if l >= len(s): return
- curCol = col(l,s)
- if curCol != indentStack[-1]:
- if curCol > indentStack[-1]:
- raise ParseFatalException(s,l,"illegal nesting")
- raise ParseException(s,l,"not a peer entry")
-
- def checkSubIndent(s,l,t):
- curCol = col(l,s)
- if curCol > indentStack[-1]:
- indentStack.append( curCol )
- else:
- raise ParseException(s,l,"not a subentry")
-
- def checkUnindent(s,l,t):
- if l >= len(s): return
- curCol = col(l,s)
- if not(indentStack and curCol < indentStack[-1] and curCol <= indentStack[-2]):
- raise ParseException(s,l,"not an unindent")
- indentStack.pop()
-
- NL = OneOrMore(LineEnd().setWhitespaceChars("\t ").suppress())
- INDENT = (Empty() + Empty().setParseAction(checkSubIndent)).setName('INDENT')
- PEER = Empty().setParseAction(checkPeerIndent).setName('')
- UNDENT = Empty().setParseAction(checkUnindent).setName('UNINDENT')
- if indent:
- smExpr = Group( Optional(NL) +
- #~ FollowedBy(blockStatementExpr) +
- INDENT + (OneOrMore( PEER + Group(blockStatementExpr) + Optional(NL) )) + UNDENT)
- else:
- smExpr = Group( Optional(NL) +
- (OneOrMore( PEER + Group(blockStatementExpr) + Optional(NL) )) )
- blockStatementExpr.ignore(_bslash + LineEnd())
- return smExpr.setName('indented block')
-
-alphas8bit = srange(r"[\0xc0-\0xd6\0xd8-\0xf6\0xf8-\0xff]")
-punc8bit = srange(r"[\0xa1-\0xbf\0xd7\0xf7]")
-
-anyOpenTag,anyCloseTag = makeHTMLTags(Word(alphas,alphanums+"_:").setName('any tag'))
-_htmlEntityMap = dict(zip("gt lt amp nbsp quot apos".split(),'><& "\''))
-commonHTMLEntity = Regex('&(?P<entity>' + '|'.join(_htmlEntityMap.keys()) +");").setName("common HTML entity")
-def replaceHTMLEntity(t):
- """Helper parser action to replace common HTML entities with their special characters"""
- return _htmlEntityMap.get(t.entity)
-
-# it's easy to get these comment structures wrong - they're very common, so may as well make them available
-cStyleComment = Combine(Regex(r"/\*(?:[^*]|\*(?!/))*") + '*/').setName("C style comment")
-"Comment of the form C{/* ... */}"
-
-htmlComment = Regex(r"<!--[\s\S]*?-->").setName("HTML comment")
-"Comment of the form C{<!-- ... -->}"
-
-restOfLine = Regex(r".*").leaveWhitespace().setName("rest of line")
-dblSlashComment = Regex(r"//(?:\\\n|[^\n])*").setName("// comment")
-"Comment of the form C{// ... (to end of line)}"
-
-cppStyleComment = Combine(Regex(r"/\*(?:[^*]|\*(?!/))*") + '*/'| dblSlashComment).setName("C++ style comment")
-"Comment of either form C{L{cStyleComment}} or C{L{dblSlashComment}}"
-
-javaStyleComment = cppStyleComment
-"Same as C{L{cppStyleComment}}"
-
-pythonStyleComment = Regex(r"#.*").setName("Python style comment")
-"Comment of the form C{# ... (to end of line)}"
-
-_commasepitem = Combine(OneOrMore(Word(printables, excludeChars=',') +
- Optional( Word(" \t") +
- ~Literal(",") + ~LineEnd() ) ) ).streamline().setName("commaItem")
-commaSeparatedList = delimitedList( Optional( quotedString.copy() | _commasepitem, default="") ).setName("commaSeparatedList")
-"""(Deprecated) Predefined expression of 1 or more printable words or quoted strings, separated by commas.
- This expression is deprecated in favor of L{pyparsing_common.comma_separated_list}."""
-
-# some other useful expressions - using lower-case class name since we are really using this as a namespace
-class pyparsing_common:
- """
- Here are some common low-level expressions that may be useful in jump-starting parser development:
- - numeric forms (L{integers<integer>}, L{reals<real>}, L{scientific notation<sci_real>})
- - common L{programming identifiers<identifier>}
- - network addresses (L{MAC<mac_address>}, L{IPv4<ipv4_address>}, L{IPv6<ipv6_address>})
- - ISO8601 L{dates<iso8601_date>} and L{datetime<iso8601_datetime>}
- - L{UUID<uuid>}
- - L{comma-separated list<comma_separated_list>}
- Parse actions:
- - C{L{convertToInteger}}
- - C{L{convertToFloat}}
- - C{L{convertToDate}}
- - C{L{convertToDatetime}}
- - C{L{stripHTMLTags}}
- - C{L{upcaseTokens}}
- - C{L{downcaseTokens}}
-
- Example::
- pyparsing_common.number.runTests('''
- # any int or real number, returned as the appropriate type
- 100
- -100
- +100
- 3.14159
- 6.02e23
- 1e-12
- ''')
-
- pyparsing_common.fnumber.runTests('''
- # any int or real number, returned as float
- 100
- -100
- +100
- 3.14159
- 6.02e23
- 1e-12
- ''')
-
- pyparsing_common.hex_integer.runTests('''
- # hex numbers
- 100
- FF
- ''')
-
- pyparsing_common.fraction.runTests('''
- # fractions
- 1/2
- -3/4
- ''')
-
- pyparsing_common.mixed_integer.runTests('''
- # mixed fractions
- 1
- 1/2
- -3/4
- 1-3/4
- ''')
-
- import uuid
- pyparsing_common.uuid.setParseAction(tokenMap(uuid.UUID))
- pyparsing_common.uuid.runTests('''
- # uuid
- 12345678-1234-5678-1234-567812345678
- ''')
- prints::
- # any int or real number, returned as the appropriate type
- 100
- [100]
-
- -100
- [-100]
-
- +100
- [100]
-
- 3.14159
- [3.14159]
-
- 6.02e23
- [6.02e+23]
-
- 1e-12
- [1e-12]
-
- # any int or real number, returned as float
- 100
- [100.0]
-
- -100
- [-100.0]
-
- +100
- [100.0]
-
- 3.14159
- [3.14159]
-
- 6.02e23
- [6.02e+23]
-
- 1e-12
- [1e-12]
-
- # hex numbers
- 100
- [256]
-
- FF
- [255]
-
- # fractions
- 1/2
- [0.5]
-
- -3/4
- [-0.75]
-
- # mixed fractions
- 1
- [1]
-
- 1/2
- [0.5]
-
- -3/4
- [-0.75]
-
- 1-3/4
- [1.75]
-
- # uuid
- 12345678-1234-5678-1234-567812345678
- [UUID('12345678-1234-5678-1234-567812345678')]
- """
-
- convertToInteger = tokenMap(int)
- """
- Parse action for converting parsed integers to Python int
- """
-
- convertToFloat = tokenMap(float)
- """
- Parse action for converting parsed numbers to Python float
- """
-
- integer = Word(nums).setName("integer").setParseAction(convertToInteger)
- """expression that parses an unsigned integer, returns an int"""
-
- hex_integer = Word(hexnums).setName("hex integer").setParseAction(tokenMap(int,16))
- """expression that parses a hexadecimal integer, returns an int"""
-
- signed_integer = Regex(r'[+-]?\d+').setName("signed integer").setParseAction(convertToInteger)
- """expression that parses an integer with optional leading sign, returns an int"""
-
- fraction = (signed_integer().setParseAction(convertToFloat) + '/' + signed_integer().setParseAction(convertToFloat)).setName("fraction")
- """fractional expression of an integer divided by an integer, returns a float"""
- fraction.addParseAction(lambda t: t[0]/t[-1])
-
- mixed_integer = (fraction | signed_integer + Optional(Optional('-').suppress() + fraction)).setName("fraction or mixed integer-fraction")
- """mixed integer of the form 'integer - fraction', with optional leading integer, returns float"""
- mixed_integer.addParseAction(sum)
-
- real = Regex(r'[+-]?\d+\.\d*').setName("real number").setParseAction(convertToFloat)
- """expression that parses a floating point number and returns a float"""
-
- sci_real = Regex(r'[+-]?\d+([eE][+-]?\d+|\.\d*([eE][+-]?\d+)?)').setName("real number with scientific notation").setParseAction(convertToFloat)
- """expression that parses a floating point number with optional scientific notation and returns a float"""
-
- # streamlining this expression makes the docs nicer-looking
- number = (sci_real | real | signed_integer).streamline()
- """any numeric expression, returns the corresponding Python type"""
-
- fnumber = Regex(r'[+-]?\d+\.?\d*([eE][+-]?\d+)?').setName("fnumber").setParseAction(convertToFloat)
- """any int or real number, returned as float"""
-
- identifier = Word(alphas+'_', alphanums+'_').setName("identifier")
- """typical code identifier (leading alpha or '_', followed by 0 or more alphas, nums, or '_')"""
-
- ipv4_address = Regex(r'(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})(\.(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})){3}').setName("IPv4 address")
- "IPv4 address (C{0.0.0.0 - 255.255.255.255})"
-
- _ipv6_part = Regex(r'[0-9a-fA-F]{1,4}').setName("hex_integer")
- _full_ipv6_address = (_ipv6_part + (':' + _ipv6_part)*7).setName("full IPv6 address")
- _short_ipv6_address = (Optional(_ipv6_part + (':' + _ipv6_part)*(0,6)) + "::" + Optional(_ipv6_part + (':' + _ipv6_part)*(0,6))).setName("short IPv6 address")
- _short_ipv6_address.addCondition(lambda t: sum(1 for tt in t if pyparsing_common._ipv6_part.matches(tt)) < 8)
- _mixed_ipv6_address = ("::ffff:" + ipv4_address).setName("mixed IPv6 address")
- ipv6_address = Combine((_full_ipv6_address | _mixed_ipv6_address | _short_ipv6_address).setName("IPv6 address")).setName("IPv6 address")
- "IPv6 address (long, short, or mixed form)"
-
- mac_address = Regex(r'[0-9a-fA-F]{2}([:.-])[0-9a-fA-F]{2}(?:\1[0-9a-fA-F]{2}){4}').setName("MAC address")
- "MAC address xx:xx:xx:xx:xx (may also have '-' or '.' delimiters)"
-
- @staticmethod
- def convertToDate(fmt="%Y-%m-%d"):
- """
- Helper to create a parse action for converting parsed date string to Python datetime.date
-
- Params -
- - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%d"})
-
- Example::
- date_expr = pyparsing_common.iso8601_date.copy()
- date_expr.setParseAction(pyparsing_common.convertToDate())
- print(date_expr.parseString("1999-12-31"))
- prints::
- [datetime.date(1999, 12, 31)]
- """
- def cvt_fn(s,l,t):
- try:
- return datetime.strptime(t[0], fmt).date()
- except ValueError as ve:
- raise ParseException(s, l, str(ve))
- return cvt_fn
-
- @staticmethod
- def convertToDatetime(fmt="%Y-%m-%dT%H:%M:%S.%f"):
- """
- Helper to create a parse action for converting parsed datetime string to Python datetime.datetime
-
- Params -
- - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%dT%H:%M:%S.%f"})
-
- Example::
- dt_expr = pyparsing_common.iso8601_datetime.copy()
- dt_expr.setParseAction(pyparsing_common.convertToDatetime())
- print(dt_expr.parseString("1999-12-31T23:59:59.999"))
- prints::
- [datetime.datetime(1999, 12, 31, 23, 59, 59, 999000)]
- """
- def cvt_fn(s,l,t):
- try:
- return datetime.strptime(t[0], fmt)
- except ValueError as ve:
- raise ParseException(s, l, str(ve))
- return cvt_fn
-
- iso8601_date = Regex(r'(?P<year>\d{4})(?:-(?P<month>\d\d)(?:-(?P<day>\d\d))?)?').setName("ISO8601 date")
- "ISO8601 date (C{yyyy-mm-dd})"
-
- iso8601_datetime = Regex(r'(?P<year>\d{4})-(?P<month>\d\d)-(?P<day>\d\d)[T ](?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d(\.\d*)?)?)?(?P<tz>Z|[+-]\d\d:?\d\d)?').setName("ISO8601 datetime")
- "ISO8601 datetime (C{yyyy-mm-ddThh:mm:ss.s(Z|+-00:00)}) - trailing seconds, milliseconds, and timezone optional; accepts separating C{'T'} or C{' '}"
-
- uuid = Regex(r'[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}').setName("UUID")
- "UUID (C{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx})"
-
- _html_stripper = anyOpenTag.suppress() | anyCloseTag.suppress()
- @staticmethod
- def stripHTMLTags(s, l, tokens):
- """
- Parse action to remove HTML tags from web page HTML source
-
- Example::
- # strip HTML links from normal text
- text = '<td>More info at the <a href="http://pyparsing.wikispaces.com">pyparsing</a> wiki page</td>'
- td,td_end = makeHTMLTags("TD")
- table_text = td + SkipTo(td_end).setParseAction(pyparsing_common.stripHTMLTags)("body") + td_end
-
- print(table_text.parseString(text).body) # -> 'More info at the pyparsing wiki page'
- """
- return pyparsing_common._html_stripper.transformString(tokens[0])
-
- _commasepitem = Combine(OneOrMore(~Literal(",") + ~LineEnd() + Word(printables, excludeChars=',')
- + Optional( White(" \t") ) ) ).streamline().setName("commaItem")
- comma_separated_list = delimitedList( Optional( quotedString.copy() | _commasepitem, default="") ).setName("comma separated list")
- """Predefined expression of 1 or more printable words or quoted strings, separated by commas."""
-
- upcaseTokens = staticmethod(tokenMap(lambda t: _ustr(t).upper()))
- """Parse action to convert tokens to upper case."""
-
- downcaseTokens = staticmethod(tokenMap(lambda t: _ustr(t).lower()))
- """Parse action to convert tokens to lower case."""
-
-
-if __name__ == "__main__":
-
- selectToken = CaselessLiteral("select")
- fromToken = CaselessLiteral("from")
-
- ident = Word(alphas, alphanums + "_$")
-
- columnName = delimitedList(ident, ".", combine=True).setParseAction(upcaseTokens)
- columnNameList = Group(delimitedList(columnName)).setName("columns")
- columnSpec = ('*' | columnNameList)
-
- tableName = delimitedList(ident, ".", combine=True).setParseAction(upcaseTokens)
- tableNameList = Group(delimitedList(tableName)).setName("tables")
-
- simpleSQL = selectToken("command") + columnSpec("columns") + fromToken + tableNameList("tables")
-
- # demo runTests method, including embedded comments in test string
- simpleSQL.runTests("""
- # '*' as column list and dotted table name
- select * from SYS.XYZZY
-
- # caseless match on "SELECT", and casts back to "select"
- SELECT * from XYZZY, ABC
-
- # list of column names, and mixed case SELECT keyword
- Select AA,BB,CC from Sys.dual
-
- # multiple tables
- Select A, B, C from Sys.dual, Table2
-
- # invalid SELECT keyword - should fail
- Xelect A, B, C from Sys.dual
-
- # incomplete command - should fail
- Select
-
- # invalid column name - should fail
- Select ^^^ frox Sys.dual
-
- """)
-
- pyparsing_common.number.runTests("""
- 100
- -100
- +100
- 3.14159
- 6.02e23
- 1e-12
- """)
-
- # any int or real number, returned as float
- pyparsing_common.fnumber.runTests("""
- 100
- -100
- +100
- 3.14159
- 6.02e23
- 1e-12
- """)
-
- pyparsing_common.hex_integer.runTests("""
- 100
- FF
- """)
-
- import uuid
- pyparsing_common.uuid.setParseAction(tokenMap(uuid.UUID))
- pyparsing_common.uuid.runTests("""
- 12345678-1234-5678-1234-567812345678
- """)
diff --git a/setuptools/_vendor/pyparsing/__init__.py b/setuptools/_vendor/pyparsing/__init__.py
new file mode 100644
index 00000000..45f334d0
--- /dev/null
+++ b/setuptools/_vendor/pyparsing/__init__.py
@@ -0,0 +1,331 @@
+# module pyparsing.py
+#
+# Copyright (c) 2003-2022 Paul T. McGuire
+#
+# 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.
+#
+
+__doc__ = """
+pyparsing module - Classes and methods to define and execute parsing grammars
+=============================================================================
+
+The pyparsing module is an alternative approach to creating and
+executing simple grammars, vs. the traditional lex/yacc approach, or the
+use of regular expressions. With pyparsing, you don't need to learn
+a new syntax for defining grammars or matching expressions - the parsing
+module provides a library of classes that you use to construct the
+grammar directly in Python.
+
+Here is a program to parse "Hello, World!" (or any greeting of the form
+``"<salutation>, <addressee>!"``), built up using :class:`Word`,
+:class:`Literal`, and :class:`And` elements
+(the :meth:`'+'<ParserElement.__add__>` operators create :class:`And` expressions,
+and the strings are auto-converted to :class:`Literal` expressions)::
+
+ from pyparsing import Word, alphas
+
+ # define grammar of a greeting
+ greet = Word(alphas) + "," + Word(alphas) + "!"
+
+ hello = "Hello, World!"
+ print(hello, "->", greet.parse_string(hello))
+
+The program outputs the following::
+
+ Hello, World! -> ['Hello', ',', 'World', '!']
+
+The Python representation of the grammar is quite readable, owing to the
+self-explanatory class names, and the use of :class:`'+'<And>`,
+:class:`'|'<MatchFirst>`, :class:`'^'<Or>` and :class:`'&'<Each>` operators.
+
+The :class:`ParseResults` object returned from
+:class:`ParserElement.parseString` can be
+accessed as a nested list, a dictionary, or an object with named
+attributes.
+
+The pyparsing module handles some of the problems that are typically
+vexing when writing text parsers:
+
+ - extra or missing whitespace (the above program will also handle
+ "Hello,World!", "Hello , World !", etc.)
+ - quoted strings
+ - embedded comments
+
+
+Getting Started -
+-----------------
+Visit the classes :class:`ParserElement` and :class:`ParseResults` to
+see the base classes that most other pyparsing
+classes inherit from. Use the docstrings for examples of how to:
+
+ - construct literal match expressions from :class:`Literal` and
+ :class:`CaselessLiteral` classes
+ - construct character word-group expressions using the :class:`Word`
+ class
+ - see how to create repetitive expressions using :class:`ZeroOrMore`
+ and :class:`OneOrMore` classes
+ - use :class:`'+'<And>`, :class:`'|'<MatchFirst>`, :class:`'^'<Or>`,
+ and :class:`'&'<Each>` operators to combine simple expressions into
+ more complex ones
+ - associate names with your parsed results using
+ :class:`ParserElement.setResultsName`
+ - access the parsed data, which is returned as a :class:`ParseResults`
+ object
+ - find some helpful expression short-cuts like :class:`delimitedList`
+ and :class:`oneOf`
+ - find more useful common expressions in the :class:`pyparsing_common`
+ namespace class
+"""
+from typing import NamedTuple
+
+
+class version_info(NamedTuple):
+ major: int
+ minor: int
+ micro: int
+ releaselevel: str
+ serial: int
+
+ @property
+ def __version__(self):
+ return (
+ "{}.{}.{}".format(self.major, self.minor, self.micro)
+ + (
+ "{}{}{}".format(
+ "r" if self.releaselevel[0] == "c" else "",
+ self.releaselevel[0],
+ self.serial,
+ ),
+ "",
+ )[self.releaselevel == "final"]
+ )
+
+ def __str__(self):
+ return "{} {} / {}".format(__name__, self.__version__, __version_time__)
+
+ def __repr__(self):
+ return "{}.{}({})".format(
+ __name__,
+ type(self).__name__,
+ ", ".join("{}={!r}".format(*nv) for nv in zip(self._fields, self)),
+ )
+
+
+__version_info__ = version_info(3, 0, 8, "final", 0)
+__version_time__ = "09 Apr 2022 23:29 UTC"
+__version__ = __version_info__.__version__
+__versionTime__ = __version_time__
+__author__ = "Paul McGuire <ptmcg.gm+pyparsing@gmail.com>"
+
+from .util import *
+from .exceptions import *
+from .actions import *
+from .core import __diag__, __compat__
+from .results import *
+from .core import *
+from .core import _builtin_exprs as core_builtin_exprs
+from .helpers import *
+from .helpers import _builtin_exprs as helper_builtin_exprs
+
+from .unicode import unicode_set, UnicodeRangeList, pyparsing_unicode as unicode
+from .testing import pyparsing_test as testing
+from .common import (
+ pyparsing_common as common,
+ _builtin_exprs as common_builtin_exprs,
+)
+
+# define backward compat synonyms
+if "pyparsing_unicode" not in globals():
+ pyparsing_unicode = unicode
+if "pyparsing_common" not in globals():
+ pyparsing_common = common
+if "pyparsing_test" not in globals():
+ pyparsing_test = testing
+
+core_builtin_exprs += common_builtin_exprs + helper_builtin_exprs
+
+
+__all__ = [
+ "__version__",
+ "__version_time__",
+ "__author__",
+ "__compat__",
+ "__diag__",
+ "And",
+ "AtLineStart",
+ "AtStringStart",
+ "CaselessKeyword",
+ "CaselessLiteral",
+ "CharsNotIn",
+ "Combine",
+ "Dict",
+ "Each",
+ "Empty",
+ "FollowedBy",
+ "Forward",
+ "GoToColumn",
+ "Group",
+ "IndentedBlock",
+ "Keyword",
+ "LineEnd",
+ "LineStart",
+ "Literal",
+ "Located",
+ "PrecededBy",
+ "MatchFirst",
+ "NoMatch",
+ "NotAny",
+ "OneOrMore",
+ "OnlyOnce",
+ "OpAssoc",
+ "Opt",
+ "Optional",
+ "Or",
+ "ParseBaseException",
+ "ParseElementEnhance",
+ "ParseException",
+ "ParseExpression",
+ "ParseFatalException",
+ "ParseResults",
+ "ParseSyntaxException",
+ "ParserElement",
+ "PositionToken",
+ "QuotedString",
+ "RecursiveGrammarException",
+ "Regex",
+ "SkipTo",
+ "StringEnd",
+ "StringStart",
+ "Suppress",
+ "Token",
+ "TokenConverter",
+ "White",
+ "Word",
+ "WordEnd",
+ "WordStart",
+ "ZeroOrMore",
+ "Char",
+ "alphanums",
+ "alphas",
+ "alphas8bit",
+ "any_close_tag",
+ "any_open_tag",
+ "c_style_comment",
+ "col",
+ "common_html_entity",
+ "counted_array",
+ "cpp_style_comment",
+ "dbl_quoted_string",
+ "dbl_slash_comment",
+ "delimited_list",
+ "dict_of",
+ "empty",
+ "hexnums",
+ "html_comment",
+ "identchars",
+ "identbodychars",
+ "java_style_comment",
+ "line",
+ "line_end",
+ "line_start",
+ "lineno",
+ "make_html_tags",
+ "make_xml_tags",
+ "match_only_at_col",
+ "match_previous_expr",
+ "match_previous_literal",
+ "nested_expr",
+ "null_debug_action",
+ "nums",
+ "one_of",
+ "printables",
+ "punc8bit",
+ "python_style_comment",
+ "quoted_string",
+ "remove_quotes",
+ "replace_with",
+ "replace_html_entity",
+ "rest_of_line",
+ "sgl_quoted_string",
+ "srange",
+ "string_end",
+ "string_start",
+ "trace_parse_action",
+ "unicode_string",
+ "with_attribute",
+ "indentedBlock",
+ "original_text_for",
+ "ungroup",
+ "infix_notation",
+ "locatedExpr",
+ "with_class",
+ "CloseMatch",
+ "token_map",
+ "pyparsing_common",
+ "pyparsing_unicode",
+ "unicode_set",
+ "condition_as_parse_action",
+ "pyparsing_test",
+ # pre-PEP8 compatibility names
+ "__versionTime__",
+ "anyCloseTag",
+ "anyOpenTag",
+ "cStyleComment",
+ "commonHTMLEntity",
+ "countedArray",
+ "cppStyleComment",
+ "dblQuotedString",
+ "dblSlashComment",
+ "delimitedList",
+ "dictOf",
+ "htmlComment",
+ "javaStyleComment",
+ "lineEnd",
+ "lineStart",
+ "makeHTMLTags",
+ "makeXMLTags",
+ "matchOnlyAtCol",
+ "matchPreviousExpr",
+ "matchPreviousLiteral",
+ "nestedExpr",
+ "nullDebugAction",
+ "oneOf",
+ "opAssoc",
+ "pythonStyleComment",
+ "quotedString",
+ "removeQuotes",
+ "replaceHTMLEntity",
+ "replaceWith",
+ "restOfLine",
+ "sglQuotedString",
+ "stringEnd",
+ "stringStart",
+ "traceParseAction",
+ "unicodeString",
+ "withAttribute",
+ "indentedBlock",
+ "originalTextFor",
+ "infixNotation",
+ "locatedExpr",
+ "withClass",
+ "tokenMap",
+ "conditionAsParseAction",
+ "autoname_elements",
+]
diff --git a/setuptools/_vendor/pyparsing/actions.py b/setuptools/_vendor/pyparsing/actions.py
new file mode 100644
index 00000000..2bcc5502
--- /dev/null
+++ b/setuptools/_vendor/pyparsing/actions.py
@@ -0,0 +1,207 @@
+# actions.py
+
+from .exceptions import ParseException
+from .util import col
+
+
+class OnlyOnce:
+ """
+ Wrapper for parse actions, to ensure they are only called once.
+ """
+
+ def __init__(self, method_call):
+ from .core import _trim_arity
+
+ self.callable = _trim_arity(method_call)
+ self.called = False
+
+ def __call__(self, s, l, t):
+ if not self.called:
+ results = self.callable(s, l, t)
+ self.called = True
+ return results
+ raise ParseException(s, l, "OnlyOnce obj called multiple times w/out reset")
+
+ def reset(self):
+ """
+ Allow the associated parse action to be called once more.
+ """
+
+ self.called = False
+
+
+def match_only_at_col(n):
+ """
+ Helper method for defining parse actions that require matching at
+ a specific column in the input text.
+ """
+
+ def verify_col(strg, locn, toks):
+ if col(locn, strg) != n:
+ raise ParseException(strg, locn, "matched token not at column {}".format(n))
+
+ return verify_col
+
+
+def replace_with(repl_str):
+ """
+ Helper method for common parse actions that simply return
+ a literal value. Especially useful when used with
+ :class:`transform_string<ParserElement.transform_string>` ().
+
+ Example::
+
+ num = Word(nums).set_parse_action(lambda toks: int(toks[0]))
+ na = one_of("N/A NA").set_parse_action(replace_with(math.nan))
+ term = na | num
+
+ OneOrMore(term).parse_string("324 234 N/A 234") # -> [324, 234, nan, 234]
+ """
+ return lambda s, l, t: [repl_str]
+
+
+def remove_quotes(s, l, t):
+ """
+ Helper parse action for removing quotation marks from parsed
+ quoted strings.
+
+ Example::
+
+ # by default, quotation marks are included in parsed results
+ quoted_string.parse_string("'Now is the Winter of our Discontent'") # -> ["'Now is the Winter of our Discontent'"]
+
+ # use remove_quotes to strip quotation marks from parsed results
+ quoted_string.set_parse_action(remove_quotes)
+ quoted_string.parse_string("'Now is the Winter of our Discontent'") # -> ["Now is the Winter of our Discontent"]
+ """
+ return t[0][1:-1]
+
+
+def with_attribute(*args, **attr_dict):
+ """
+ Helper to create a validating parse action to be used with start
+ tags created with :class:`make_xml_tags` or
+ :class:`make_html_tags`. Use ``with_attribute`` to qualify
+ a starting tag with a required attribute value, to avoid false
+ matches on common tags such as ``<TD>`` or ``<DIV>``.
+
+ Call ``with_attribute`` with a series of attribute names and
+ values. Specify the list of filter attributes names and values as:
+
+ - keyword arguments, as in ``(align="right")``, or
+ - as an explicit dict with ``**`` operator, when an attribute
+ name is also a Python reserved word, as in ``**{"class":"Customer", "align":"right"}``
+ - a list of name-value tuples, as in ``(("ns1:class", "Customer"), ("ns2:align", "right"))``
+
+ For attribute names with a namespace prefix, you must use the second
+ form. Attribute names are matched insensitive to upper/lower case.
+
+ If just testing for ``class`` (with or without a namespace), use
+ :class:`with_class`.
+
+ To verify that the attribute exists, but without specifying a value,
+ pass ``with_attribute.ANY_VALUE`` as the value.
+
+ Example::
+
+ html = '''
+ <div>
+ Some text
+ <div type="grid">1 4 0 1 0</div>
+ <div type="graph">1,3 2,3 1,1</div>
+ <div>this has no type</div>
+ </div>
+
+ '''
+ div,div_end = make_html_tags("div")
+
+ # only match div tag having a type attribute with value "grid"
+ div_grid = div().set_parse_action(with_attribute(type="grid"))
+ grid_expr = div_grid + SkipTo(div | div_end)("body")
+ for grid_header in grid_expr.search_string(html):
+ print(grid_header.body)
+
+ # construct a match with any div tag having a type attribute, regardless of the value
+ div_any_type = div().set_parse_action(with_attribute(type=with_attribute.ANY_VALUE))
+ div_expr = div_any_type + SkipTo(div | div_end)("body")
+ for div_header in div_expr.search_string(html):
+ print(div_header.body)
+
+ prints::
+
+ 1 4 0 1 0
+
+ 1 4 0 1 0
+ 1,3 2,3 1,1
+ """
+ if args:
+ attrs = args[:]
+ else:
+ attrs = attr_dict.items()
+ attrs = [(k, v) for k, v in attrs]
+
+ def pa(s, l, tokens):
+ for attrName, attrValue in attrs:
+ if attrName not in tokens:
+ raise ParseException(s, l, "no matching attribute " + attrName)
+ if attrValue != with_attribute.ANY_VALUE and tokens[attrName] != attrValue:
+ raise ParseException(
+ s,
+ l,
+ "attribute {!r} has value {!r}, must be {!r}".format(
+ attrName, tokens[attrName], attrValue
+ ),
+ )
+
+ return pa
+
+
+with_attribute.ANY_VALUE = object()
+
+
+def with_class(classname, namespace=""):
+ """
+ Simplified version of :class:`with_attribute` when
+ matching on a div class - made difficult because ``class`` is
+ a reserved word in Python.
+
+ Example::
+
+ html = '''
+ <div>
+ Some text
+ <div class="grid">1 4 0 1 0</div>
+ <div class="graph">1,3 2,3 1,1</div>
+ <div>this &lt;div&gt; has no class</div>
+ </div>
+
+ '''
+ div,div_end = make_html_tags("div")
+ div_grid = div().set_parse_action(with_class("grid"))
+
+ grid_expr = div_grid + SkipTo(div | div_end)("body")
+ for grid_header in grid_expr.search_string(html):
+ print(grid_header.body)
+
+ div_any_type = div().set_parse_action(with_class(withAttribute.ANY_VALUE))
+ div_expr = div_any_type + SkipTo(div | div_end)("body")
+ for div_header in div_expr.search_string(html):
+ print(div_header.body)
+
+ prints::
+
+ 1 4 0 1 0
+
+ 1 4 0 1 0
+ 1,3 2,3 1,1
+ """
+ classattr = "{}:class".format(namespace) if namespace else "class"
+ return with_attribute(**{classattr: classname})
+
+
+# pre-PEP8 compatibility symbols
+replaceWith = replace_with
+removeQuotes = remove_quotes
+withAttribute = with_attribute
+withClass = with_class
+matchOnlyAtCol = match_only_at_col
diff --git a/setuptools/_vendor/pyparsing/common.py b/setuptools/_vendor/pyparsing/common.py
new file mode 100644
index 00000000..1859fb79
--- /dev/null
+++ b/setuptools/_vendor/pyparsing/common.py
@@ -0,0 +1,424 @@
+# common.py
+from .core import *
+from .helpers import delimited_list, any_open_tag, any_close_tag
+from datetime import datetime
+
+
+# some other useful expressions - using lower-case class name since we are really using this as a namespace
+class pyparsing_common:
+ """Here are some common low-level expressions that may be useful in
+ jump-starting parser development:
+
+ - numeric forms (:class:`integers<integer>`, :class:`reals<real>`,
+ :class:`scientific notation<sci_real>`)
+ - common :class:`programming identifiers<identifier>`
+ - network addresses (:class:`MAC<mac_address>`,
+ :class:`IPv4<ipv4_address>`, :class:`IPv6<ipv6_address>`)
+ - ISO8601 :class:`dates<iso8601_date>` and
+ :class:`datetime<iso8601_datetime>`
+ - :class:`UUID<uuid>`
+ - :class:`comma-separated list<comma_separated_list>`
+ - :class:`url`
+
+ Parse actions:
+
+ - :class:`convertToInteger`
+ - :class:`convertToFloat`
+ - :class:`convertToDate`
+ - :class:`convertToDatetime`
+ - :class:`stripHTMLTags`
+ - :class:`upcaseTokens`
+ - :class:`downcaseTokens`
+
+ Example::
+
+ pyparsing_common.number.runTests('''
+ # any int or real number, returned as the appropriate type
+ 100
+ -100
+ +100
+ 3.14159
+ 6.02e23
+ 1e-12
+ ''')
+
+ pyparsing_common.fnumber.runTests('''
+ # any int or real number, returned as float
+ 100
+ -100
+ +100
+ 3.14159
+ 6.02e23
+ 1e-12
+ ''')
+
+ pyparsing_common.hex_integer.runTests('''
+ # hex numbers
+ 100
+ FF
+ ''')
+
+ pyparsing_common.fraction.runTests('''
+ # fractions
+ 1/2
+ -3/4
+ ''')
+
+ pyparsing_common.mixed_integer.runTests('''
+ # mixed fractions
+ 1
+ 1/2
+ -3/4
+ 1-3/4
+ ''')
+
+ import uuid
+ pyparsing_common.uuid.setParseAction(tokenMap(uuid.UUID))
+ pyparsing_common.uuid.runTests('''
+ # uuid
+ 12345678-1234-5678-1234-567812345678
+ ''')
+
+ prints::
+
+ # any int or real number, returned as the appropriate type
+ 100
+ [100]
+
+ -100
+ [-100]
+
+ +100
+ [100]
+
+ 3.14159
+ [3.14159]
+
+ 6.02e23
+ [6.02e+23]
+
+ 1e-12
+ [1e-12]
+
+ # any int or real number, returned as float
+ 100
+ [100.0]
+
+ -100
+ [-100.0]
+
+ +100
+ [100.0]
+
+ 3.14159
+ [3.14159]
+
+ 6.02e23
+ [6.02e+23]
+
+ 1e-12
+ [1e-12]
+
+ # hex numbers
+ 100
+ [256]
+
+ FF
+ [255]
+
+ # fractions
+ 1/2
+ [0.5]
+
+ -3/4
+ [-0.75]
+
+ # mixed fractions
+ 1
+ [1]
+
+ 1/2
+ [0.5]
+
+ -3/4
+ [-0.75]
+
+ 1-3/4
+ [1.75]
+
+ # uuid
+ 12345678-1234-5678-1234-567812345678
+ [UUID('12345678-1234-5678-1234-567812345678')]
+ """
+
+ convert_to_integer = token_map(int)
+ """
+ Parse action for converting parsed integers to Python int
+ """
+
+ convert_to_float = token_map(float)
+ """
+ Parse action for converting parsed numbers to Python float
+ """
+
+ integer = Word(nums).set_name("integer").set_parse_action(convert_to_integer)
+ """expression that parses an unsigned integer, returns an int"""
+
+ hex_integer = (
+ Word(hexnums).set_name("hex integer").set_parse_action(token_map(int, 16))
+ )
+ """expression that parses a hexadecimal integer, returns an int"""
+
+ signed_integer = (
+ Regex(r"[+-]?\d+")
+ .set_name("signed integer")
+ .set_parse_action(convert_to_integer)
+ )
+ """expression that parses an integer with optional leading sign, returns an int"""
+
+ fraction = (
+ signed_integer().set_parse_action(convert_to_float)
+ + "/"
+ + signed_integer().set_parse_action(convert_to_float)
+ ).set_name("fraction")
+ """fractional expression of an integer divided by an integer, returns a float"""
+ fraction.add_parse_action(lambda tt: tt[0] / tt[-1])
+
+ mixed_integer = (
+ fraction | signed_integer + Opt(Opt("-").suppress() + fraction)
+ ).set_name("fraction or mixed integer-fraction")
+ """mixed integer of the form 'integer - fraction', with optional leading integer, returns float"""
+ mixed_integer.add_parse_action(sum)
+
+ real = (
+ Regex(r"[+-]?(?:\d+\.\d*|\.\d+)")
+ .set_name("real number")
+ .set_parse_action(convert_to_float)
+ )
+ """expression that parses a floating point number and returns a float"""
+
+ sci_real = (
+ Regex(r"[+-]?(?:\d+(?:[eE][+-]?\d+)|(?:\d+\.\d*|\.\d+)(?:[eE][+-]?\d+)?)")
+ .set_name("real number with scientific notation")
+ .set_parse_action(convert_to_float)
+ )
+ """expression that parses a floating point number with optional
+ scientific notation and returns a float"""
+
+ # streamlining this expression makes the docs nicer-looking
+ number = (sci_real | real | signed_integer).setName("number").streamline()
+ """any numeric expression, returns the corresponding Python type"""
+
+ fnumber = (
+ Regex(r"[+-]?\d+\.?\d*([eE][+-]?\d+)?")
+ .set_name("fnumber")
+ .set_parse_action(convert_to_float)
+ )
+ """any int or real number, returned as float"""
+
+ identifier = Word(identchars, identbodychars).set_name("identifier")
+ """typical code identifier (leading alpha or '_', followed by 0 or more alphas, nums, or '_')"""
+
+ ipv4_address = Regex(
+ r"(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})(\.(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})){3}"
+ ).set_name("IPv4 address")
+ "IPv4 address (``0.0.0.0 - 255.255.255.255``)"
+
+ _ipv6_part = Regex(r"[0-9a-fA-F]{1,4}").set_name("hex_integer")
+ _full_ipv6_address = (_ipv6_part + (":" + _ipv6_part) * 7).set_name(
+ "full IPv6 address"
+ )
+ _short_ipv6_address = (
+ Opt(_ipv6_part + (":" + _ipv6_part) * (0, 6))
+ + "::"
+ + Opt(_ipv6_part + (":" + _ipv6_part) * (0, 6))
+ ).set_name("short IPv6 address")
+ _short_ipv6_address.add_condition(
+ lambda t: sum(1 for tt in t if pyparsing_common._ipv6_part.matches(tt)) < 8
+ )
+ _mixed_ipv6_address = ("::ffff:" + ipv4_address).set_name("mixed IPv6 address")
+ ipv6_address = Combine(
+ (_full_ipv6_address | _mixed_ipv6_address | _short_ipv6_address).set_name(
+ "IPv6 address"
+ )
+ ).set_name("IPv6 address")
+ "IPv6 address (long, short, or mixed form)"
+
+ mac_address = Regex(
+ r"[0-9a-fA-F]{2}([:.-])[0-9a-fA-F]{2}(?:\1[0-9a-fA-F]{2}){4}"
+ ).set_name("MAC address")
+ "MAC address xx:xx:xx:xx:xx (may also have '-' or '.' delimiters)"
+
+ @staticmethod
+ def convert_to_date(fmt: str = "%Y-%m-%d"):
+ """
+ Helper to create a parse action for converting parsed date string to Python datetime.date
+
+ Params -
+ - fmt - format to be passed to datetime.strptime (default= ``"%Y-%m-%d"``)
+
+ Example::
+
+ date_expr = pyparsing_common.iso8601_date.copy()
+ date_expr.setParseAction(pyparsing_common.convertToDate())
+ print(date_expr.parseString("1999-12-31"))
+
+ prints::
+
+ [datetime.date(1999, 12, 31)]
+ """
+
+ def cvt_fn(ss, ll, tt):
+ try:
+ return datetime.strptime(tt[0], fmt).date()
+ except ValueError as ve:
+ raise ParseException(ss, ll, str(ve))
+
+ return cvt_fn
+
+ @staticmethod
+ def convert_to_datetime(fmt: str = "%Y-%m-%dT%H:%M:%S.%f"):
+ """Helper to create a parse action for converting parsed
+ datetime string to Python datetime.datetime
+
+ Params -
+ - fmt - format to be passed to datetime.strptime (default= ``"%Y-%m-%dT%H:%M:%S.%f"``)
+
+ Example::
+
+ dt_expr = pyparsing_common.iso8601_datetime.copy()
+ dt_expr.setParseAction(pyparsing_common.convertToDatetime())
+ print(dt_expr.parseString("1999-12-31T23:59:59.999"))
+
+ prints::
+
+ [datetime.datetime(1999, 12, 31, 23, 59, 59, 999000)]
+ """
+
+ def cvt_fn(s, l, t):
+ try:
+ return datetime.strptime(t[0], fmt)
+ except ValueError as ve:
+ raise ParseException(s, l, str(ve))
+
+ return cvt_fn
+
+ iso8601_date = Regex(
+ r"(?P<year>\d{4})(?:-(?P<month>\d\d)(?:-(?P<day>\d\d))?)?"
+ ).set_name("ISO8601 date")
+ "ISO8601 date (``yyyy-mm-dd``)"
+
+ iso8601_datetime = Regex(
+ r"(?P<year>\d{4})-(?P<month>\d\d)-(?P<day>\d\d)[T ](?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d(\.\d*)?)?)?(?P<tz>Z|[+-]\d\d:?\d\d)?"
+ ).set_name("ISO8601 datetime")
+ "ISO8601 datetime (``yyyy-mm-ddThh:mm:ss.s(Z|+-00:00)``) - trailing seconds, milliseconds, and timezone optional; accepts separating ``'T'`` or ``' '``"
+
+ uuid = Regex(r"[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}").set_name("UUID")
+ "UUID (``xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx``)"
+
+ _html_stripper = any_open_tag.suppress() | any_close_tag.suppress()
+
+ @staticmethod
+ def strip_html_tags(s: str, l: int, tokens: ParseResults):
+ """Parse action to remove HTML tags from web page HTML source
+
+ Example::
+
+ # strip HTML links from normal text
+ text = '<td>More info at the <a href="https://github.com/pyparsing/pyparsing/wiki">pyparsing</a> wiki page</td>'
+ td, td_end = makeHTMLTags("TD")
+ table_text = td + SkipTo(td_end).setParseAction(pyparsing_common.stripHTMLTags)("body") + td_end
+ print(table_text.parseString(text).body)
+
+ Prints::
+
+ More info at the pyparsing wiki page
+ """
+ return pyparsing_common._html_stripper.transform_string(tokens[0])
+
+ _commasepitem = (
+ Combine(
+ OneOrMore(
+ ~Literal(",")
+ + ~LineEnd()
+ + Word(printables, exclude_chars=",")
+ + Opt(White(" \t") + ~FollowedBy(LineEnd() | ","))
+ )
+ )
+ .streamline()
+ .set_name("commaItem")
+ )
+ comma_separated_list = delimited_list(
+ Opt(quoted_string.copy() | _commasepitem, default="")
+ ).set_name("comma separated list")
+ """Predefined expression of 1 or more printable words or quoted strings, separated by commas."""
+
+ upcase_tokens = staticmethod(token_map(lambda t: t.upper()))
+ """Parse action to convert tokens to upper case."""
+
+ downcase_tokens = staticmethod(token_map(lambda t: t.lower()))
+ """Parse action to convert tokens to lower case."""
+
+ # fmt: off
+ url = Regex(
+ # https://mathiasbynens.be/demo/url-regex
+ # https://gist.github.com/dperini/729294
+ r"^" +
+ # protocol identifier (optional)
+ # short syntax // still required
+ r"(?:(?:(?P<scheme>https?|ftp):)?\/\/)" +
+ # user:pass BasicAuth (optional)
+ r"(?:(?P<auth>\S+(?::\S*)?)@)?" +
+ r"(?P<host>" +
+ # IP address exclusion
+ # private & local networks
+ r"(?!(?:10|127)(?:\.\d{1,3}){3})" +
+ r"(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})" +
+ r"(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})" +
+ # IP address dotted notation octets
+ # excludes loopback network 0.0.0.0
+ # excludes reserved space >= 224.0.0.0
+ # excludes network & broadcast addresses
+ # (first & last IP address of each class)
+ r"(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])" +
+ r"(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}" +
+ r"(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))" +
+ r"|" +
+ # host & domain names, may end with dot
+ # can be replaced by a shortest alternative
+ # (?![-_])(?:[-\w\u00a1-\uffff]{0,63}[^-_]\.)+
+ r"(?:" +
+ r"(?:" +
+ r"[a-z0-9\u00a1-\uffff]" +
+ r"[a-z0-9\u00a1-\uffff_-]{0,62}" +
+ r")?" +
+ r"[a-z0-9\u00a1-\uffff]\." +
+ r")+" +
+ # TLD identifier name, may end with dot
+ r"(?:[a-z\u00a1-\uffff]{2,}\.?)" +
+ r")" +
+ # port number (optional)
+ r"(:(?P<port>\d{2,5}))?" +
+ # resource path (optional)
+ r"(?P<path>\/[^?# ]*)?" +
+ # query string (optional)
+ r"(\?(?P<query>[^#]*))?" +
+ # fragment (optional)
+ r"(#(?P<fragment>\S*))?" +
+ r"$"
+ ).set_name("url")
+ # fmt: on
+
+ # pre-PEP8 compatibility names
+ convertToInteger = convert_to_integer
+ convertToFloat = convert_to_float
+ convertToDate = convert_to_date
+ convertToDatetime = convert_to_datetime
+ stripHTMLTags = strip_html_tags
+ upcaseTokens = upcase_tokens
+ downcaseTokens = downcase_tokens
+
+
+_builtin_exprs = [
+ v for v in vars(pyparsing_common).values() if isinstance(v, ParserElement)
+]
diff --git a/setuptools/_vendor/pyparsing/core.py b/setuptools/_vendor/pyparsing/core.py
new file mode 100644
index 00000000..454bd57d
--- /dev/null
+++ b/setuptools/_vendor/pyparsing/core.py
@@ -0,0 +1,5812 @@
+#
+# core.py
+#
+import os
+from typing import (
+ Optional as OptionalType,
+ Iterable as IterableType,
+ NamedTuple,
+ Union,
+ Callable,
+ Any,
+ Generator,
+ Tuple,
+ List,
+ TextIO,
+ Set,
+ Dict as DictType,
+ Sequence,
+)
+from abc import ABC, abstractmethod
+from enum import Enum
+import string
+import copy
+import warnings
+import re
+import sys
+from collections.abc import Iterable
+import traceback
+import types
+from operator import itemgetter
+from functools import wraps
+from threading import RLock
+from pathlib import Path
+
+from .util import (
+ _FifoCache,
+ _UnboundedCache,
+ __config_flags,
+ _collapse_string_to_ranges,
+ _escape_regex_range_chars,
+ _bslash,
+ _flatten,
+ LRUMemo as _LRUMemo,
+ UnboundedMemo as _UnboundedMemo,
+)
+from .exceptions import *
+from .actions import *
+from .results import ParseResults, _ParseResultsWithOffset
+from .unicode import pyparsing_unicode
+
+_MAX_INT = sys.maxsize
+str_type: Tuple[type, ...] = (str, bytes)
+
+#
+# Copyright (c) 2003-2022 Paul T. McGuire
+#
+# 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.
+#
+
+
+if sys.version_info >= (3, 8):
+ from functools import cached_property
+else:
+
+ class cached_property:
+ def __init__(self, func):
+ self._func = func
+
+ def __get__(self, instance, owner=None):
+ ret = instance.__dict__[self._func.__name__] = self._func(instance)
+ return ret
+
+
+class __compat__(__config_flags):
+ """
+ A cross-version compatibility configuration for pyparsing features that will be
+ released in a future version. By setting values in this configuration to True,
+ those features can be enabled in prior versions for compatibility development
+ and testing.
+
+ - ``collect_all_And_tokens`` - flag to enable fix for Issue #63 that fixes erroneous grouping
+ of results names when an :class:`And` expression is nested within an :class:`Or` or :class:`MatchFirst`;
+ maintained for compatibility, but setting to ``False`` no longer restores pre-2.3.1
+ behavior
+ """
+
+ _type_desc = "compatibility"
+
+ collect_all_And_tokens = True
+
+ _all_names = [__ for __ in locals() if not __.startswith("_")]
+ _fixed_names = """
+ collect_all_And_tokens
+ """.split()
+
+
+class __diag__(__config_flags):
+ _type_desc = "diagnostic"
+
+ warn_multiple_tokens_in_named_alternation = False
+ warn_ungrouped_named_tokens_in_collection = False
+ warn_name_set_on_empty_Forward = False
+ warn_on_parse_using_empty_Forward = False
+ warn_on_assignment_to_Forward = False
+ warn_on_multiple_string_args_to_oneof = False
+ warn_on_match_first_with_lshift_operator = False
+ enable_debug_on_named_expressions = False
+
+ _all_names = [__ for __ in locals() if not __.startswith("_")]
+ _warning_names = [name for name in _all_names if name.startswith("warn")]
+ _debug_names = [name for name in _all_names if name.startswith("enable_debug")]
+
+ @classmethod
+ def enable_all_warnings(cls) -> None:
+ for name in cls._warning_names:
+ cls.enable(name)
+
+
+class Diagnostics(Enum):
+ """
+ Diagnostic configuration (all default to disabled)
+ - ``warn_multiple_tokens_in_named_alternation`` - flag to enable warnings when a results
+ name is defined on a :class:`MatchFirst` or :class:`Or` expression with one or more :class:`And` subexpressions
+ - ``warn_ungrouped_named_tokens_in_collection`` - flag to enable warnings when a results
+ name is defined on a containing expression with ungrouped subexpressions that also
+ have results names
+ - ``warn_name_set_on_empty_Forward`` - flag to enable warnings when a :class:`Forward` is defined
+ with a results name, but has no contents defined
+ - ``warn_on_parse_using_empty_Forward`` - flag to enable warnings when a :class:`Forward` is
+ defined in a grammar but has never had an expression attached to it
+ - ``warn_on_assignment_to_Forward`` - flag to enable warnings when a :class:`Forward` is defined
+ but is overwritten by assigning using ``'='`` instead of ``'<<='`` or ``'<<'``
+ - ``warn_on_multiple_string_args_to_oneof`` - flag to enable warnings when :class:`one_of` is
+ incorrectly called with multiple str arguments
+ - ``enable_debug_on_named_expressions`` - flag to auto-enable debug on all subsequent
+ calls to :class:`ParserElement.set_name`
+
+ Diagnostics are enabled/disabled by calling :class:`enable_diag` and :class:`disable_diag`.
+ All warnings can be enabled by calling :class:`enable_all_warnings`.
+ """
+
+ warn_multiple_tokens_in_named_alternation = 0
+ warn_ungrouped_named_tokens_in_collection = 1
+ warn_name_set_on_empty_Forward = 2
+ warn_on_parse_using_empty_Forward = 3
+ warn_on_assignment_to_Forward = 4
+ warn_on_multiple_string_args_to_oneof = 5
+ warn_on_match_first_with_lshift_operator = 6
+ enable_debug_on_named_expressions = 7
+
+
+def enable_diag(diag_enum: Diagnostics) -> None:
+ """
+ Enable a global pyparsing diagnostic flag (see :class:`Diagnostics`).
+ """
+ __diag__.enable(diag_enum.name)
+
+
+def disable_diag(diag_enum: Diagnostics) -> None:
+ """
+ Disable a global pyparsing diagnostic flag (see :class:`Diagnostics`).
+ """
+ __diag__.disable(diag_enum.name)
+
+
+def enable_all_warnings() -> None:
+ """
+ Enable all global pyparsing diagnostic warnings (see :class:`Diagnostics`).
+ """
+ __diag__.enable_all_warnings()
+
+
+# hide abstract class
+del __config_flags
+
+
+def _should_enable_warnings(
+ cmd_line_warn_options: IterableType[str], warn_env_var: OptionalType[str]
+) -> bool:
+ enable = bool(warn_env_var)
+ for warn_opt in cmd_line_warn_options:
+ w_action, w_message, w_category, w_module, w_line = (warn_opt + "::::").split(
+ ":"
+ )[:5]
+ if not w_action.lower().startswith("i") and (
+ not (w_message or w_category or w_module) or w_module == "pyparsing"
+ ):
+ enable = True
+ elif w_action.lower().startswith("i") and w_module in ("pyparsing", ""):
+ enable = False
+ return enable
+
+
+if _should_enable_warnings(
+ sys.warnoptions, os.environ.get("PYPARSINGENABLEALLWARNINGS")
+):
+ enable_all_warnings()
+
+
+# build list of single arg builtins, that can be used as parse actions
+_single_arg_builtins = {
+ sum,
+ len,
+ sorted,
+ reversed,
+ list,
+ tuple,
+ set,
+ any,
+ all,
+ min,
+ max,
+}
+
+_generatorType = types.GeneratorType
+ParseAction = Union[
+ Callable[[], Any],
+ Callable[[ParseResults], Any],
+ Callable[[int, ParseResults], Any],
+ Callable[[str, int, ParseResults], Any],
+]
+ParseCondition = Union[
+ Callable[[], bool],
+ Callable[[ParseResults], bool],
+ Callable[[int, ParseResults], bool],
+ Callable[[str, int, ParseResults], bool],
+]
+ParseFailAction = Callable[[str, int, "ParserElement", Exception], None]
+DebugStartAction = Callable[[str, int, "ParserElement", bool], None]
+DebugSuccessAction = Callable[
+ [str, int, int, "ParserElement", ParseResults, bool], None
+]
+DebugExceptionAction = Callable[[str, int, "ParserElement", Exception, bool], None]
+
+
+alphas = string.ascii_uppercase + string.ascii_lowercase
+identchars = pyparsing_unicode.Latin1.identchars
+identbodychars = pyparsing_unicode.Latin1.identbodychars
+nums = "0123456789"
+hexnums = nums + "ABCDEFabcdef"
+alphanums = alphas + nums
+printables = "".join([c for c in string.printable if c not in string.whitespace])
+
+_trim_arity_call_line: traceback.StackSummary = None
+
+
+def _trim_arity(func, max_limit=3):
+ """decorator to trim function calls to match the arity of the target"""
+ global _trim_arity_call_line
+
+ if func in _single_arg_builtins:
+ return lambda s, l, t: func(t)
+
+ limit = 0
+ found_arity = False
+
+ def extract_tb(tb, limit=0):
+ frames = traceback.extract_tb(tb, limit=limit)
+ frame_summary = frames[-1]
+ return [frame_summary[:2]]
+
+ # synthesize what would be returned by traceback.extract_stack at the call to
+ # user's parse action 'func', so that we don't incur call penalty at parse time
+
+ # fmt: off
+ LINE_DIFF = 7
+ # IF ANY CODE CHANGES, EVEN JUST COMMENTS OR BLANK LINES, BETWEEN THE NEXT LINE AND
+ # THE CALL TO FUNC INSIDE WRAPPER, LINE_DIFF MUST BE MODIFIED!!!!
+ _trim_arity_call_line = (_trim_arity_call_line or traceback.extract_stack(limit=2)[-1])
+ pa_call_line_synth = (_trim_arity_call_line[0], _trim_arity_call_line[1] + LINE_DIFF)
+
+ def wrapper(*args):
+ nonlocal found_arity, limit
+ while 1:
+ try:
+ ret = func(*args[limit:])
+ found_arity = True
+ return ret
+ except TypeError as te:
+ # re-raise TypeErrors if they did not come from our arity testing
+ if found_arity:
+ raise
+ else:
+ tb = te.__traceback__
+ trim_arity_type_error = (
+ extract_tb(tb, limit=2)[-1][:2] == pa_call_line_synth
+ )
+ del tb
+
+ if trim_arity_type_error:
+ if limit < max_limit:
+ limit += 1
+ continue
+
+ raise
+ # fmt: on
+
+ # copy func name to wrapper for sensible debug output
+ # (can't use functools.wraps, since that messes with function signature)
+ func_name = getattr(func, "__name__", getattr(func, "__class__").__name__)
+ wrapper.__name__ = func_name
+ wrapper.__doc__ = func.__doc__
+
+ return wrapper
+
+
+def condition_as_parse_action(
+ fn: ParseCondition, message: str = None, fatal: bool = False
+) -> ParseAction:
+ """
+ Function to convert a simple predicate function that returns ``True`` or ``False``
+ into a parse action. Can be used in places when a parse action is required
+ and :class:`ParserElement.add_condition` cannot be used (such as when adding a condition
+ to an operator level in :class:`infix_notation`).
+
+ Optional keyword arguments:
+
+ - ``message`` - define a custom message to be used in the raised exception
+ - ``fatal`` - if True, will raise :class:`ParseFatalException` to stop parsing immediately;
+ otherwise will raise :class:`ParseException`
+
+ """
+ msg = message if message is not None else "failed user-defined condition"
+ exc_type = ParseFatalException if fatal else ParseException
+ fn = _trim_arity(fn)
+
+ @wraps(fn)
+ def pa(s, l, t):
+ if not bool(fn(s, l, t)):
+ raise exc_type(s, l, msg)
+
+ return pa
+
+
+def _default_start_debug_action(
+ instring: str, loc: int, expr: "ParserElement", cache_hit: bool = False
+):
+ cache_hit_str = "*" if cache_hit else ""
+ print(
+ (
+ "{}Match {} at loc {}({},{})\n {}\n {}^".format(
+ cache_hit_str,
+ expr,
+ loc,
+ lineno(loc, instring),
+ col(loc, instring),
+ line(loc, instring),
+ " " * (col(loc, instring) - 1),
+ )
+ )
+ )
+
+
+def _default_success_debug_action(
+ instring: str,
+ startloc: int,
+ endloc: int,
+ expr: "ParserElement",
+ toks: ParseResults,
+ cache_hit: bool = False,
+):
+ cache_hit_str = "*" if cache_hit else ""
+ print("{}Matched {} -> {}".format(cache_hit_str, expr, toks.as_list()))
+
+
+def _default_exception_debug_action(
+ instring: str,
+ loc: int,
+ expr: "ParserElement",
+ exc: Exception,
+ cache_hit: bool = False,
+):
+ cache_hit_str = "*" if cache_hit else ""
+ print(
+ "{}Match {} failed, {} raised: {}".format(
+ cache_hit_str, expr, type(exc).__name__, exc
+ )
+ )
+
+
+def null_debug_action(*args):
+ """'Do-nothing' debug action, to suppress debugging output during parsing."""
+
+
+class ParserElement(ABC):
+ """Abstract base level parser element class."""
+
+ DEFAULT_WHITE_CHARS: str = " \n\t\r"
+ verbose_stacktrace: bool = False
+ _literalStringClass: OptionalType[type] = None
+
+ @staticmethod
+ def set_default_whitespace_chars(chars: str) -> None:
+ r"""
+ Overrides the default whitespace chars
+
+ Example::
+
+ # default whitespace chars are space, <TAB> and newline
+ OneOrMore(Word(alphas)).parse_string("abc def\nghi jkl") # -> ['abc', 'def', 'ghi', 'jkl']
+
+ # change to just treat newline as significant
+ ParserElement.set_default_whitespace_chars(" \t")
+ OneOrMore(Word(alphas)).parse_string("abc def\nghi jkl") # -> ['abc', 'def']
+ """
+ ParserElement.DEFAULT_WHITE_CHARS = chars
+
+ # update whitespace all parse expressions defined in this module
+ for expr in _builtin_exprs:
+ if expr.copyDefaultWhiteChars:
+ expr.whiteChars = set(chars)
+
+ @staticmethod
+ def inline_literals_using(cls: type) -> None:
+ """
+ Set class to be used for inclusion of string literals into a parser.
+
+ Example::
+
+ # default literal class used is Literal
+ integer = Word(nums)
+ date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
+
+ date_str.parse_string("1999/12/31") # -> ['1999', '/', '12', '/', '31']
+
+
+ # change to Suppress
+ ParserElement.inline_literals_using(Suppress)
+ date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
+
+ date_str.parse_string("1999/12/31") # -> ['1999', '12', '31']
+ """
+ ParserElement._literalStringClass = cls
+
+ class DebugActions(NamedTuple):
+ debug_try: OptionalType[DebugStartAction]
+ debug_match: OptionalType[DebugSuccessAction]
+ debug_fail: OptionalType[DebugExceptionAction]
+
+ def __init__(self, savelist: bool = False):
+ self.parseAction: List[ParseAction] = list()
+ self.failAction: OptionalType[ParseFailAction] = None
+ self.customName = None
+ self._defaultName = None
+ self.resultsName = None
+ self.saveAsList = savelist
+ self.skipWhitespace = True
+ self.whiteChars = set(ParserElement.DEFAULT_WHITE_CHARS)
+ self.copyDefaultWhiteChars = True
+ # used when checking for left-recursion
+ self.mayReturnEmpty = False
+ self.keepTabs = False
+ self.ignoreExprs: List["ParserElement"] = list()
+ self.debug = False
+ self.streamlined = False
+ # optimize exception handling for subclasses that don't advance parse index
+ self.mayIndexError = True
+ self.errmsg = ""
+ # mark results names as modal (report only last) or cumulative (list all)
+ self.modalResults = True
+ # custom debug actions
+ self.debugActions = self.DebugActions(None, None, None)
+ # avoid redundant calls to preParse
+ self.callPreparse = True
+ self.callDuringTry = False
+ self.suppress_warnings_: List[Diagnostics] = []
+
+ def suppress_warning(self, warning_type: Diagnostics) -> "ParserElement":
+ """
+ Suppress warnings emitted for a particular diagnostic on this expression.
+
+ Example::
+
+ base = pp.Forward()
+ base.suppress_warning(Diagnostics.warn_on_parse_using_empty_Forward)
+
+ # statement would normally raise a warning, but is now suppressed
+ print(base.parseString("x"))
+
+ """
+ self.suppress_warnings_.append(warning_type)
+ return self
+
+ def copy(self) -> "ParserElement":
+ """
+ Make a copy of this :class:`ParserElement`. Useful for defining
+ different parse actions for the same parsing pattern, using copies of
+ the original parse element.
+
+ Example::
+
+ integer = Word(nums).set_parse_action(lambda toks: int(toks[0]))
+ integerK = integer.copy().add_parse_action(lambda toks: toks[0] * 1024) + Suppress("K")
+ integerM = integer.copy().add_parse_action(lambda toks: toks[0] * 1024 * 1024) + Suppress("M")
+
+ print(OneOrMore(integerK | integerM | integer).parse_string("5K 100 640K 256M"))
+
+ prints::
+
+ [5120, 100, 655360, 268435456]
+
+ Equivalent form of ``expr.copy()`` is just ``expr()``::
+
+ integerM = integer().add_parse_action(lambda toks: toks[0] * 1024 * 1024) + Suppress("M")
+ """
+ cpy = copy.copy(self)
+ cpy.parseAction = self.parseAction[:]
+ cpy.ignoreExprs = self.ignoreExprs[:]
+ if self.copyDefaultWhiteChars:
+ cpy.whiteChars = set(ParserElement.DEFAULT_WHITE_CHARS)
+ return cpy
+
+ def set_results_name(
+ self, name: str, list_all_matches: bool = False, *, listAllMatches: bool = False
+ ) -> "ParserElement":
+ """
+ Define name for referencing matching tokens as a nested attribute
+ of the returned parse results.
+
+ Normally, results names are assigned as you would assign keys in a dict:
+ any existing value is overwritten by later values. If it is necessary to
+ keep all values captured for a particular results name, call ``set_results_name``
+ with ``list_all_matches`` = True.
+
+ NOTE: ``set_results_name`` returns a *copy* of the original :class:`ParserElement` object;
+ this is so that the client can define a basic element, such as an
+ integer, and reference it in multiple places with different names.
+
+ You can also set results names using the abbreviated syntax,
+ ``expr("name")`` in place of ``expr.set_results_name("name")``
+ - see :class:`__call__`. If ``list_all_matches`` is required, use
+ ``expr("name*")``.
+
+ Example::
+
+ date_str = (integer.set_results_name("year") + '/'
+ + integer.set_results_name("month") + '/'
+ + integer.set_results_name("day"))
+
+ # equivalent form:
+ date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
+ """
+ listAllMatches = listAllMatches or list_all_matches
+ return self._setResultsName(name, listAllMatches)
+
+ def _setResultsName(self, name, listAllMatches=False):
+ if name is None:
+ return self
+ newself = self.copy()
+ if name.endswith("*"):
+ name = name[:-1]
+ listAllMatches = True
+ newself.resultsName = name
+ newself.modalResults = not listAllMatches
+ return newself
+
+ def set_break(self, break_flag: bool = True) -> "ParserElement":
+ """
+ Method to invoke the Python pdb debugger when this element is
+ about to be parsed. Set ``break_flag`` to ``True`` to enable, ``False`` to
+ disable.
+ """
+ if break_flag:
+ _parseMethod = self._parse
+
+ def breaker(instring, loc, doActions=True, callPreParse=True):
+ import pdb
+
+ # this call to pdb.set_trace() is intentional, not a checkin error
+ pdb.set_trace()
+ return _parseMethod(instring, loc, doActions, callPreParse)
+
+ breaker._originalParseMethod = _parseMethod
+ self._parse = breaker
+ else:
+ if hasattr(self._parse, "_originalParseMethod"):
+ self._parse = self._parse._originalParseMethod
+ return self
+
+ def set_parse_action(self, *fns: ParseAction, **kwargs) -> "ParserElement":
+ """
+ Define one or more actions to perform when successfully matching parse element definition.
+
+ Parse actions can be called to perform data conversions, do extra validation,
+ update external data structures, or enhance or replace the parsed tokens.
+ Each parse action ``fn`` is a callable method with 0-3 arguments, called as
+ ``fn(s, loc, toks)`` , ``fn(loc, toks)`` , ``fn(toks)`` , or just ``fn()`` , where:
+
+ - s = the original string being parsed (see note below)
+ - loc = the location of the matching substring
+ - toks = a list of the matched tokens, packaged as a :class:`ParseResults` object
+
+ The parsed tokens are passed to the parse action as ParseResults. They can be
+ modified in place using list-style append, extend, and pop operations to update
+ the parsed list elements; and with dictionary-style item set and del operations
+ to add, update, or remove any named results. If the tokens are modified in place,
+ it is not necessary to return them with a return statement.
+
+ Parse actions can also completely replace the given tokens, with another ``ParseResults``
+ object, or with some entirely different object (common for parse actions that perform data
+ conversions). A convenient way to build a new parse result is to define the values
+ using a dict, and then create the return value using :class:`ParseResults.from_dict`.
+
+ If None is passed as the ``fn`` parse action, all previously added parse actions for this
+ expression are cleared.
+
+ Optional keyword arguments:
+
+ - call_during_try = (default= ``False``) indicate if parse action should be run during
+ lookaheads and alternate testing. For parse actions that have side effects, it is
+ important to only call the parse action once it is determined that it is being
+ called as part of a successful parse. For parse actions that perform additional
+ validation, then call_during_try should be passed as True, so that the validation
+ code is included in the preliminary "try" parses.
+
+ Note: the default parsing behavior is to expand tabs in the input string
+ before starting the parsing process. See :class:`parse_string` for more
+ information on parsing strings containing ``<TAB>`` s, and suggested
+ methods to maintain a consistent view of the parsed string, the parse
+ location, and line and column positions within the parsed string.
+
+ Example::
+
+ # parse dates in the form YYYY/MM/DD
+
+ # use parse action to convert toks from str to int at parse time
+ def convert_to_int(toks):
+ return int(toks[0])
+
+ # use a parse action to verify that the date is a valid date
+ def is_valid_date(instring, loc, toks):
+ from datetime import date
+ year, month, day = toks[::2]
+ try:
+ date(year, month, day)
+ except ValueError:
+ raise ParseException(instring, loc, "invalid date given")
+
+ integer = Word(nums)
+ date_str = integer + '/' + integer + '/' + integer
+
+ # add parse actions
+ integer.set_parse_action(convert_to_int)
+ date_str.set_parse_action(is_valid_date)
+
+ # note that integer fields are now ints, not strings
+ date_str.run_tests('''
+ # successful parse - note that integer fields were converted to ints
+ 1999/12/31
+
+ # fail - invalid date
+ 1999/13/31
+ ''')
+ """
+ if list(fns) == [None]:
+ self.parseAction = []
+ else:
+ if not all(callable(fn) for fn in fns):
+ raise TypeError("parse actions must be callable")
+ self.parseAction = [_trim_arity(fn) for fn in fns]
+ self.callDuringTry = kwargs.get(
+ "call_during_try", kwargs.get("callDuringTry", False)
+ )
+ return self
+
+ def add_parse_action(self, *fns: ParseAction, **kwargs) -> "ParserElement":
+ """
+ Add one or more parse actions to expression's list of parse actions. See :class:`set_parse_action`.
+
+ See examples in :class:`copy`.
+ """
+ self.parseAction += [_trim_arity(fn) for fn in fns]
+ self.callDuringTry = self.callDuringTry or kwargs.get(
+ "call_during_try", kwargs.get("callDuringTry", False)
+ )
+ return self
+
+ def add_condition(self, *fns: ParseCondition, **kwargs) -> "ParserElement":
+ """Add a boolean predicate function to expression's list of parse actions. See
+ :class:`set_parse_action` for function call signatures. Unlike ``set_parse_action``,
+ functions passed to ``add_condition`` need to return boolean success/fail of the condition.
+
+ Optional keyword arguments:
+
+ - message = define a custom message to be used in the raised exception
+ - fatal = if True, will raise ParseFatalException to stop parsing immediately; otherwise will raise
+ ParseException
+ - call_during_try = boolean to indicate if this method should be called during internal tryParse calls,
+ default=False
+
+ Example::
+
+ integer = Word(nums).set_parse_action(lambda toks: int(toks[0]))
+ year_int = integer.copy()
+ year_int.add_condition(lambda toks: toks[0] >= 2000, message="Only support years 2000 and later")
+ date_str = year_int + '/' + integer + '/' + integer
+
+ result = date_str.parse_string("1999/12/31") # -> Exception: Only support years 2000 and later (at char 0),
+ (line:1, col:1)
+ """
+ for fn in fns:
+ self.parseAction.append(
+ condition_as_parse_action(
+ fn, message=kwargs.get("message"), fatal=kwargs.get("fatal", False)
+ )
+ )
+
+ self.callDuringTry = self.callDuringTry or kwargs.get(
+ "call_during_try", kwargs.get("callDuringTry", False)
+ )
+ return self
+
+ def set_fail_action(self, fn: ParseFailAction) -> "ParserElement":
+ """
+ Define action to perform if parsing fails at this expression.
+ Fail acton fn is a callable function that takes the arguments
+ ``fn(s, loc, expr, err)`` where:
+
+ - s = string being parsed
+ - loc = location where expression match was attempted and failed
+ - expr = the parse expression that failed
+ - err = the exception thrown
+
+ The function returns no value. It may throw :class:`ParseFatalException`
+ if it is desired to stop parsing immediately."""
+ self.failAction = fn
+ return self
+
+ def _skipIgnorables(self, instring, loc):
+ exprsFound = True
+ while exprsFound:
+ exprsFound = False
+ for e in self.ignoreExprs:
+ try:
+ while 1:
+ loc, dummy = e._parse(instring, loc)
+ exprsFound = True
+ except ParseException:
+ pass
+ return loc
+
+ def preParse(self, instring, loc):
+ if self.ignoreExprs:
+ loc = self._skipIgnorables(instring, loc)
+
+ if self.skipWhitespace:
+ instrlen = len(instring)
+ white_chars = self.whiteChars
+ while loc < instrlen and instring[loc] in white_chars:
+ loc += 1
+
+ return loc
+
+ def parseImpl(self, instring, loc, doActions=True):
+ return loc, []
+
+ def postParse(self, instring, loc, tokenlist):
+ return tokenlist
+
+ # @profile
+ def _parseNoCache(
+ self, instring, loc, doActions=True, callPreParse=True
+ ) -> Tuple[int, ParseResults]:
+ TRY, MATCH, FAIL = 0, 1, 2
+ debugging = self.debug # and doActions)
+ len_instring = len(instring)
+
+ if debugging or self.failAction:
+ # print("Match {} at loc {}({}, {})".format(self, loc, lineno(loc, instring), col(loc, instring)))
+ try:
+ if callPreParse and self.callPreparse:
+ pre_loc = self.preParse(instring, loc)
+ else:
+ pre_loc = loc
+ tokens_start = pre_loc
+ if self.debugActions.debug_try:
+ self.debugActions.debug_try(instring, tokens_start, self, False)
+ if self.mayIndexError or pre_loc >= len_instring:
+ try:
+ loc, tokens = self.parseImpl(instring, pre_loc, doActions)
+ except IndexError:
+ raise ParseException(instring, len_instring, self.errmsg, self)
+ else:
+ loc, tokens = self.parseImpl(instring, pre_loc, doActions)
+ except Exception as err:
+ # print("Exception raised:", err)
+ if self.debugActions.debug_fail:
+ self.debugActions.debug_fail(
+ instring, tokens_start, self, err, False
+ )
+ if self.failAction:
+ self.failAction(instring, tokens_start, self, err)
+ raise
+ else:
+ if callPreParse and self.callPreparse:
+ pre_loc = self.preParse(instring, loc)
+ else:
+ pre_loc = loc
+ tokens_start = pre_loc
+ if self.mayIndexError or pre_loc >= len_instring:
+ try:
+ loc, tokens = self.parseImpl(instring, pre_loc, doActions)
+ except IndexError:
+ raise ParseException(instring, len_instring, self.errmsg, self)
+ else:
+ loc, tokens = self.parseImpl(instring, pre_loc, doActions)
+
+ tokens = self.postParse(instring, loc, tokens)
+
+ ret_tokens = ParseResults(
+ tokens, self.resultsName, asList=self.saveAsList, modal=self.modalResults
+ )
+ if self.parseAction and (doActions or self.callDuringTry):
+ if debugging:
+ try:
+ for fn in self.parseAction:
+ try:
+ tokens = fn(instring, tokens_start, ret_tokens)
+ except IndexError as parse_action_exc:
+ exc = ParseException("exception raised in parse action")
+ raise exc from parse_action_exc
+
+ if tokens is not None and tokens is not ret_tokens:
+ ret_tokens = ParseResults(
+ tokens,
+ self.resultsName,
+ asList=self.saveAsList
+ and isinstance(tokens, (ParseResults, list)),
+ modal=self.modalResults,
+ )
+ except Exception as err:
+ # print "Exception raised in user parse action:", err
+ if self.debugActions.debug_fail:
+ self.debugActions.debug_fail(
+ instring, tokens_start, self, err, False
+ )
+ raise
+ else:
+ for fn in self.parseAction:
+ try:
+ tokens = fn(instring, tokens_start, ret_tokens)
+ except IndexError as parse_action_exc:
+ exc = ParseException("exception raised in parse action")
+ raise exc from parse_action_exc
+
+ if tokens is not None and tokens is not ret_tokens:
+ ret_tokens = ParseResults(
+ tokens,
+ self.resultsName,
+ asList=self.saveAsList
+ and isinstance(tokens, (ParseResults, list)),
+ modal=self.modalResults,
+ )
+ if debugging:
+ # print("Matched", self, "->", ret_tokens.as_list())
+ if self.debugActions.debug_match:
+ self.debugActions.debug_match(
+ instring, tokens_start, loc, self, ret_tokens, False
+ )
+
+ return loc, ret_tokens
+
+ def try_parse(self, instring: str, loc: int, raise_fatal: bool = False) -> int:
+ try:
+ return self._parse(instring, loc, doActions=False)[0]
+ except ParseFatalException:
+ if raise_fatal:
+ raise
+ raise ParseException(instring, loc, self.errmsg, self)
+
+ def can_parse_next(self, instring: str, loc: int) -> bool:
+ try:
+ self.try_parse(instring, loc)
+ except (ParseException, IndexError):
+ return False
+ else:
+ return True
+
+ # cache for left-recursion in Forward references
+ recursion_lock = RLock()
+ recursion_memos: DictType[
+ Tuple[int, "Forward", bool], Tuple[int, Union[ParseResults, Exception]]
+ ] = {}
+
+ # argument cache for optimizing repeated calls when backtracking through recursive expressions
+ packrat_cache = (
+ {}
+ ) # this is set later by enabled_packrat(); this is here so that reset_cache() doesn't fail
+ packrat_cache_lock = RLock()
+ packrat_cache_stats = [0, 0]
+
+ # this method gets repeatedly called during backtracking with the same arguments -
+ # we can cache these arguments and save ourselves the trouble of re-parsing the contained expression
+ def _parseCache(
+ self, instring, loc, doActions=True, callPreParse=True
+ ) -> Tuple[int, ParseResults]:
+ HIT, MISS = 0, 1
+ TRY, MATCH, FAIL = 0, 1, 2
+ lookup = (self, instring, loc, callPreParse, doActions)
+ with ParserElement.packrat_cache_lock:
+ cache = ParserElement.packrat_cache
+ value = cache.get(lookup)
+ if value is cache.not_in_cache:
+ ParserElement.packrat_cache_stats[MISS] += 1
+ try:
+ value = self._parseNoCache(instring, loc, doActions, callPreParse)
+ except ParseBaseException as pe:
+ # cache a copy of the exception, without the traceback
+ cache.set(lookup, pe.__class__(*pe.args))
+ raise
+ else:
+ cache.set(lookup, (value[0], value[1].copy(), loc))
+ return value
+ else:
+ ParserElement.packrat_cache_stats[HIT] += 1
+ if self.debug and self.debugActions.debug_try:
+ try:
+ self.debugActions.debug_try(instring, loc, self, cache_hit=True)
+ except TypeError:
+ pass
+ if isinstance(value, Exception):
+ if self.debug and self.debugActions.debug_fail:
+ try:
+ self.debugActions.debug_fail(
+ instring, loc, self, value, cache_hit=True
+ )
+ except TypeError:
+ pass
+ raise value
+
+ loc_, result, endloc = value[0], value[1].copy(), value[2]
+ if self.debug and self.debugActions.debug_match:
+ try:
+ self.debugActions.debug_match(
+ instring, loc_, endloc, self, result, cache_hit=True
+ )
+ except TypeError:
+ pass
+
+ return loc_, result
+
+ _parse = _parseNoCache
+
+ @staticmethod
+ def reset_cache() -> None:
+ ParserElement.packrat_cache.clear()
+ ParserElement.packrat_cache_stats[:] = [0] * len(
+ ParserElement.packrat_cache_stats
+ )
+ ParserElement.recursion_memos.clear()
+
+ _packratEnabled = False
+ _left_recursion_enabled = False
+
+ @staticmethod
+ def disable_memoization() -> None:
+ """
+ Disables active Packrat or Left Recursion parsing and their memoization
+
+ This method also works if neither Packrat nor Left Recursion are enabled.
+ This makes it safe to call before activating Packrat nor Left Recursion
+ to clear any previous settings.
+ """
+ ParserElement.reset_cache()
+ ParserElement._left_recursion_enabled = False
+ ParserElement._packratEnabled = False
+ ParserElement._parse = ParserElement._parseNoCache
+
+ @staticmethod
+ def enable_left_recursion(
+ cache_size_limit: OptionalType[int] = None, *, force=False
+ ) -> None:
+ """
+ Enables "bounded recursion" parsing, which allows for both direct and indirect
+ left-recursion. During parsing, left-recursive :class:`Forward` elements are
+ repeatedly matched with a fixed recursion depth that is gradually increased
+ until finding the longest match.
+
+ Example::
+
+ import pyparsing as pp
+ pp.ParserElement.enable_left_recursion()
+
+ E = pp.Forward("E")
+ num = pp.Word(pp.nums)
+ # match `num`, or `num '+' num`, or `num '+' num '+' num`, ...
+ E <<= E + '+' - num | num
+
+ print(E.parse_string("1+2+3"))
+
+ Recursion search naturally memoizes matches of ``Forward`` elements and may
+ thus skip reevaluation of parse actions during backtracking. This may break
+ programs with parse actions which rely on strict ordering of side-effects.
+
+ Parameters:
+
+ - cache_size_limit - (default=``None``) - memoize at most this many
+ ``Forward`` elements during matching; if ``None`` (the default),
+ memoize all ``Forward`` elements.
+
+ Bounded Recursion parsing works similar but not identical to Packrat parsing,
+ thus the two cannot be used together. Use ``force=True`` to disable any
+ previous, conflicting settings.
+ """
+ if force:
+ ParserElement.disable_memoization()
+ elif ParserElement._packratEnabled:
+ raise RuntimeError("Packrat and Bounded Recursion are not compatible")
+ if cache_size_limit is None:
+ ParserElement.recursion_memos = _UnboundedMemo()
+ elif cache_size_limit > 0:
+ ParserElement.recursion_memos = _LRUMemo(capacity=cache_size_limit)
+ else:
+ raise NotImplementedError("Memo size of %s" % cache_size_limit)
+ ParserElement._left_recursion_enabled = True
+
+ @staticmethod
+ def enable_packrat(cache_size_limit: int = 128, *, force: bool = False) -> None:
+ """
+ Enables "packrat" parsing, which adds memoizing to the parsing logic.
+ Repeated parse attempts at the same string location (which happens
+ often in many complex grammars) can immediately return a cached value,
+ instead of re-executing parsing/validating code. Memoizing is done of
+ both valid results and parsing exceptions.
+
+ Parameters:
+
+ - cache_size_limit - (default= ``128``) - if an integer value is provided
+ will limit the size of the packrat cache; if None is passed, then
+ the cache size will be unbounded; if 0 is passed, the cache will
+ be effectively disabled.
+
+ This speedup may break existing programs that use parse actions that
+ have side-effects. For this reason, packrat parsing is disabled when
+ you first import pyparsing. To activate the packrat feature, your
+ program must call the class method :class:`ParserElement.enable_packrat`.
+ For best results, call ``enable_packrat()`` immediately after
+ importing pyparsing.
+
+ Example::
+
+ import pyparsing
+ pyparsing.ParserElement.enable_packrat()
+
+ Packrat parsing works similar but not identical to Bounded Recursion parsing,
+ thus the two cannot be used together. Use ``force=True`` to disable any
+ previous, conflicting settings.
+ """
+ if force:
+ ParserElement.disable_memoization()
+ elif ParserElement._left_recursion_enabled:
+ raise RuntimeError("Packrat and Bounded Recursion are not compatible")
+ if not ParserElement._packratEnabled:
+ ParserElement._packratEnabled = True
+ if cache_size_limit is None:
+ ParserElement.packrat_cache = _UnboundedCache()
+ else:
+ ParserElement.packrat_cache = _FifoCache(cache_size_limit)
+ ParserElement._parse = ParserElement._parseCache
+
+ def parse_string(
+ self, instring: str, parse_all: bool = False, *, parseAll: bool = False
+ ) -> ParseResults:
+ """
+ Parse a string with respect to the parser definition. This function is intended as the primary interface to the
+ client code.
+
+ :param instring: The input string to be parsed.
+ :param parse_all: If set, the entire input string must match the grammar.
+ :param parseAll: retained for pre-PEP8 compatibility, will be removed in a future release.
+ :raises ParseException: Raised if ``parse_all`` is set and the input string does not match the whole grammar.
+ :returns: the parsed data as a :class:`ParseResults` object, which may be accessed as a `list`, a `dict`, or
+ an object with attributes if the given parser includes results names.
+
+ If the input string is required to match the entire grammar, ``parse_all`` flag must be set to ``True``. This
+ is also equivalent to ending the grammar with :class:`StringEnd`().
+
+ To report proper column numbers, ``parse_string`` operates on a copy of the input string where all tabs are
+ converted to spaces (8 spaces per tab, as per the default in ``string.expandtabs``). If the input string
+ contains tabs and the grammar uses parse actions that use the ``loc`` argument to index into the string
+ being parsed, one can ensure a consistent view of the input string by doing one of the following:
+
+ - calling ``parse_with_tabs`` on your grammar before calling ``parse_string`` (see :class:`parse_with_tabs`),
+ - define your parse action using the full ``(s,loc,toks)`` signature, and reference the input string using the
+ parse action's ``s`` argument, or
+ - explicitly expand the tabs in your input string before calling ``parse_string``.
+
+ Examples:
+
+ By default, partial matches are OK.
+
+ >>> res = Word('a').parse_string('aaaaabaaa')
+ >>> print(res)
+ ['aaaaa']
+
+ The parsing behavior varies by the inheriting class of this abstract class. Please refer to the children
+ directly to see more examples.
+
+ It raises an exception if parse_all flag is set and instring does not match the whole grammar.
+
+ >>> res = Word('a').parse_string('aaaaabaaa', parse_all=True)
+ Traceback (most recent call last):
+ ...
+ pyparsing.ParseException: Expected end of text, found 'b' (at char 5), (line:1, col:6)
+ """
+ parseAll = parse_all or parseAll
+
+ ParserElement.reset_cache()
+ if not self.streamlined:
+ self.streamline()
+ for e in self.ignoreExprs:
+ e.streamline()
+ if not self.keepTabs:
+ instring = instring.expandtabs()
+ try:
+ loc, tokens = self._parse(instring, 0)
+ if parseAll:
+ loc = self.preParse(instring, loc)
+ se = Empty() + StringEnd()
+ se._parse(instring, loc)
+ except ParseBaseException as exc:
+ if ParserElement.verbose_stacktrace:
+ raise
+ else:
+ # catch and re-raise exception from here, clearing out pyparsing internal stack trace
+ raise exc.with_traceback(None)
+ else:
+ return tokens
+
+ def scan_string(
+ self,
+ instring: str,
+ max_matches: int = _MAX_INT,
+ overlap: bool = False,
+ *,
+ debug: bool = False,
+ maxMatches: int = _MAX_INT,
+ ) -> Generator[Tuple[ParseResults, int, int], None, None]:
+ """
+ Scan the input string for expression matches. Each match will return the
+ matching tokens, start location, and end location. May be called with optional
+ ``max_matches`` argument, to clip scanning after 'n' matches are found. If
+ ``overlap`` is specified, then overlapping matches will be reported.
+
+ Note that the start and end locations are reported relative to the string
+ being parsed. See :class:`parse_string` for more information on parsing
+ strings with embedded tabs.
+
+ Example::
+
+ source = "sldjf123lsdjjkf345sldkjf879lkjsfd987"
+ print(source)
+ for tokens, start, end in Word(alphas).scan_string(source):
+ print(' '*start + '^'*(end-start))
+ print(' '*start + tokens[0])
+
+ prints::
+
+ sldjf123lsdjjkf345sldkjf879lkjsfd987
+ ^^^^^
+ sldjf
+ ^^^^^^^
+ lsdjjkf
+ ^^^^^^
+ sldkjf
+ ^^^^^^
+ lkjsfd
+ """
+ maxMatches = min(maxMatches, max_matches)
+ if not self.streamlined:
+ self.streamline()
+ for e in self.ignoreExprs:
+ e.streamline()
+
+ if not self.keepTabs:
+ instring = str(instring).expandtabs()
+ instrlen = len(instring)
+ loc = 0
+ preparseFn = self.preParse
+ parseFn = self._parse
+ ParserElement.resetCache()
+ matches = 0
+ try:
+ while loc <= instrlen and matches < maxMatches:
+ try:
+ preloc = preparseFn(instring, loc)
+ nextLoc, tokens = parseFn(instring, preloc, callPreParse=False)
+ except ParseException:
+ loc = preloc + 1
+ else:
+ if nextLoc > loc:
+ matches += 1
+ if debug:
+ print(
+ {
+ "tokens": tokens.asList(),
+ "start": preloc,
+ "end": nextLoc,
+ }
+ )
+ yield tokens, preloc, nextLoc
+ if overlap:
+ nextloc = preparseFn(instring, loc)
+ if nextloc > loc:
+ loc = nextLoc
+ else:
+ loc += 1
+ else:
+ loc = nextLoc
+ else:
+ loc = preloc + 1
+ except ParseBaseException as exc:
+ if ParserElement.verbose_stacktrace:
+ raise
+ else:
+ # catch and re-raise exception from here, clears out pyparsing internal stack trace
+ raise exc.with_traceback(None)
+
+ def transform_string(self, instring: str, *, debug: bool = False) -> str:
+ """
+ Extension to :class:`scan_string`, to modify matching text with modified tokens that may
+ be returned from a parse action. To use ``transform_string``, define a grammar and
+ attach a parse action to it that modifies the returned token list.
+ Invoking ``transform_string()`` on a target string will then scan for matches,
+ and replace the matched text patterns according to the logic in the parse
+ action. ``transform_string()`` returns the resulting transformed string.
+
+ Example::
+
+ wd = Word(alphas)
+ wd.set_parse_action(lambda toks: toks[0].title())
+
+ print(wd.transform_string("now is the winter of our discontent made glorious summer by this sun of york."))
+
+ prints::
+
+ Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York.
+ """
+ out: List[str] = []
+ lastE = 0
+ # force preservation of <TAB>s, to minimize unwanted transformation of string, and to
+ # keep string locs straight between transform_string and scan_string
+ self.keepTabs = True
+ try:
+ for t, s, e in self.scan_string(instring, debug=debug):
+ out.append(instring[lastE:s])
+ if t:
+ if isinstance(t, ParseResults):
+ out += t.as_list()
+ elif isinstance(t, Iterable) and not isinstance(t, str_type):
+ out.extend(t)
+ else:
+ out.append(t)
+ lastE = e
+ out.append(instring[lastE:])
+ out = [o for o in out if o]
+ return "".join([str(s) for s in _flatten(out)])
+ except ParseBaseException as exc:
+ if ParserElement.verbose_stacktrace:
+ raise
+ else:
+ # catch and re-raise exception from here, clears out pyparsing internal stack trace
+ raise exc.with_traceback(None)
+
+ def search_string(
+ self,
+ instring: str,
+ max_matches: int = _MAX_INT,
+ *,
+ debug: bool = False,
+ maxMatches: int = _MAX_INT,
+ ) -> ParseResults:
+ """
+ Another extension to :class:`scan_string`, simplifying the access to the tokens found
+ to match the given parse expression. May be called with optional
+ ``max_matches`` argument, to clip searching after 'n' matches are found.
+
+ Example::
+
+ # a capitalized word starts with an uppercase letter, followed by zero or more lowercase letters
+ cap_word = Word(alphas.upper(), alphas.lower())
+
+ print(cap_word.search_string("More than Iron, more than Lead, more than Gold I need Electricity"))
+
+ # the sum() builtin can be used to merge results into a single ParseResults object
+ print(sum(cap_word.search_string("More than Iron, more than Lead, more than Gold I need Electricity")))
+
+ prints::
+
+ [['More'], ['Iron'], ['Lead'], ['Gold'], ['I'], ['Electricity']]
+ ['More', 'Iron', 'Lead', 'Gold', 'I', 'Electricity']
+ """
+ maxMatches = min(maxMatches, max_matches)
+ try:
+ return ParseResults(
+ [t for t, s, e in self.scan_string(instring, maxMatches, debug=debug)]
+ )
+ except ParseBaseException as exc:
+ if ParserElement.verbose_stacktrace:
+ raise
+ else:
+ # catch and re-raise exception from here, clears out pyparsing internal stack trace
+ raise exc.with_traceback(None)
+
+ def split(
+ self,
+ instring: str,
+ maxsplit: int = _MAX_INT,
+ include_separators: bool = False,
+ *,
+ includeSeparators=False,
+ ) -> Generator[str, None, None]:
+ """
+ Generator method to split a string using the given expression as a separator.
+ May be called with optional ``maxsplit`` argument, to limit the number of splits;
+ and the optional ``include_separators`` argument (default= ``False``), if the separating
+ matching text should be included in the split results.
+
+ Example::
+
+ punc = one_of(list(".,;:/-!?"))
+ print(list(punc.split("This, this?, this sentence, is badly punctuated!")))
+
+ prints::
+
+ ['This', ' this', '', ' this sentence', ' is badly punctuated', '']
+ """
+ includeSeparators = includeSeparators or include_separators
+ last = 0
+ for t, s, e in self.scan_string(instring, max_matches=maxsplit):
+ yield instring[last:s]
+ if includeSeparators:
+ yield t[0]
+ last = e
+ yield instring[last:]
+
+ def __add__(self, other) -> "ParserElement":
+ """
+ Implementation of ``+`` operator - returns :class:`And`. Adding strings to a :class:`ParserElement`
+ converts them to :class:`Literal`s by default.
+
+ Example::
+
+ greet = Word(alphas) + "," + Word(alphas) + "!"
+ hello = "Hello, World!"
+ print(hello, "->", greet.parse_string(hello))
+
+ prints::
+
+ Hello, World! -> ['Hello', ',', 'World', '!']
+
+ ``...`` may be used as a parse expression as a short form of :class:`SkipTo`.
+
+ Literal('start') + ... + Literal('end')
+
+ is equivalent to:
+
+ Literal('start') + SkipTo('end')("_skipped*") + Literal('end')
+
+ Note that the skipped text is returned with '_skipped' as a results name,
+ and to support having multiple skips in the same parser, the value returned is
+ a list of all skipped text.
+ """
+ if other is Ellipsis:
+ return _PendingSkip(self)
+
+ if isinstance(other, str_type):
+ other = self._literalStringClass(other)
+ if not isinstance(other, ParserElement):
+ raise TypeError(
+ "Cannot combine element of type {} with ParserElement".format(
+ type(other).__name__
+ )
+ )
+ return And([self, other])
+
+ def __radd__(self, other) -> "ParserElement":
+ """
+ Implementation of ``+`` operator when left operand is not a :class:`ParserElement`
+ """
+ if other is Ellipsis:
+ return SkipTo(self)("_skipped*") + self
+
+ if isinstance(other, str_type):
+ other = self._literalStringClass(other)
+ if not isinstance(other, ParserElement):
+ raise TypeError(
+ "Cannot combine element of type {} with ParserElement".format(
+ type(other).__name__
+ )
+ )
+ return other + self
+
+ def __sub__(self, other) -> "ParserElement":
+ """
+ Implementation of ``-`` operator, returns :class:`And` with error stop
+ """
+ if isinstance(other, str_type):
+ other = self._literalStringClass(other)
+ if not isinstance(other, ParserElement):
+ raise TypeError(
+ "Cannot combine element of type {} with ParserElement".format(
+ type(other).__name__
+ )
+ )
+ return self + And._ErrorStop() + other
+
+ def __rsub__(self, other) -> "ParserElement":
+ """
+ Implementation of ``-`` operator when left operand is not a :class:`ParserElement`
+ """
+ if isinstance(other, str_type):
+ other = self._literalStringClass(other)
+ if not isinstance(other, ParserElement):
+ raise TypeError(
+ "Cannot combine element of type {} with ParserElement".format(
+ type(other).__name__
+ )
+ )
+ return other - self
+
+ def __mul__(self, other) -> "ParserElement":
+ """
+ Implementation of ``*`` operator, allows use of ``expr * 3`` in place of
+ ``expr + expr + expr``. Expressions may also be multiplied by a 2-integer
+ tuple, similar to ``{min, max}`` multipliers in regular expressions. Tuples
+ may also include ``None`` as in:
+ - ``expr*(n, None)`` or ``expr*(n, )`` is equivalent
+ to ``expr*n + ZeroOrMore(expr)``
+ (read as "at least n instances of ``expr``")
+ - ``expr*(None, n)`` is equivalent to ``expr*(0, n)``
+ (read as "0 to n instances of ``expr``")
+ - ``expr*(None, None)`` is equivalent to ``ZeroOrMore(expr)``
+ - ``expr*(1, None)`` is equivalent to ``OneOrMore(expr)``
+
+ Note that ``expr*(None, n)`` does not raise an exception if
+ more than n exprs exist in the input stream; that is,
+ ``expr*(None, n)`` does not enforce a maximum number of expr
+ occurrences. If this behavior is desired, then write
+ ``expr*(None, n) + ~expr``
+ """
+ if other is Ellipsis:
+ other = (0, None)
+ elif isinstance(other, tuple) and other[:1] == (Ellipsis,):
+ other = ((0,) + other[1:] + (None,))[:2]
+
+ if isinstance(other, int):
+ minElements, optElements = other, 0
+ elif isinstance(other, tuple):
+ other = tuple(o if o is not Ellipsis else None for o in other)
+ other = (other + (None, None))[:2]
+ if other[0] is None:
+ other = (0, other[1])
+ if isinstance(other[0], int) and other[1] is None:
+ if other[0] == 0:
+ return ZeroOrMore(self)
+ if other[0] == 1:
+ return OneOrMore(self)
+ else:
+ return self * other[0] + ZeroOrMore(self)
+ elif isinstance(other[0], int) and isinstance(other[1], int):
+ minElements, optElements = other
+ optElements -= minElements
+ else:
+ raise TypeError(
+ "cannot multiply ParserElement and ({}) objects".format(
+ ",".join(type(item).__name__ for item in other)
+ )
+ )
+ else:
+ raise TypeError(
+ "cannot multiply ParserElement and {} objects".format(
+ type(other).__name__
+ )
+ )
+
+ if minElements < 0:
+ raise ValueError("cannot multiply ParserElement by negative value")
+ if optElements < 0:
+ raise ValueError(
+ "second tuple value must be greater or equal to first tuple value"
+ )
+ if minElements == optElements == 0:
+ return And([])
+
+ if optElements:
+
+ def makeOptionalList(n):
+ if n > 1:
+ return Opt(self + makeOptionalList(n - 1))
+ else:
+ return Opt(self)
+
+ if minElements:
+ if minElements == 1:
+ ret = self + makeOptionalList(optElements)
+ else:
+ ret = And([self] * minElements) + makeOptionalList(optElements)
+ else:
+ ret = makeOptionalList(optElements)
+ else:
+ if minElements == 1:
+ ret = self
+ else:
+ ret = And([self] * minElements)
+ return ret
+
+ def __rmul__(self, other) -> "ParserElement":
+ return self.__mul__(other)
+
+ def __or__(self, other) -> "ParserElement":
+ """
+ Implementation of ``|`` operator - returns :class:`MatchFirst`
+ """
+ if other is Ellipsis:
+ return _PendingSkip(self, must_skip=True)
+
+ if isinstance(other, str_type):
+ other = self._literalStringClass(other)
+ if not isinstance(other, ParserElement):
+ raise TypeError(
+ "Cannot combine element of type {} with ParserElement".format(
+ type(other).__name__
+ )
+ )
+ return MatchFirst([self, other])
+
+ def __ror__(self, other) -> "ParserElement":
+ """
+ Implementation of ``|`` operator when left operand is not a :class:`ParserElement`
+ """
+ if isinstance(other, str_type):
+ other = self._literalStringClass(other)
+ if not isinstance(other, ParserElement):
+ raise TypeError(
+ "Cannot combine element of type {} with ParserElement".format(
+ type(other).__name__
+ )
+ )
+ return other | self
+
+ def __xor__(self, other) -> "ParserElement":
+ """
+ Implementation of ``^`` operator - returns :class:`Or`
+ """
+ if isinstance(other, str_type):
+ other = self._literalStringClass(other)
+ if not isinstance(other, ParserElement):
+ raise TypeError(
+ "Cannot combine element of type {} with ParserElement".format(
+ type(other).__name__
+ )
+ )
+ return Or([self, other])
+
+ def __rxor__(self, other) -> "ParserElement":
+ """
+ Implementation of ``^`` operator when left operand is not a :class:`ParserElement`
+ """
+ if isinstance(other, str_type):
+ other = self._literalStringClass(other)
+ if not isinstance(other, ParserElement):
+ raise TypeError(
+ "Cannot combine element of type {} with ParserElement".format(
+ type(other).__name__
+ )
+ )
+ return other ^ self
+
+ def __and__(self, other) -> "ParserElement":
+ """
+ Implementation of ``&`` operator - returns :class:`Each`
+ """
+ if isinstance(other, str_type):
+ other = self._literalStringClass(other)
+ if not isinstance(other, ParserElement):
+ raise TypeError(
+ "Cannot combine element of type {} with ParserElement".format(
+ type(other).__name__
+ )
+ )
+ return Each([self, other])
+
+ def __rand__(self, other) -> "ParserElement":
+ """
+ Implementation of ``&`` operator when left operand is not a :class:`ParserElement`
+ """
+ if isinstance(other, str_type):
+ other = self._literalStringClass(other)
+ if not isinstance(other, ParserElement):
+ raise TypeError(
+ "Cannot combine element of type {} with ParserElement".format(
+ type(other).__name__
+ )
+ )
+ return other & self
+
+ def __invert__(self) -> "ParserElement":
+ """
+ Implementation of ``~`` operator - returns :class:`NotAny`
+ """
+ return NotAny(self)
+
+ # disable __iter__ to override legacy use of sequential access to __getitem__ to
+ # iterate over a sequence
+ __iter__ = None
+
+ def __getitem__(self, key):
+ """
+ use ``[]`` indexing notation as a short form for expression repetition:
+
+ - ``expr[n]`` is equivalent to ``expr*n``
+ - ``expr[m, n]`` is equivalent to ``expr*(m, n)``
+ - ``expr[n, ...]`` or ``expr[n,]`` is equivalent
+ to ``expr*n + ZeroOrMore(expr)``
+ (read as "at least n instances of ``expr``")
+ - ``expr[..., n]`` is equivalent to ``expr*(0, n)``
+ (read as "0 to n instances of ``expr``")
+ - ``expr[...]`` and ``expr[0, ...]`` are equivalent to ``ZeroOrMore(expr)``
+ - ``expr[1, ...]`` is equivalent to ``OneOrMore(expr)``
+
+ ``None`` may be used in place of ``...``.
+
+ Note that ``expr[..., n]`` and ``expr[m, n]``do not raise an exception
+ if more than ``n`` ``expr``s exist in the input stream. If this behavior is
+ desired, then write ``expr[..., n] + ~expr``.
+ """
+
+ # convert single arg keys to tuples
+ try:
+ if isinstance(key, str_type):
+ key = (key,)
+ iter(key)
+ except TypeError:
+ key = (key, key)
+
+ if len(key) > 2:
+ raise TypeError(
+ "only 1 or 2 index arguments supported ({}{})".format(
+ key[:5], "... [{}]".format(len(key)) if len(key) > 5 else ""
+ )
+ )
+
+ # clip to 2 elements
+ ret = self * tuple(key[:2])
+ return ret
+
+ def __call__(self, name: str = None) -> "ParserElement":
+ """
+ Shortcut for :class:`set_results_name`, with ``list_all_matches=False``.
+
+ If ``name`` is given with a trailing ``'*'`` character, then ``list_all_matches`` will be
+ passed as ``True``.
+
+ If ``name` is omitted, same as calling :class:`copy`.
+
+ Example::
+
+ # these are equivalent
+ userdata = Word(alphas).set_results_name("name") + Word(nums + "-").set_results_name("socsecno")
+ userdata = Word(alphas)("name") + Word(nums + "-")("socsecno")
+ """
+ if name is not None:
+ return self._setResultsName(name)
+ else:
+ return self.copy()
+
+ def suppress(self) -> "ParserElement":
+ """
+ Suppresses the output of this :class:`ParserElement`; useful to keep punctuation from
+ cluttering up returned output.
+ """
+ return Suppress(self)
+
+ def ignore_whitespace(self, recursive: bool = True) -> "ParserElement":
+ """
+ Enables the skipping of whitespace before matching the characters in the
+ :class:`ParserElement`'s defined pattern.
+
+ :param recursive: If ``True`` (the default), also enable whitespace skipping in child elements (if any)
+ """
+ self.skipWhitespace = True
+ return self
+
+ def leave_whitespace(self, recursive: bool = True) -> "ParserElement":
+ """
+ Disables the skipping of whitespace before matching the characters in the
+ :class:`ParserElement`'s defined pattern. This is normally only used internally by
+ the pyparsing module, but may be needed in some whitespace-sensitive grammars.
+
+ :param recursive: If true (the default), also disable whitespace skipping in child elements (if any)
+ """
+ self.skipWhitespace = False
+ return self
+
+ def set_whitespace_chars(
+ self, chars: Union[Set[str], str], copy_defaults: bool = False
+ ) -> "ParserElement":
+ """
+ Overrides the default whitespace chars
+ """
+ self.skipWhitespace = True
+ self.whiteChars = set(chars)
+ self.copyDefaultWhiteChars = copy_defaults
+ return self
+
+ def parse_with_tabs(self) -> "ParserElement":
+ """
+ Overrides default behavior to expand ``<TAB>`` s to spaces before parsing the input string.
+ Must be called before ``parse_string`` when the input grammar contains elements that
+ match ``<TAB>`` characters.
+ """
+ self.keepTabs = True
+ return self
+
+ def ignore(self, other: "ParserElement") -> "ParserElement":
+ """
+ Define expression to be ignored (e.g., comments) while doing pattern
+ matching; may be called repeatedly, to define multiple comment or other
+ ignorable patterns.
+
+ Example::
+
+ patt = OneOrMore(Word(alphas))
+ patt.parse_string('ablaj /* comment */ lskjd')
+ # -> ['ablaj']
+
+ patt.ignore(c_style_comment)
+ patt.parse_string('ablaj /* comment */ lskjd')
+ # -> ['ablaj', 'lskjd']
+ """
+ import typing
+
+ if isinstance(other, str_type):
+ other = Suppress(other)
+
+ if isinstance(other, Suppress):
+ if other not in self.ignoreExprs:
+ self.ignoreExprs.append(other)
+ else:
+ self.ignoreExprs.append(Suppress(other.copy()))
+ return self
+
+ def set_debug_actions(
+ self,
+ start_action: DebugStartAction,
+ success_action: DebugSuccessAction,
+ exception_action: DebugExceptionAction,
+ ) -> "ParserElement":
+ """
+ Customize display of debugging messages while doing pattern matching:
+
+ - ``start_action`` - method to be called when an expression is about to be parsed;
+ should have the signature ``fn(input_string: str, location: int, expression: ParserElement, cache_hit: bool)``
+
+ - ``success_action`` - method to be called when an expression has successfully parsed;
+ should have the signature ``fn(input_string: str, start_location: int, end_location: int, expression: ParserELement, parsed_tokens: ParseResults, cache_hit: bool)``
+
+ - ``exception_action`` - method to be called when expression fails to parse;
+ should have the signature ``fn(input_string: str, location: int, expression: ParserElement, exception: Exception, cache_hit: bool)``
+ """
+ self.debugActions = self.DebugActions(
+ start_action or _default_start_debug_action,
+ success_action or _default_success_debug_action,
+ exception_action or _default_exception_debug_action,
+ )
+ self.debug = True
+ return self
+
+ def set_debug(self, flag: bool = True) -> "ParserElement":
+ """
+ Enable display of debugging messages while doing pattern matching.
+ Set ``flag`` to ``True`` to enable, ``False`` to disable.
+
+ Example::
+
+ wd = Word(alphas).set_name("alphaword")
+ integer = Word(nums).set_name("numword")
+ term = wd | integer
+
+ # turn on debugging for wd
+ wd.set_debug()
+
+ OneOrMore(term).parse_string("abc 123 xyz 890")
+
+ prints::
+
+ Match alphaword at loc 0(1,1)
+ Matched alphaword -> ['abc']
+ Match alphaword at loc 3(1,4)
+ Exception raised:Expected alphaword (at char 4), (line:1, col:5)
+ Match alphaword at loc 7(1,8)
+ Matched alphaword -> ['xyz']
+ Match alphaword at loc 11(1,12)
+ Exception raised:Expected alphaword (at char 12), (line:1, col:13)
+ Match alphaword at loc 15(1,16)
+ Exception raised:Expected alphaword (at char 15), (line:1, col:16)
+
+ The output shown is that produced by the default debug actions - custom debug actions can be
+ specified using :class:`set_debug_actions`. Prior to attempting
+ to match the ``wd`` expression, the debugging message ``"Match <exprname> at loc <n>(<line>,<col>)"``
+ is shown. Then if the parse succeeds, a ``"Matched"`` message is shown, or an ``"Exception raised"``
+ message is shown. Also note the use of :class:`set_name` to assign a human-readable name to the expression,
+ which makes debugging and exception messages easier to understand - for instance, the default
+ name created for the :class:`Word` expression without calling ``set_name`` is ``"W:(A-Za-z)"``.
+ """
+ if flag:
+ self.set_debug_actions(
+ _default_start_debug_action,
+ _default_success_debug_action,
+ _default_exception_debug_action,
+ )
+ else:
+ self.debug = False
+ return self
+
+ @property
+ def default_name(self) -> str:
+ if self._defaultName is None:
+ self._defaultName = self._generateDefaultName()
+ return self._defaultName
+
+ @abstractmethod
+ def _generateDefaultName(self):
+ """
+ Child classes must define this method, which defines how the ``default_name`` is set.
+ """
+
+ def set_name(self, name: str) -> "ParserElement":
+ """
+ Define name for this expression, makes debugging and exception messages clearer.
+ Example::
+ Word(nums).parse_string("ABC") # -> Exception: Expected W:(0-9) (at char 0), (line:1, col:1)
+ Word(nums).set_name("integer").parse_string("ABC") # -> Exception: Expected integer (at char 0), (line:1, col:1)
+ """
+ self.customName = name
+ self.errmsg = "Expected " + self.name
+ if __diag__.enable_debug_on_named_expressions:
+ self.set_debug()
+ return self
+
+ @property
+ def name(self) -> str:
+ # This will use a user-defined name if available, but otherwise defaults back to the auto-generated name
+ return self.customName if self.customName is not None else self.default_name
+
+ def __str__(self) -> str:
+ return self.name
+
+ def __repr__(self) -> str:
+ return str(self)
+
+ def streamline(self) -> "ParserElement":
+ self.streamlined = True
+ self._defaultName = None
+ return self
+
+ def recurse(self) -> Sequence["ParserElement"]:
+ return []
+
+ def _checkRecursion(self, parseElementList):
+ subRecCheckList = parseElementList[:] + [self]
+ for e in self.recurse():
+ e._checkRecursion(subRecCheckList)
+
+ def validate(self, validateTrace=None) -> None:
+ """
+ Check defined expressions for valid structure, check for infinite recursive definitions.
+ """
+ self._checkRecursion([])
+
+ def parse_file(
+ self,
+ file_or_filename: Union[str, Path, TextIO],
+ encoding: str = "utf-8",
+ parse_all: bool = False,
+ *,
+ parseAll: bool = False,
+ ) -> ParseResults:
+ """
+ Execute the parse expression on the given file or filename.
+ If a filename is specified (instead of a file object),
+ the entire file is opened, read, and closed before parsing.
+ """
+ parseAll = parseAll or parse_all
+ try:
+ file_contents = file_or_filename.read()
+ except AttributeError:
+ with open(file_or_filename, "r", encoding=encoding) as f:
+ file_contents = f.read()
+ try:
+ return self.parse_string(file_contents, parseAll)
+ except ParseBaseException as exc:
+ if ParserElement.verbose_stacktrace:
+ raise
+ else:
+ # catch and re-raise exception from here, clears out pyparsing internal stack trace
+ raise exc.with_traceback(None)
+
+ def __eq__(self, other):
+ if self is other:
+ return True
+ elif isinstance(other, str_type):
+ return self.matches(other, parse_all=True)
+ elif isinstance(other, ParserElement):
+ return vars(self) == vars(other)
+ return False
+
+ def __hash__(self):
+ return id(self)
+
+ def matches(
+ self, test_string: str, parse_all: bool = True, *, parseAll: bool = True
+ ) -> bool:
+ """
+ Method for quick testing of a parser against a test string. Good for simple
+ inline microtests of sub expressions while building up larger parser.
+
+ Parameters:
+ - ``test_string`` - to test against this expression for a match
+ - ``parse_all`` - (default= ``True``) - flag to pass to :class:`parse_string` when running tests
+
+ Example::
+
+ expr = Word(nums)
+ assert expr.matches("100")
+ """
+ parseAll = parseAll and parse_all
+ try:
+ self.parse_string(str(test_string), parse_all=parseAll)
+ return True
+ except ParseBaseException:
+ return False
+
+ def run_tests(
+ self,
+ tests: Union[str, List[str]],
+ parse_all: bool = True,
+ comment: OptionalType[Union["ParserElement", str]] = "#",
+ full_dump: bool = True,
+ print_results: bool = True,
+ failure_tests: bool = False,
+ post_parse: Callable[[str, ParseResults], str] = None,
+ file: OptionalType[TextIO] = None,
+ with_line_numbers: bool = False,
+ *,
+ parseAll: bool = True,
+ fullDump: bool = True,
+ printResults: bool = True,
+ failureTests: bool = False,
+ postParse: Callable[[str, ParseResults], str] = None,
+ ) -> Tuple[bool, List[Tuple[str, Union[ParseResults, Exception]]]]:
+ """
+ Execute the parse expression on a series of test strings, showing each
+ test, the parsed results or where the parse failed. Quick and easy way to
+ run a parse expression against a list of sample strings.
+
+ Parameters:
+ - ``tests`` - a list of separate test strings, or a multiline string of test strings
+ - ``parse_all`` - (default= ``True``) - flag to pass to :class:`parse_string` when running tests
+ - ``comment`` - (default= ``'#'``) - expression for indicating embedded comments in the test
+ string; pass None to disable comment filtering
+ - ``full_dump`` - (default= ``True``) - dump results as list followed by results names in nested outline;
+ if False, only dump nested list
+ - ``print_results`` - (default= ``True``) prints test output to stdout
+ - ``failure_tests`` - (default= ``False``) indicates if these tests are expected to fail parsing
+ - ``post_parse`` - (default= ``None``) optional callback for successful parse results; called as
+ `fn(test_string, parse_results)` and returns a string to be added to the test output
+ - ``file`` - (default= ``None``) optional file-like object to which test output will be written;
+ if None, will default to ``sys.stdout``
+ - ``with_line_numbers`` - default= ``False``) show test strings with line and column numbers
+
+ Returns: a (success, results) tuple, where success indicates that all tests succeeded
+ (or failed if ``failure_tests`` is True), and the results contain a list of lines of each
+ test's output
+
+ Example::
+
+ number_expr = pyparsing_common.number.copy()
+
+ result = number_expr.run_tests('''
+ # unsigned integer
+ 100
+ # negative integer
+ -100
+ # float with scientific notation
+ 6.02e23
+ # integer with scientific notation
+ 1e-12
+ ''')
+ print("Success" if result[0] else "Failed!")
+
+ result = number_expr.run_tests('''
+ # stray character
+ 100Z
+ # missing leading digit before '.'
+ -.100
+ # too many '.'
+ 3.14.159
+ ''', failure_tests=True)
+ print("Success" if result[0] else "Failed!")
+
+ prints::
+
+ # unsigned integer
+ 100
+ [100]
+
+ # negative integer
+ -100
+ [-100]
+
+ # float with scientific notation
+ 6.02e23
+ [6.02e+23]
+
+ # integer with scientific notation
+ 1e-12
+ [1e-12]
+
+ Success
+
+ # stray character
+ 100Z
+ ^
+ FAIL: Expected end of text (at char 3), (line:1, col:4)
+
+ # missing leading digit before '.'
+ -.100
+ ^
+ FAIL: Expected {real number with scientific notation | real number | signed integer} (at char 0), (line:1, col:1)
+
+ # too many '.'
+ 3.14.159
+ ^
+ FAIL: Expected end of text (at char 4), (line:1, col:5)
+
+ Success
+
+ Each test string must be on a single line. If you want to test a string that spans multiple
+ lines, create a test like this::
+
+ expr.run_tests(r"this is a test\\n of strings that spans \\n 3 lines")
+
+ (Note that this is a raw string literal, you must include the leading ``'r'``.)
+ """
+ from .testing import pyparsing_test
+
+ parseAll = parseAll and parse_all
+ fullDump = fullDump and full_dump
+ printResults = printResults and print_results
+ failureTests = failureTests or failure_tests
+ postParse = postParse or post_parse
+ if isinstance(tests, str_type):
+ line_strip = type(tests).strip
+ tests = [line_strip(test_line) for test_line in tests.rstrip().splitlines()]
+ if isinstance(comment, str_type):
+ comment = Literal(comment)
+ if file is None:
+ file = sys.stdout
+ print_ = file.write
+
+ result: Union[ParseResults, Exception]
+ allResults = []
+ comments = []
+ success = True
+ NL = Literal(r"\n").add_parse_action(replace_with("\n")).ignore(quoted_string)
+ BOM = "\ufeff"
+ for t in tests:
+ if comment is not None and comment.matches(t, False) or comments and not t:
+ comments.append(
+ pyparsing_test.with_line_numbers(t) if with_line_numbers else t
+ )
+ continue
+ if not t:
+ continue
+ out = [
+ "\n" + "\n".join(comments) if comments else "",
+ pyparsing_test.with_line_numbers(t) if with_line_numbers else t,
+ ]
+ comments = []
+ try:
+ # convert newline marks to actual newlines, and strip leading BOM if present
+ t = NL.transform_string(t.lstrip(BOM))
+ result = self.parse_string(t, parse_all=parseAll)
+ except ParseBaseException as pe:
+ fatal = "(FATAL)" if isinstance(pe, ParseFatalException) else ""
+ out.append(pe.explain())
+ out.append("FAIL: " + str(pe))
+ if ParserElement.verbose_stacktrace:
+ out.extend(traceback.format_tb(pe.__traceback__))
+ success = success and failureTests
+ result = pe
+ except Exception as exc:
+ out.append("FAIL-EXCEPTION: {}: {}".format(type(exc).__name__, exc))
+ if ParserElement.verbose_stacktrace:
+ out.extend(traceback.format_tb(exc.__traceback__))
+ success = success and failureTests
+ result = exc
+ else:
+ success = success and not failureTests
+ if postParse is not None:
+ try:
+ pp_value = postParse(t, result)
+ if pp_value is not None:
+ if isinstance(pp_value, ParseResults):
+ out.append(pp_value.dump())
+ else:
+ out.append(str(pp_value))
+ else:
+ out.append(result.dump())
+ except Exception as e:
+ out.append(result.dump(full=fullDump))
+ out.append(
+ "{} failed: {}: {}".format(
+ postParse.__name__, type(e).__name__, e
+ )
+ )
+ else:
+ out.append(result.dump(full=fullDump))
+ out.append("")
+
+ if printResults:
+ print_("\n".join(out))
+
+ allResults.append((t, result))
+
+ return success, allResults
+
+ def create_diagram(
+ self,
+ output_html: Union[TextIO, Path, str],
+ vertical: int = 3,
+ show_results_names: bool = False,
+ show_groups: bool = False,
+ **kwargs,
+ ) -> None:
+ """
+ Create a railroad diagram for the parser.
+
+ Parameters:
+ - output_html (str or file-like object) - output target for generated
+ diagram HTML
+ - vertical (int) - threshold for formatting multiple alternatives vertically
+ instead of horizontally (default=3)
+ - show_results_names - bool flag whether diagram should show annotations for
+ defined results names
+ - show_groups - bool flag whether groups should be highlighted with an unlabeled surrounding box
+ Additional diagram-formatting keyword arguments can also be included;
+ see railroad.Diagram class.
+ """
+
+ try:
+ from .diagram import to_railroad, railroad_to_html
+ except ImportError as ie:
+ raise Exception(
+ "must ``pip install pyparsing[diagrams]`` to generate parser railroad diagrams"
+ ) from ie
+
+ self.streamline()
+
+ railroad = to_railroad(
+ self,
+ vertical=vertical,
+ show_results_names=show_results_names,
+ show_groups=show_groups,
+ diagram_kwargs=kwargs,
+ )
+ if isinstance(output_html, (str, Path)):
+ with open(output_html, "w", encoding="utf-8") as diag_file:
+ diag_file.write(railroad_to_html(railroad))
+ else:
+ # we were passed a file-like object, just write to it
+ output_html.write(railroad_to_html(railroad))
+
+ setDefaultWhitespaceChars = set_default_whitespace_chars
+ inlineLiteralsUsing = inline_literals_using
+ setResultsName = set_results_name
+ setBreak = set_break
+ setParseAction = set_parse_action
+ addParseAction = add_parse_action
+ addCondition = add_condition
+ setFailAction = set_fail_action
+ tryParse = try_parse
+ canParseNext = can_parse_next
+ resetCache = reset_cache
+ enableLeftRecursion = enable_left_recursion
+ enablePackrat = enable_packrat
+ parseString = parse_string
+ scanString = scan_string
+ searchString = search_string
+ transformString = transform_string
+ setWhitespaceChars = set_whitespace_chars
+ parseWithTabs = parse_with_tabs
+ setDebugActions = set_debug_actions
+ setDebug = set_debug
+ defaultName = default_name
+ setName = set_name
+ parseFile = parse_file
+ runTests = run_tests
+ ignoreWhitespace = ignore_whitespace
+ leaveWhitespace = leave_whitespace
+
+
+class _PendingSkip(ParserElement):
+ # internal placeholder class to hold a place were '...' is added to a parser element,
+ # once another ParserElement is added, this placeholder will be replaced with a SkipTo
+ def __init__(self, expr: ParserElement, must_skip: bool = False):
+ super().__init__()
+ self.anchor = expr
+ self.must_skip = must_skip
+
+ def _generateDefaultName(self):
+ return str(self.anchor + Empty()).replace("Empty", "...")
+
+ def __add__(self, other) -> "ParserElement":
+ skipper = SkipTo(other).set_name("...")("_skipped*")
+ if self.must_skip:
+
+ def must_skip(t):
+ if not t._skipped or t._skipped.as_list() == [""]:
+ del t[0]
+ t.pop("_skipped", None)
+
+ def show_skip(t):
+ if t._skipped.as_list()[-1:] == [""]:
+ t.pop("_skipped")
+ t["_skipped"] = "missing <" + repr(self.anchor) + ">"
+
+ return (
+ self.anchor + skipper().add_parse_action(must_skip)
+ | skipper().add_parse_action(show_skip)
+ ) + other
+
+ return self.anchor + skipper + other
+
+ def __repr__(self):
+ return self.defaultName
+
+ def parseImpl(self, *args):
+ raise Exception(
+ "use of `...` expression without following SkipTo target expression"
+ )
+
+
+class Token(ParserElement):
+ """Abstract :class:`ParserElement` subclass, for defining atomic
+ matching patterns.
+ """
+
+ def __init__(self):
+ super().__init__(savelist=False)
+
+ def _generateDefaultName(self):
+ return type(self).__name__
+
+
+class Empty(Token):
+ """
+ An empty token, will always match.
+ """
+
+ def __init__(self):
+ super().__init__()
+ self.mayReturnEmpty = True
+ self.mayIndexError = False
+
+
+class NoMatch(Token):
+ """
+ A token that will never match.
+ """
+
+ def __init__(self):
+ super().__init__()
+ self.mayReturnEmpty = True
+ self.mayIndexError = False
+ self.errmsg = "Unmatchable token"
+
+ def parseImpl(self, instring, loc, doActions=True):
+ raise ParseException(instring, loc, self.errmsg, self)
+
+
+class Literal(Token):
+ """
+ Token to exactly match a specified string.
+
+ Example::
+
+ Literal('blah').parse_string('blah') # -> ['blah']
+ Literal('blah').parse_string('blahfooblah') # -> ['blah']
+ Literal('blah').parse_string('bla') # -> Exception: Expected "blah"
+
+ For case-insensitive matching, use :class:`CaselessLiteral`.
+
+ For keyword matching (force word break before and after the matched string),
+ use :class:`Keyword` or :class:`CaselessKeyword`.
+ """
+
+ def __init__(self, match_string: str = "", *, matchString: str = ""):
+ super().__init__()
+ match_string = matchString or match_string
+ self.match = match_string
+ self.matchLen = len(match_string)
+ try:
+ self.firstMatchChar = match_string[0]
+ except IndexError:
+ raise ValueError("null string passed to Literal; use Empty() instead")
+ self.errmsg = "Expected " + self.name
+ self.mayReturnEmpty = False
+ self.mayIndexError = False
+
+ # Performance tuning: modify __class__ to select
+ # a parseImpl optimized for single-character check
+ if self.matchLen == 1 and type(self) is Literal:
+ self.__class__ = _SingleCharLiteral
+
+ def _generateDefaultName(self):
+ return repr(self.match)
+
+ def parseImpl(self, instring, loc, doActions=True):
+ if instring[loc] == self.firstMatchChar and instring.startswith(
+ self.match, loc
+ ):
+ return loc + self.matchLen, self.match
+ raise ParseException(instring, loc, self.errmsg, self)
+
+
+class _SingleCharLiteral(Literal):
+ def parseImpl(self, instring, loc, doActions=True):
+ if instring[loc] == self.firstMatchChar:
+ return loc + 1, self.match
+ raise ParseException(instring, loc, self.errmsg, self)
+
+
+ParserElement._literalStringClass = Literal
+
+
+class Keyword(Token):
+ """
+ Token to exactly match a specified string as a keyword, that is,
+ it must be immediately followed by a non-keyword character. Compare
+ with :class:`Literal`:
+
+ - ``Literal("if")`` will match the leading ``'if'`` in
+ ``'ifAndOnlyIf'``.
+ - ``Keyword("if")`` will not; it will only match the leading
+ ``'if'`` in ``'if x=1'``, or ``'if(y==2)'``
+
+ Accepts two optional constructor arguments in addition to the
+ keyword string:
+
+ - ``identChars`` is a string of characters that would be valid
+ identifier characters, defaulting to all alphanumerics + "_" and
+ "$"
+ - ``caseless`` allows case-insensitive matching, default is ``False``.
+
+ Example::
+
+ Keyword("start").parse_string("start") # -> ['start']
+ Keyword("start").parse_string("starting") # -> Exception
+
+ For case-insensitive matching, use :class:`CaselessKeyword`.
+ """
+
+ DEFAULT_KEYWORD_CHARS = alphanums + "_$"
+
+ def __init__(
+ self,
+ match_string: str = "",
+ ident_chars: OptionalType[str] = None,
+ caseless: bool = False,
+ *,
+ matchString: str = "",
+ identChars: OptionalType[str] = None,
+ ):
+ super().__init__()
+ identChars = identChars or ident_chars
+ if identChars is None:
+ identChars = Keyword.DEFAULT_KEYWORD_CHARS
+ match_string = matchString or match_string
+ self.match = match_string
+ self.matchLen = len(match_string)
+ try:
+ self.firstMatchChar = match_string[0]
+ except IndexError:
+ raise ValueError("null string passed to Keyword; use Empty() instead")
+ self.errmsg = "Expected {} {}".format(type(self).__name__, self.name)
+ self.mayReturnEmpty = False
+ self.mayIndexError = False
+ self.caseless = caseless
+ if caseless:
+ self.caselessmatch = match_string.upper()
+ identChars = identChars.upper()
+ self.identChars = set(identChars)
+
+ def _generateDefaultName(self):
+ return repr(self.match)
+
+ def parseImpl(self, instring, loc, doActions=True):
+ errmsg = self.errmsg
+ errloc = loc
+ if self.caseless:
+ if instring[loc : loc + self.matchLen].upper() == self.caselessmatch:
+ if loc == 0 or instring[loc - 1].upper() not in self.identChars:
+ if (
+ loc >= len(instring) - self.matchLen
+ or instring[loc + self.matchLen].upper() not in self.identChars
+ ):
+ return loc + self.matchLen, self.match
+ else:
+ # followed by keyword char
+ errmsg += ", was immediately followed by keyword character"
+ errloc = loc + self.matchLen
+ else:
+ # preceded by keyword char
+ errmsg += ", keyword was immediately preceded by keyword character"
+ errloc = loc - 1
+ # else no match just raise plain exception
+
+ else:
+ if (
+ instring[loc] == self.firstMatchChar
+ and self.matchLen == 1
+ or instring.startswith(self.match, loc)
+ ):
+ if loc == 0 or instring[loc - 1] not in self.identChars:
+ if (
+ loc >= len(instring) - self.matchLen
+ or instring[loc + self.matchLen] not in self.identChars
+ ):
+ return loc + self.matchLen, self.match
+ else:
+ # followed by keyword char
+ errmsg += (
+ ", keyword was immediately followed by keyword character"
+ )
+ errloc = loc + self.matchLen
+ else:
+ # preceded by keyword char
+ errmsg += ", keyword was immediately preceded by keyword character"
+ errloc = loc - 1
+ # else no match just raise plain exception
+
+ raise ParseException(instring, errloc, errmsg, self)
+
+ @staticmethod
+ def set_default_keyword_chars(chars) -> None:
+ """
+ Overrides the default characters used by :class:`Keyword` expressions.
+ """
+ Keyword.DEFAULT_KEYWORD_CHARS = chars
+
+ setDefaultKeywordChars = set_default_keyword_chars
+
+
+class CaselessLiteral(Literal):
+ """
+ Token to match a specified string, ignoring case of letters.
+ Note: the matched results will always be in the case of the given
+ match string, NOT the case of the input text.
+
+ Example::
+
+ OneOrMore(CaselessLiteral("CMD")).parse_string("cmd CMD Cmd10")
+ # -> ['CMD', 'CMD', 'CMD']
+
+ (Contrast with example for :class:`CaselessKeyword`.)
+ """
+
+ def __init__(self, match_string: str = "", *, matchString: str = ""):
+ match_string = matchString or match_string
+ super().__init__(match_string.upper())
+ # Preserve the defining literal.
+ self.returnString = match_string
+ self.errmsg = "Expected " + self.name
+
+ def parseImpl(self, instring, loc, doActions=True):
+ if instring[loc : loc + self.matchLen].upper() == self.match:
+ return loc + self.matchLen, self.returnString
+ raise ParseException(instring, loc, self.errmsg, self)
+
+
+class CaselessKeyword(Keyword):
+ """
+ Caseless version of :class:`Keyword`.
+
+ Example::
+
+ OneOrMore(CaselessKeyword("CMD")).parse_string("cmd CMD Cmd10")
+ # -> ['CMD', 'CMD']
+
+ (Contrast with example for :class:`CaselessLiteral`.)
+ """
+
+ def __init__(
+ self,
+ match_string: str = "",
+ ident_chars: OptionalType[str] = None,
+ *,
+ matchString: str = "",
+ identChars: OptionalType[str] = None,
+ ):
+ identChars = identChars or ident_chars
+ match_string = matchString or match_string
+ super().__init__(match_string, identChars, caseless=True)
+
+
+class CloseMatch(Token):
+ """A variation on :class:`Literal` which matches "close" matches,
+ that is, strings with at most 'n' mismatching characters.
+ :class:`CloseMatch` takes parameters:
+
+ - ``match_string`` - string to be matched
+ - ``caseless`` - a boolean indicating whether to ignore casing when comparing characters
+ - ``max_mismatches`` - (``default=1``) maximum number of
+ mismatches allowed to count as a match
+
+ The results from a successful parse will contain the matched text
+ from the input string and the following named results:
+
+ - ``mismatches`` - a list of the positions within the
+ match_string where mismatches were found
+ - ``original`` - the original match_string used to compare
+ against the input string
+
+ If ``mismatches`` is an empty list, then the match was an exact
+ match.
+
+ Example::
+
+ patt = CloseMatch("ATCATCGAATGGA")
+ patt.parse_string("ATCATCGAAXGGA") # -> (['ATCATCGAAXGGA'], {'mismatches': [[9]], 'original': ['ATCATCGAATGGA']})
+ patt.parse_string("ATCAXCGAAXGGA") # -> Exception: Expected 'ATCATCGAATGGA' (with up to 1 mismatches) (at char 0), (line:1, col:1)
+
+ # exact match
+ patt.parse_string("ATCATCGAATGGA") # -> (['ATCATCGAATGGA'], {'mismatches': [[]], 'original': ['ATCATCGAATGGA']})
+
+ # close match allowing up to 2 mismatches
+ patt = CloseMatch("ATCATCGAATGGA", max_mismatches=2)
+ patt.parse_string("ATCAXCGAAXGGA") # -> (['ATCAXCGAAXGGA'], {'mismatches': [[4, 9]], 'original': ['ATCATCGAATGGA']})
+ """
+
+ def __init__(
+ self,
+ match_string: str,
+ max_mismatches: int = None,
+ *,
+ maxMismatches: int = 1,
+ caseless=False,
+ ):
+ maxMismatches = max_mismatches if max_mismatches is not None else maxMismatches
+ super().__init__()
+ self.match_string = match_string
+ self.maxMismatches = maxMismatches
+ self.errmsg = "Expected {!r} (with up to {} mismatches)".format(
+ self.match_string, self.maxMismatches
+ )
+ self.caseless = caseless
+ self.mayIndexError = False
+ self.mayReturnEmpty = False
+
+ def _generateDefaultName(self):
+ return "{}:{!r}".format(type(self).__name__, self.match_string)
+
+ def parseImpl(self, instring, loc, doActions=True):
+ start = loc
+ instrlen = len(instring)
+ maxloc = start + len(self.match_string)
+
+ if maxloc <= instrlen:
+ match_string = self.match_string
+ match_stringloc = 0
+ mismatches = []
+ maxMismatches = self.maxMismatches
+
+ for match_stringloc, s_m in enumerate(
+ zip(instring[loc:maxloc], match_string)
+ ):
+ src, mat = s_m
+ if self.caseless:
+ src, mat = src.lower(), mat.lower()
+
+ if src != mat:
+ mismatches.append(match_stringloc)
+ if len(mismatches) > maxMismatches:
+ break
+ else:
+ loc = start + match_stringloc + 1
+ results = ParseResults([instring[start:loc]])
+ results["original"] = match_string
+ results["mismatches"] = mismatches
+ return loc, results
+
+ raise ParseException(instring, loc, self.errmsg, self)
+
+
+class Word(Token):
+ """Token for matching words composed of allowed character sets.
+ Parameters:
+ - ``init_chars`` - string of all characters that should be used to
+ match as a word; "ABC" will match "AAA", "ABAB", "CBAC", etc.;
+ if ``body_chars`` is also specified, then this is the string of
+ initial characters
+ - ``body_chars`` - string of characters that
+ can be used for matching after a matched initial character as
+ given in ``init_chars``; if omitted, same as the initial characters
+ (default=``None``)
+ - ``min`` - minimum number of characters to match (default=1)
+ - ``max`` - maximum number of characters to match (default=0)
+ - ``exact`` - exact number of characters to match (default=0)
+ - ``as_keyword`` - match as a keyword (default=``False``)
+ - ``exclude_chars`` - characters that might be
+ found in the input ``body_chars`` string but which should not be
+ accepted for matching ;useful to define a word of all
+ printables except for one or two characters, for instance
+ (default=``None``)
+
+ :class:`srange` is useful for defining custom character set strings
+ for defining :class:`Word` expressions, using range notation from
+ regular expression character sets.
+
+ A common mistake is to use :class:`Word` to match a specific literal
+ string, as in ``Word("Address")``. Remember that :class:`Word`
+ uses the string argument to define *sets* of matchable characters.
+ This expression would match "Add", "AAA", "dAred", or any other word
+ made up of the characters 'A', 'd', 'r', 'e', and 's'. To match an
+ exact literal string, use :class:`Literal` or :class:`Keyword`.
+
+ pyparsing includes helper strings for building Words:
+
+ - :class:`alphas`
+ - :class:`nums`
+ - :class:`alphanums`
+ - :class:`hexnums`
+ - :class:`alphas8bit` (alphabetic characters in ASCII range 128-255
+ - accented, tilded, umlauted, etc.)
+ - :class:`punc8bit` (non-alphabetic characters in ASCII range
+ 128-255 - currency, symbols, superscripts, diacriticals, etc.)
+ - :class:`printables` (any non-whitespace character)
+
+ ``alphas``, ``nums``, and ``printables`` are also defined in several
+ Unicode sets - see :class:`pyparsing_unicode``.
+
+ Example::
+
+ # a word composed of digits
+ integer = Word(nums) # equivalent to Word("0123456789") or Word(srange("0-9"))
+
+ # a word with a leading capital, and zero or more lowercase
+ capital_word = Word(alphas.upper(), alphas.lower())
+
+ # hostnames are alphanumeric, with leading alpha, and '-'
+ hostname = Word(alphas, alphanums + '-')
+
+ # roman numeral (not a strict parser, accepts invalid mix of characters)
+ roman = Word("IVXLCDM")
+
+ # any string of non-whitespace characters, except for ','
+ csv_value = Word(printables, exclude_chars=",")
+ """
+
+ def __init__(
+ self,
+ init_chars: str = "",
+ body_chars: OptionalType[str] = None,
+ min: int = 1,
+ max: int = 0,
+ exact: int = 0,
+ as_keyword: bool = False,
+ exclude_chars: OptionalType[str] = None,
+ *,
+ initChars: OptionalType[str] = None,
+ bodyChars: OptionalType[str] = None,
+ asKeyword: bool = False,
+ excludeChars: OptionalType[str] = None,
+ ):
+ initChars = initChars or init_chars
+ bodyChars = bodyChars or body_chars
+ asKeyword = asKeyword or as_keyword
+ excludeChars = excludeChars or exclude_chars
+ super().__init__()
+ if not initChars:
+ raise ValueError(
+ "invalid {}, initChars cannot be empty string".format(
+ type(self).__name__
+ )
+ )
+
+ initChars = set(initChars)
+ self.initChars = initChars
+ if excludeChars:
+ excludeChars = set(excludeChars)
+ initChars -= excludeChars
+ if bodyChars:
+ bodyChars = set(bodyChars) - excludeChars
+ self.initCharsOrig = "".join(sorted(initChars))
+
+ if bodyChars:
+ self.bodyCharsOrig = "".join(sorted(bodyChars))
+ self.bodyChars = set(bodyChars)
+ else:
+ self.bodyCharsOrig = "".join(sorted(initChars))
+ self.bodyChars = set(initChars)
+
+ self.maxSpecified = max > 0
+
+ if min < 1:
+ raise ValueError(
+ "cannot specify a minimum length < 1; use Opt(Word()) if zero-length word is permitted"
+ )
+
+ self.minLen = min
+
+ if max > 0:
+ self.maxLen = max
+ else:
+ self.maxLen = _MAX_INT
+
+ if exact > 0:
+ self.maxLen = exact
+ self.minLen = exact
+
+ self.errmsg = "Expected " + self.name
+ self.mayIndexError = False
+ self.asKeyword = asKeyword
+
+ # see if we can make a regex for this Word
+ if " " not in self.initChars | self.bodyChars and (min == 1 and exact == 0):
+ if self.bodyChars == self.initChars:
+ if max == 0:
+ repeat = "+"
+ elif max == 1:
+ repeat = ""
+ else:
+ repeat = "{{{},{}}}".format(
+ self.minLen, "" if self.maxLen == _MAX_INT else self.maxLen
+ )
+ self.reString = "[{}]{}".format(
+ _collapse_string_to_ranges(self.initChars),
+ repeat,
+ )
+ elif len(self.initChars) == 1:
+ if max == 0:
+ repeat = "*"
+ else:
+ repeat = "{{0,{}}}".format(max - 1)
+ self.reString = "{}[{}]{}".format(
+ re.escape(self.initCharsOrig),
+ _collapse_string_to_ranges(self.bodyChars),
+ repeat,
+ )
+ else:
+ if max == 0:
+ repeat = "*"
+ elif max == 2:
+ repeat = ""
+ else:
+ repeat = "{{0,{}}}".format(max - 1)
+ self.reString = "[{}][{}]{}".format(
+ _collapse_string_to_ranges(self.initChars),
+ _collapse_string_to_ranges(self.bodyChars),
+ repeat,
+ )
+ if self.asKeyword:
+ self.reString = r"\b" + self.reString + r"\b"
+
+ try:
+ self.re = re.compile(self.reString)
+ except re.error:
+ self.re = None
+ else:
+ self.re_match = self.re.match
+ self.__class__ = _WordRegex
+
+ def _generateDefaultName(self):
+ def charsAsStr(s):
+ max_repr_len = 16
+ s = _collapse_string_to_ranges(s, re_escape=False)
+ if len(s) > max_repr_len:
+ return s[: max_repr_len - 3] + "..."
+ else:
+ return s
+
+ if self.initChars != self.bodyChars:
+ base = "W:({}, {})".format(
+ charsAsStr(self.initChars), charsAsStr(self.bodyChars)
+ )
+ else:
+ base = "W:({})".format(charsAsStr(self.initChars))
+
+ # add length specification
+ if self.minLen > 1 or self.maxLen != _MAX_INT:
+ if self.minLen == self.maxLen:
+ if self.minLen == 1:
+ return base[2:]
+ else:
+ return base + "{{{}}}".format(self.minLen)
+ elif self.maxLen == _MAX_INT:
+ return base + "{{{},...}}".format(self.minLen)
+ else:
+ return base + "{{{},{}}}".format(self.minLen, self.maxLen)
+ return base
+
+ def parseImpl(self, instring, loc, doActions=True):
+ if instring[loc] not in self.initChars:
+ raise ParseException(instring, loc, self.errmsg, self)
+
+ start = loc
+ loc += 1
+ instrlen = len(instring)
+ bodychars = self.bodyChars
+ maxloc = start + self.maxLen
+ maxloc = min(maxloc, instrlen)
+ while loc < maxloc and instring[loc] in bodychars:
+ loc += 1
+
+ throwException = False
+ if loc - start < self.minLen:
+ throwException = True
+ elif self.maxSpecified and loc < instrlen and instring[loc] in bodychars:
+ throwException = True
+ elif self.asKeyword:
+ if (
+ start > 0
+ and instring[start - 1] in bodychars
+ or loc < instrlen
+ and instring[loc] in bodychars
+ ):
+ throwException = True
+
+ if throwException:
+ raise ParseException(instring, loc, self.errmsg, self)
+
+ return loc, instring[start:loc]
+
+
+class _WordRegex(Word):
+ def parseImpl(self, instring, loc, doActions=True):
+ result = self.re_match(instring, loc)
+ if not result:
+ raise ParseException(instring, loc, self.errmsg, self)
+
+ loc = result.end()
+ return loc, result.group()
+
+
+class Char(_WordRegex):
+ """A short-cut class for defining :class:`Word` ``(characters, exact=1)``,
+ when defining a match of any single character in a string of
+ characters.
+ """
+
+ def __init__(
+ self,
+ charset: str,
+ as_keyword: bool = False,
+ exclude_chars: OptionalType[str] = None,
+ *,
+ asKeyword: bool = False,
+ excludeChars: OptionalType[str] = None,
+ ):
+ asKeyword = asKeyword or as_keyword
+ excludeChars = excludeChars or exclude_chars
+ super().__init__(
+ charset, exact=1, asKeyword=asKeyword, excludeChars=excludeChars
+ )
+ self.reString = "[{}]".format(_collapse_string_to_ranges(self.initChars))
+ if asKeyword:
+ self.reString = r"\b{}\b".format(self.reString)
+ self.re = re.compile(self.reString)
+ self.re_match = self.re.match
+
+
+class Regex(Token):
+ r"""Token for matching strings that match a given regular
+ expression. Defined with string specifying the regular expression in
+ a form recognized by the stdlib Python `re module <https://docs.python.org/3/library/re.html>`_.
+ If the given regex contains named groups (defined using ``(?P<name>...)``),
+ these will be preserved as named :class:`ParseResults`.
+
+ If instead of the Python stdlib ``re`` module you wish to use a different RE module
+ (such as the ``regex`` module), you can do so by building your ``Regex`` object with
+ a compiled RE that was compiled using ``regex``.
+
+ Example::
+
+ realnum = Regex(r"[+-]?\d+\.\d*")
+ # ref: https://stackoverflow.com/questions/267399/how-do-you-match-only-valid-roman-numerals-with-a-regular-expression
+ roman = Regex(r"M{0,4}(CM|CD|D?{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})")
+
+ # named fields in a regex will be returned as named results
+ date = Regex(r'(?P<year>\d{4})-(?P<month>\d\d?)-(?P<day>\d\d?)')
+
+ # the Regex class will accept re's compiled using the regex module
+ import regex
+ parser = pp.Regex(regex.compile(r'[0-9]'))
+ """
+
+ def __init__(
+ self,
+ pattern: Any,
+ flags: Union[re.RegexFlag, int] = 0,
+ as_group_list: bool = False,
+ as_match: bool = False,
+ *,
+ asGroupList: bool = False,
+ asMatch: bool = False,
+ ):
+ """The parameters ``pattern`` and ``flags`` are passed
+ to the ``re.compile()`` function as-is. See the Python
+ `re module <https://docs.python.org/3/library/re.html>`_ module for an
+ explanation of the acceptable patterns and flags.
+ """
+ super().__init__()
+ asGroupList = asGroupList or as_group_list
+ asMatch = asMatch or as_match
+
+ if isinstance(pattern, str_type):
+ if not pattern:
+ raise ValueError("null string passed to Regex; use Empty() instead")
+
+ self._re = None
+ self.reString = self.pattern = pattern
+ self.flags = flags
+
+ elif hasattr(pattern, "pattern") and hasattr(pattern, "match"):
+ self._re = pattern
+ self.pattern = self.reString = pattern.pattern
+ self.flags = flags
+
+ else:
+ raise TypeError(
+ "Regex may only be constructed with a string or a compiled RE object"
+ )
+
+ self.errmsg = "Expected " + self.name
+ self.mayIndexError = False
+ self.asGroupList = asGroupList
+ self.asMatch = asMatch
+ if self.asGroupList:
+ self.parseImpl = self.parseImplAsGroupList
+ if self.asMatch:
+ self.parseImpl = self.parseImplAsMatch
+
+ @cached_property
+ def re(self):
+ if self._re:
+ return self._re
+ else:
+ try:
+ return re.compile(self.pattern, self.flags)
+ except re.error:
+ raise ValueError(
+ "invalid pattern ({!r}) passed to Regex".format(self.pattern)
+ )
+
+ @cached_property
+ def re_match(self):
+ return self.re.match
+
+ @cached_property
+ def mayReturnEmpty(self):
+ return self.re_match("") is not None
+
+ def _generateDefaultName(self):
+ return "Re:({})".format(repr(self.pattern).replace("\\\\", "\\"))
+
+ def parseImpl(self, instring, loc, doActions=True):
+ result = self.re_match(instring, loc)
+ if not result:
+ raise ParseException(instring, loc, self.errmsg, self)
+
+ loc = result.end()
+ ret = ParseResults(result.group())
+ d = result.groupdict()
+ if d:
+ for k, v in d.items():
+ ret[k] = v
+ return loc, ret
+
+ def parseImplAsGroupList(self, instring, loc, doActions=True):
+ result = self.re_match(instring, loc)
+ if not result:
+ raise ParseException(instring, loc, self.errmsg, self)
+
+ loc = result.end()
+ ret = result.groups()
+ return loc, ret
+
+ def parseImplAsMatch(self, instring, loc, doActions=True):
+ result = self.re_match(instring, loc)
+ if not result:
+ raise ParseException(instring, loc, self.errmsg, self)
+
+ loc = result.end()
+ ret = result
+ return loc, ret
+
+ def sub(self, repl: str) -> ParserElement:
+ r"""
+ Return :class:`Regex` with an attached parse action to transform the parsed
+ result as if called using `re.sub(expr, repl, string) <https://docs.python.org/3/library/re.html#re.sub>`_.
+
+ Example::
+
+ make_html = Regex(r"(\w+):(.*?):").sub(r"<\1>\2</\1>")
+ print(make_html.transform_string("h1:main title:"))
+ # prints "<h1>main title</h1>"
+ """
+ if self.asGroupList:
+ raise TypeError("cannot use sub() with Regex(asGroupList=True)")
+
+ if self.asMatch and callable(repl):
+ raise TypeError("cannot use sub() with a callable with Regex(asMatch=True)")
+
+ if self.asMatch:
+
+ def pa(tokens):
+ return tokens[0].expand(repl)
+
+ else:
+
+ def pa(tokens):
+ return self.re.sub(repl, tokens[0])
+
+ return self.add_parse_action(pa)
+
+
+class QuotedString(Token):
+ r"""
+ Token for matching strings that are delimited by quoting characters.
+
+ Defined with the following parameters:
+
+ - ``quote_char`` - string of one or more characters defining the
+ quote delimiting string
+ - ``esc_char`` - character to re_escape quotes, typically backslash
+ (default= ``None``)
+ - ``esc_quote`` - special quote sequence to re_escape an embedded quote
+ string (such as SQL's ``""`` to re_escape an embedded ``"``)
+ (default= ``None``)
+ - ``multiline`` - boolean indicating whether quotes can span
+ multiple lines (default= ``False``)
+ - ``unquote_results`` - boolean indicating whether the matched text
+ should be unquoted (default= ``True``)
+ - ``end_quote_char`` - string of one or more characters defining the
+ end of the quote delimited string (default= ``None`` => same as
+ quote_char)
+ - ``convert_whitespace_escapes`` - convert escaped whitespace
+ (``'\t'``, ``'\n'``, etc.) to actual whitespace
+ (default= ``True``)
+
+ Example::
+
+ qs = QuotedString('"')
+ print(qs.search_string('lsjdf "This is the quote" sldjf'))
+ complex_qs = QuotedString('{{', end_quote_char='}}')
+ print(complex_qs.search_string('lsjdf {{This is the "quote"}} sldjf'))
+ sql_qs = QuotedString('"', esc_quote='""')
+ print(sql_qs.search_string('lsjdf "This is the quote with ""embedded"" quotes" sldjf'))
+
+ prints::
+
+ [['This is the quote']]
+ [['This is the "quote"']]
+ [['This is the quote with "embedded" quotes']]
+ """
+ ws_map = ((r"\t", "\t"), (r"\n", "\n"), (r"\f", "\f"), (r"\r", "\r"))
+
+ def __init__(
+ self,
+ quote_char: str = "",
+ esc_char: OptionalType[str] = None,
+ esc_quote: OptionalType[str] = None,
+ multiline: bool = False,
+ unquote_results: bool = True,
+ end_quote_char: OptionalType[str] = None,
+ convert_whitespace_escapes: bool = True,
+ *,
+ quoteChar: str = "",
+ escChar: OptionalType[str] = None,
+ escQuote: OptionalType[str] = None,
+ unquoteResults: bool = True,
+ endQuoteChar: OptionalType[str] = None,
+ convertWhitespaceEscapes: bool = True,
+ ):
+ super().__init__()
+ escChar = escChar or esc_char
+ escQuote = escQuote or esc_quote
+ unquoteResults = unquoteResults and unquote_results
+ endQuoteChar = endQuoteChar or end_quote_char
+ convertWhitespaceEscapes = (
+ convertWhitespaceEscapes and convert_whitespace_escapes
+ )
+ quote_char = quoteChar or quote_char
+
+ # remove white space from quote chars - wont work anyway
+ quote_char = quote_char.strip()
+ if not quote_char:
+ raise ValueError("quote_char cannot be the empty string")
+
+ if endQuoteChar is None:
+ endQuoteChar = quote_char
+ else:
+ endQuoteChar = endQuoteChar.strip()
+ if not endQuoteChar:
+ raise ValueError("endQuoteChar cannot be the empty string")
+
+ self.quoteChar = quote_char
+ self.quoteCharLen = len(quote_char)
+ self.firstQuoteChar = quote_char[0]
+ self.endQuoteChar = endQuoteChar
+ self.endQuoteCharLen = len(endQuoteChar)
+ self.escChar = escChar
+ self.escQuote = escQuote
+ self.unquoteResults = unquoteResults
+ self.convertWhitespaceEscapes = convertWhitespaceEscapes
+
+ sep = ""
+ inner_pattern = ""
+
+ if escQuote:
+ inner_pattern += r"{}(?:{})".format(sep, re.escape(escQuote))
+ sep = "|"
+
+ if escChar:
+ inner_pattern += r"{}(?:{}.)".format(sep, re.escape(escChar))
+ sep = "|"
+ self.escCharReplacePattern = re.escape(self.escChar) + "(.)"
+
+ if len(self.endQuoteChar) > 1:
+ inner_pattern += (
+ "{}(?:".format(sep)
+ + "|".join(
+ "(?:{}(?!{}))".format(
+ re.escape(self.endQuoteChar[:i]),
+ re.escape(self.endQuoteChar[i:]),
+ )
+ for i in range(len(self.endQuoteChar) - 1, 0, -1)
+ )
+ + ")"
+ )
+ sep = "|"
+
+ if multiline:
+ self.flags = re.MULTILINE | re.DOTALL
+ inner_pattern += r"{}(?:[^{}{}])".format(
+ sep,
+ _escape_regex_range_chars(self.endQuoteChar[0]),
+ (_escape_regex_range_chars(escChar) if escChar is not None else ""),
+ )
+ else:
+ self.flags = 0
+ inner_pattern += r"{}(?:[^{}\n\r{}])".format(
+ sep,
+ _escape_regex_range_chars(self.endQuoteChar[0]),
+ (_escape_regex_range_chars(escChar) if escChar is not None else ""),
+ )
+
+ self.pattern = "".join(
+ [
+ re.escape(self.quoteChar),
+ "(?:",
+ inner_pattern,
+ ")*",
+ re.escape(self.endQuoteChar),
+ ]
+ )
+
+ try:
+ self.re = re.compile(self.pattern, self.flags)
+ self.reString = self.pattern
+ self.re_match = self.re.match
+ except re.error:
+ raise ValueError(
+ "invalid pattern {!r} passed to Regex".format(self.pattern)
+ )
+
+ self.errmsg = "Expected " + self.name
+ self.mayIndexError = False
+ self.mayReturnEmpty = True
+
+ def _generateDefaultName(self):
+ if self.quoteChar == self.endQuoteChar and isinstance(self.quoteChar, str_type):
+ return "string enclosed in {!r}".format(self.quoteChar)
+
+ return "quoted string, starting with {} ending with {}".format(
+ self.quoteChar, self.endQuoteChar
+ )
+
+ def parseImpl(self, instring, loc, doActions=True):
+ result = (
+ instring[loc] == self.firstQuoteChar
+ and self.re_match(instring, loc)
+ or None
+ )
+ if not result:
+ raise ParseException(instring, loc, self.errmsg, self)
+
+ loc = result.end()
+ ret = result.group()
+
+ if self.unquoteResults:
+
+ # strip off quotes
+ ret = ret[self.quoteCharLen : -self.endQuoteCharLen]
+
+ if isinstance(ret, str_type):
+ # replace escaped whitespace
+ if "\\" in ret and self.convertWhitespaceEscapes:
+ for wslit, wschar in self.ws_map:
+ ret = ret.replace(wslit, wschar)
+
+ # replace escaped characters
+ if self.escChar:
+ ret = re.sub(self.escCharReplacePattern, r"\g<1>", ret)
+
+ # replace escaped quotes
+ if self.escQuote:
+ ret = ret.replace(self.escQuote, self.endQuoteChar)
+
+ return loc, ret
+
+
+class CharsNotIn(Token):
+ """Token for matching words composed of characters *not* in a given
+ set (will include whitespace in matched characters if not listed in
+ the provided exclusion set - see example). Defined with string
+ containing all disallowed characters, and an optional minimum,
+ maximum, and/or exact length. The default value for ``min`` is
+ 1 (a minimum value < 1 is not valid); the default values for
+ ``max`` and ``exact`` are 0, meaning no maximum or exact
+ length restriction.
+
+ Example::
+
+ # define a comma-separated-value as anything that is not a ','
+ csv_value = CharsNotIn(',')
+ print(delimited_list(csv_value).parse_string("dkls,lsdkjf,s12 34,@!#,213"))
+
+ prints::
+
+ ['dkls', 'lsdkjf', 's12 34', '@!#', '213']
+ """
+
+ def __init__(
+ self,
+ not_chars: str = "",
+ min: int = 1,
+ max: int = 0,
+ exact: int = 0,
+ *,
+ notChars: str = "",
+ ):
+ super().__init__()
+ self.skipWhitespace = False
+ self.notChars = not_chars or notChars
+ self.notCharsSet = set(self.notChars)
+
+ if min < 1:
+ raise ValueError(
+ "cannot specify a minimum length < 1; use "
+ "Opt(CharsNotIn()) if zero-length char group is permitted"
+ )
+
+ self.minLen = min
+
+ if max > 0:
+ self.maxLen = max
+ else:
+ self.maxLen = _MAX_INT
+
+ if exact > 0:
+ self.maxLen = exact
+ self.minLen = exact
+
+ self.errmsg = "Expected " + self.name
+ self.mayReturnEmpty = self.minLen == 0
+ self.mayIndexError = False
+
+ def _generateDefaultName(self):
+ not_chars_str = _collapse_string_to_ranges(self.notChars)
+ if len(not_chars_str) > 16:
+ return "!W:({}...)".format(self.notChars[: 16 - 3])
+ else:
+ return "!W:({})".format(self.notChars)
+
+ def parseImpl(self, instring, loc, doActions=True):
+ notchars = self.notCharsSet
+ if instring[loc] in notchars:
+ raise ParseException(instring, loc, self.errmsg, self)
+
+ start = loc
+ loc += 1
+ maxlen = min(start + self.maxLen, len(instring))
+ while loc < maxlen and instring[loc] not in notchars:
+ loc += 1
+
+ if loc - start < self.minLen:
+ raise ParseException(instring, loc, self.errmsg, self)
+
+ return loc, instring[start:loc]
+
+
+class White(Token):
+ """Special matching class for matching whitespace. Normally,
+ whitespace is ignored by pyparsing grammars. This class is included
+ when some whitespace structures are significant. Define with
+ a string containing the whitespace characters to be matched; default
+ is ``" \\t\\r\\n"``. Also takes optional ``min``,
+ ``max``, and ``exact`` arguments, as defined for the
+ :class:`Word` class.
+ """
+
+ whiteStrs = {
+ " ": "<SP>",
+ "\t": "<TAB>",
+ "\n": "<LF>",
+ "\r": "<CR>",
+ "\f": "<FF>",
+ "\u00A0": "<NBSP>",
+ "\u1680": "<OGHAM_SPACE_MARK>",
+ "\u180E": "<MONGOLIAN_VOWEL_SEPARATOR>",
+ "\u2000": "<EN_QUAD>",
+ "\u2001": "<EM_QUAD>",
+ "\u2002": "<EN_SPACE>",
+ "\u2003": "<EM_SPACE>",
+ "\u2004": "<THREE-PER-EM_SPACE>",
+ "\u2005": "<FOUR-PER-EM_SPACE>",
+ "\u2006": "<SIX-PER-EM_SPACE>",
+ "\u2007": "<FIGURE_SPACE>",
+ "\u2008": "<PUNCTUATION_SPACE>",
+ "\u2009": "<THIN_SPACE>",
+ "\u200A": "<HAIR_SPACE>",
+ "\u200B": "<ZERO_WIDTH_SPACE>",
+ "\u202F": "<NNBSP>",
+ "\u205F": "<MMSP>",
+ "\u3000": "<IDEOGRAPHIC_SPACE>",
+ }
+
+ def __init__(self, ws: str = " \t\r\n", min: int = 1, max: int = 0, exact: int = 0):
+ super().__init__()
+ self.matchWhite = ws
+ self.set_whitespace_chars(
+ "".join(c for c in self.whiteStrs if c not in self.matchWhite),
+ copy_defaults=True,
+ )
+ # self.leave_whitespace()
+ self.mayReturnEmpty = True
+ self.errmsg = "Expected " + self.name
+
+ self.minLen = min
+
+ if max > 0:
+ self.maxLen = max
+ else:
+ self.maxLen = _MAX_INT
+
+ if exact > 0:
+ self.maxLen = exact
+ self.minLen = exact
+
+ def _generateDefaultName(self):
+ return "".join(White.whiteStrs[c] for c in self.matchWhite)
+
+ def parseImpl(self, instring, loc, doActions=True):
+ if instring[loc] not in self.matchWhite:
+ raise ParseException(instring, loc, self.errmsg, self)
+ start = loc
+ loc += 1
+ maxloc = start + self.maxLen
+ maxloc = min(maxloc, len(instring))
+ while loc < maxloc and instring[loc] in self.matchWhite:
+ loc += 1
+
+ if loc - start < self.minLen:
+ raise ParseException(instring, loc, self.errmsg, self)
+
+ return loc, instring[start:loc]
+
+
+class PositionToken(Token):
+ def __init__(self):
+ super().__init__()
+ self.mayReturnEmpty = True
+ self.mayIndexError = False
+
+
+class GoToColumn(PositionToken):
+ """Token to advance to a specific column of input text; useful for
+ tabular report scraping.
+ """
+
+ def __init__(self, colno: int):
+ super().__init__()
+ self.col = colno
+
+ def preParse(self, instring, loc):
+ if col(loc, instring) != self.col:
+ instrlen = len(instring)
+ if self.ignoreExprs:
+ loc = self._skipIgnorables(instring, loc)
+ while (
+ loc < instrlen
+ and instring[loc].isspace()
+ and col(loc, instring) != self.col
+ ):
+ loc += 1
+ return loc
+
+ def parseImpl(self, instring, loc, doActions=True):
+ thiscol = col(loc, instring)
+ if thiscol > self.col:
+ raise ParseException(instring, loc, "Text not in expected column", self)
+ newloc = loc + self.col - thiscol
+ ret = instring[loc:newloc]
+ return newloc, ret
+
+
+class LineStart(PositionToken):
+ r"""Matches if current position is at the beginning of a line within
+ the parse string
+
+ Example::
+
+ test = '''\
+ AAA this line
+ AAA and this line
+ AAA but not this one
+ B AAA and definitely not this one
+ '''
+
+ for t in (LineStart() + 'AAA' + restOfLine).search_string(test):
+ print(t)
+
+ prints::
+
+ ['AAA', ' this line']
+ ['AAA', ' and this line']
+
+ """
+
+ def __init__(self):
+ super().__init__()
+ self.leave_whitespace()
+ self.orig_whiteChars = set() | self.whiteChars
+ self.whiteChars.discard("\n")
+ self.skipper = Empty().set_whitespace_chars(self.whiteChars)
+ self.errmsg = "Expected start of line"
+
+ def preParse(self, instring, loc):
+ if loc == 0:
+ return loc
+ else:
+ ret = self.skipper.preParse(instring, loc)
+ if "\n" in self.orig_whiteChars:
+ while instring[ret : ret + 1] == "\n":
+ ret = self.skipper.preParse(instring, ret + 1)
+ return ret
+
+ def parseImpl(self, instring, loc, doActions=True):
+ if col(loc, instring) == 1:
+ return loc, []
+ raise ParseException(instring, loc, self.errmsg, self)
+
+
+class LineEnd(PositionToken):
+ """Matches if current position is at the end of a line within the
+ parse string
+ """
+
+ def __init__(self):
+ super().__init__()
+ self.whiteChars.discard("\n")
+ self.set_whitespace_chars(self.whiteChars, copy_defaults=False)
+ self.errmsg = "Expected end of line"
+
+ def parseImpl(self, instring, loc, doActions=True):
+ if loc < len(instring):
+ if instring[loc] == "\n":
+ return loc + 1, "\n"
+ else:
+ raise ParseException(instring, loc, self.errmsg, self)
+ elif loc == len(instring):
+ return loc + 1, []
+ else:
+ raise ParseException(instring, loc, self.errmsg, self)
+
+
+class StringStart(PositionToken):
+ """Matches if current position is at the beginning of the parse
+ string
+ """
+
+ def __init__(self):
+ super().__init__()
+ self.errmsg = "Expected start of text"
+
+ def parseImpl(self, instring, loc, doActions=True):
+ if loc != 0:
+ # see if entire string up to here is just whitespace and ignoreables
+ if loc != self.preParse(instring, 0):
+ raise ParseException(instring, loc, self.errmsg, self)
+ return loc, []
+
+
+class StringEnd(PositionToken):
+ """
+ Matches if current position is at the end of the parse string
+ """
+
+ def __init__(self):
+ super().__init__()
+ self.errmsg = "Expected end of text"
+
+ def parseImpl(self, instring, loc, doActions=True):
+ if loc < len(instring):
+ raise ParseException(instring, loc, self.errmsg, self)
+ elif loc == len(instring):
+ return loc + 1, []
+ elif loc > len(instring):
+ return loc, []
+ else:
+ raise ParseException(instring, loc, self.errmsg, self)
+
+
+class WordStart(PositionToken):
+ """Matches if the current position is at the beginning of a
+ :class:`Word`, and is not preceded by any character in a given
+ set of ``word_chars`` (default= ``printables``). To emulate the
+ ``\b`` behavior of regular expressions, use
+ ``WordStart(alphanums)``. ``WordStart`` will also match at
+ the beginning of the string being parsed, or at the beginning of
+ a line.
+ """
+
+ def __init__(self, word_chars: str = printables, *, wordChars: str = printables):
+ wordChars = word_chars if wordChars == printables else wordChars
+ super().__init__()
+ self.wordChars = set(wordChars)
+ self.errmsg = "Not at the start of a word"
+
+ def parseImpl(self, instring, loc, doActions=True):
+ if loc != 0:
+ if (
+ instring[loc - 1] in self.wordChars
+ or instring[loc] not in self.wordChars
+ ):
+ raise ParseException(instring, loc, self.errmsg, self)
+ return loc, []
+
+
+class WordEnd(PositionToken):
+ """Matches if the current position is at the end of a :class:`Word`,
+ and is not followed by any character in a given set of ``word_chars``
+ (default= ``printables``). To emulate the ``\b`` behavior of
+ regular expressions, use ``WordEnd(alphanums)``. ``WordEnd``
+ will also match at the end of the string being parsed, or at the end
+ of a line.
+ """
+
+ def __init__(self, word_chars: str = printables, *, wordChars: str = printables):
+ wordChars = word_chars if wordChars == printables else wordChars
+ super().__init__()
+ self.wordChars = set(wordChars)
+ self.skipWhitespace = False
+ self.errmsg = "Not at the end of a word"
+
+ def parseImpl(self, instring, loc, doActions=True):
+ instrlen = len(instring)
+ if instrlen > 0 and loc < instrlen:
+ if (
+ instring[loc] in self.wordChars
+ or instring[loc - 1] not in self.wordChars
+ ):
+ raise ParseException(instring, loc, self.errmsg, self)
+ return loc, []
+
+
+class ParseExpression(ParserElement):
+ """Abstract subclass of ParserElement, for combining and
+ post-processing parsed tokens.
+ """
+
+ def __init__(self, exprs: IterableType[ParserElement], savelist: bool = False):
+ super().__init__(savelist)
+ self.exprs: List[ParserElement]
+ if isinstance(exprs, _generatorType):
+ exprs = list(exprs)
+
+ if isinstance(exprs, str_type):
+ self.exprs = [self._literalStringClass(exprs)]
+ elif isinstance(exprs, ParserElement):
+ self.exprs = [exprs]
+ elif isinstance(exprs, Iterable):
+ exprs = list(exprs)
+ # if sequence of strings provided, wrap with Literal
+ if any(isinstance(expr, str_type) for expr in exprs):
+ exprs = (
+ self._literalStringClass(e) if isinstance(e, str_type) else e
+ for e in exprs
+ )
+ self.exprs = list(exprs)
+ else:
+ try:
+ self.exprs = list(exprs)
+ except TypeError:
+ self.exprs = [exprs]
+ self.callPreparse = False
+
+ def recurse(self) -> Sequence[ParserElement]:
+ return self.exprs[:]
+
+ def append(self, other) -> ParserElement:
+ self.exprs.append(other)
+ self._defaultName = None
+ return self
+
+ def leave_whitespace(self, recursive: bool = True) -> ParserElement:
+ """
+ Extends ``leave_whitespace`` defined in base class, and also invokes ``leave_whitespace`` on
+ all contained expressions.
+ """
+ super().leave_whitespace(recursive)
+
+ if recursive:
+ self.exprs = [e.copy() for e in self.exprs]
+ for e in self.exprs:
+ e.leave_whitespace(recursive)
+ return self
+
+ def ignore_whitespace(self, recursive: bool = True) -> ParserElement:
+ """
+ Extends ``ignore_whitespace`` defined in base class, and also invokes ``leave_whitespace`` on
+ all contained expressions.
+ """
+ super().ignore_whitespace(recursive)
+ if recursive:
+ self.exprs = [e.copy() for e in self.exprs]
+ for e in self.exprs:
+ e.ignore_whitespace(recursive)
+ return self
+
+ def ignore(self, other) -> ParserElement:
+ if isinstance(other, Suppress):
+ if other not in self.ignoreExprs:
+ super().ignore(other)
+ for e in self.exprs:
+ e.ignore(self.ignoreExprs[-1])
+ else:
+ super().ignore(other)
+ for e in self.exprs:
+ e.ignore(self.ignoreExprs[-1])
+ return self
+
+ def _generateDefaultName(self):
+ return "{}:({})".format(self.__class__.__name__, str(self.exprs))
+
+ def streamline(self) -> ParserElement:
+ if self.streamlined:
+ return self
+
+ super().streamline()
+
+ for e in self.exprs:
+ e.streamline()
+
+ # collapse nested :class:`And`'s of the form ``And(And(And(a, b), c), d)`` to ``And(a, b, c, d)``
+ # but only if there are no parse actions or resultsNames on the nested And's
+ # (likewise for :class:`Or`'s and :class:`MatchFirst`'s)
+ if len(self.exprs) == 2:
+ other = self.exprs[0]
+ if (
+ isinstance(other, self.__class__)
+ and not other.parseAction
+ and other.resultsName is None
+ and not other.debug
+ ):
+ self.exprs = other.exprs[:] + [self.exprs[1]]
+ self._defaultName = None
+ self.mayReturnEmpty |= other.mayReturnEmpty
+ self.mayIndexError |= other.mayIndexError
+
+ other = self.exprs[-1]
+ if (
+ isinstance(other, self.__class__)
+ and not other.parseAction
+ and other.resultsName is None
+ and not other.debug
+ ):
+ self.exprs = self.exprs[:-1] + other.exprs[:]
+ self._defaultName = None
+ self.mayReturnEmpty |= other.mayReturnEmpty
+ self.mayIndexError |= other.mayIndexError
+
+ self.errmsg = "Expected " + str(self)
+
+ return self
+
+ def validate(self, validateTrace=None) -> None:
+ tmp = (validateTrace if validateTrace is not None else [])[:] + [self]
+ for e in self.exprs:
+ e.validate(tmp)
+ self._checkRecursion([])
+
+ def copy(self) -> ParserElement:
+ ret = super().copy()
+ ret.exprs = [e.copy() for e in self.exprs]
+ return ret
+
+ def _setResultsName(self, name, listAllMatches=False):
+ if (
+ __diag__.warn_ungrouped_named_tokens_in_collection
+ and Diagnostics.warn_ungrouped_named_tokens_in_collection
+ not in self.suppress_warnings_
+ ):
+ for e in self.exprs:
+ if (
+ isinstance(e, ParserElement)
+ and e.resultsName
+ and Diagnostics.warn_ungrouped_named_tokens_in_collection
+ not in e.suppress_warnings_
+ ):
+ warnings.warn(
+ "{}: setting results name {!r} on {} expression "
+ "collides with {!r} on contained expression".format(
+ "warn_ungrouped_named_tokens_in_collection",
+ name,
+ type(self).__name__,
+ e.resultsName,
+ ),
+ stacklevel=3,
+ )
+
+ return super()._setResultsName(name, listAllMatches)
+
+ ignoreWhitespace = ignore_whitespace
+ leaveWhitespace = leave_whitespace
+
+
+class And(ParseExpression):
+ """
+ Requires all given :class:`ParseExpression` s to be found in the given order.
+ Expressions may be separated by whitespace.
+ May be constructed using the ``'+'`` operator.
+ May also be constructed using the ``'-'`` operator, which will
+ suppress backtracking.
+
+ Example::
+
+ integer = Word(nums)
+ name_expr = OneOrMore(Word(alphas))
+
+ expr = And([integer("id"), name_expr("name"), integer("age")])
+ # more easily written as:
+ expr = integer("id") + name_expr("name") + integer("age")
+ """
+
+ class _ErrorStop(Empty):
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.leave_whitespace()
+
+ def _generateDefaultName(self):
+ return "-"
+
+ def __init__(self, exprs_arg: IterableType[ParserElement], savelist: bool = True):
+ exprs: List[ParserElement] = list(exprs_arg)
+ if exprs and Ellipsis in exprs:
+ tmp = []
+ for i, expr in enumerate(exprs):
+ if expr is Ellipsis:
+ if i < len(exprs) - 1:
+ skipto_arg: ParserElement = (Empty() + exprs[i + 1]).exprs[-1]
+ tmp.append(SkipTo(skipto_arg)("_skipped*"))
+ else:
+ raise Exception(
+ "cannot construct And with sequence ending in ..."
+ )
+ else:
+ tmp.append(expr)
+ exprs[:] = tmp
+ super().__init__(exprs, savelist)
+ if self.exprs:
+ self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs)
+ if not isinstance(self.exprs[0], White):
+ self.set_whitespace_chars(
+ self.exprs[0].whiteChars,
+ copy_defaults=self.exprs[0].copyDefaultWhiteChars,
+ )
+ self.skipWhitespace = self.exprs[0].skipWhitespace
+ else:
+ self.skipWhitespace = False
+ else:
+ self.mayReturnEmpty = True
+ self.callPreparse = True
+
+ def streamline(self) -> ParserElement:
+ # collapse any _PendingSkip's
+ if self.exprs:
+ if any(
+ isinstance(e, ParseExpression)
+ and e.exprs
+ and isinstance(e.exprs[-1], _PendingSkip)
+ for e in self.exprs[:-1]
+ ):
+ for i, e in enumerate(self.exprs[:-1]):
+ if e is None:
+ continue
+ if (
+ isinstance(e, ParseExpression)
+ and e.exprs
+ and isinstance(e.exprs[-1], _PendingSkip)
+ ):
+ e.exprs[-1] = e.exprs[-1] + self.exprs[i + 1]
+ self.exprs[i + 1] = None
+ self.exprs = [e for e in self.exprs if e is not None]
+
+ super().streamline()
+
+ # link any IndentedBlocks to the prior expression
+ for prev, cur in zip(self.exprs, self.exprs[1:]):
+ # traverse cur or any first embedded expr of cur looking for an IndentedBlock
+ # (but watch out for recursive grammar)
+ seen = set()
+ while cur:
+ if id(cur) in seen:
+ break
+ seen.add(id(cur))
+ if isinstance(cur, IndentedBlock):
+ prev.add_parse_action(
+ lambda s, l, t, cur_=cur: setattr(
+ cur_, "parent_anchor", col(l, s)
+ )
+ )
+ break
+ subs = cur.recurse()
+ cur = next(iter(subs), None)
+
+ self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs)
+ return self
+
+ def parseImpl(self, instring, loc, doActions=True):
+ # pass False as callPreParse arg to _parse for first element, since we already
+ # pre-parsed the string as part of our And pre-parsing
+ loc, resultlist = self.exprs[0]._parse(
+ instring, loc, doActions, callPreParse=False
+ )
+ errorStop = False
+ for e in self.exprs[1:]:
+ # if isinstance(e, And._ErrorStop):
+ if type(e) is And._ErrorStop:
+ errorStop = True
+ continue
+ if errorStop:
+ try:
+ loc, exprtokens = e._parse(instring, loc, doActions)
+ except ParseSyntaxException:
+ raise
+ except ParseBaseException as pe:
+ pe.__traceback__ = None
+ raise ParseSyntaxException._from_exception(pe)
+ except IndexError:
+ raise ParseSyntaxException(
+ instring, len(instring), self.errmsg, self
+ )
+ else:
+ loc, exprtokens = e._parse(instring, loc, doActions)
+ if exprtokens or exprtokens.haskeys():
+ resultlist += exprtokens
+ return loc, resultlist
+
+ def __iadd__(self, other):
+ if isinstance(other, str_type):
+ other = self._literalStringClass(other)
+ return self.append(other) # And([self, other])
+
+ def _checkRecursion(self, parseElementList):
+ subRecCheckList = parseElementList[:] + [self]
+ for e in self.exprs:
+ e._checkRecursion(subRecCheckList)
+ if not e.mayReturnEmpty:
+ break
+
+ def _generateDefaultName(self):
+ inner = " ".join(str(e) for e in self.exprs)
+ # strip off redundant inner {}'s
+ while len(inner) > 1 and inner[0 :: len(inner) - 1] == "{}":
+ inner = inner[1:-1]
+ return "{" + inner + "}"
+
+
+class Or(ParseExpression):
+ """Requires that at least one :class:`ParseExpression` is found. If
+ two expressions match, the expression that matches the longest
+ string will be used. May be constructed using the ``'^'``
+ operator.
+
+ Example::
+
+ # construct Or using '^' operator
+
+ number = Word(nums) ^ Combine(Word(nums) + '.' + Word(nums))
+ print(number.search_string("123 3.1416 789"))
+
+ prints::
+
+ [['123'], ['3.1416'], ['789']]
+ """
+
+ def __init__(self, exprs: IterableType[ParserElement], savelist: bool = False):
+ super().__init__(exprs, savelist)
+ if self.exprs:
+ self.mayReturnEmpty = any(e.mayReturnEmpty for e in self.exprs)
+ self.skipWhitespace = all(e.skipWhitespace for e in self.exprs)
+ else:
+ self.mayReturnEmpty = True
+
+ def streamline(self) -> ParserElement:
+ super().streamline()
+ if self.exprs:
+ self.mayReturnEmpty = any(e.mayReturnEmpty for e in self.exprs)
+ self.saveAsList = any(e.saveAsList for e in self.exprs)
+ self.skipWhitespace = all(
+ e.skipWhitespace and not isinstance(e, White) for e in self.exprs
+ )
+ else:
+ self.saveAsList = False
+ return self
+
+ def parseImpl(self, instring, loc, doActions=True):
+ maxExcLoc = -1
+ maxException = None
+ matches = []
+ fatals = []
+ if all(e.callPreparse for e in self.exprs):
+ loc = self.preParse(instring, loc)
+ for e in self.exprs:
+ try:
+ loc2 = e.try_parse(instring, loc, raise_fatal=True)
+ except ParseFatalException as pfe:
+ pfe.__traceback__ = None
+ pfe.parserElement = e
+ fatals.append(pfe)
+ maxException = None
+ maxExcLoc = -1
+ except ParseException as err:
+ if not fatals:
+ err.__traceback__ = None
+ if err.loc > maxExcLoc:
+ maxException = err
+ maxExcLoc = err.loc
+ except IndexError:
+ if len(instring) > maxExcLoc:
+ maxException = ParseException(
+ instring, len(instring), e.errmsg, self
+ )
+ maxExcLoc = len(instring)
+ else:
+ # save match among all matches, to retry longest to shortest
+ matches.append((loc2, e))
+
+ if matches:
+ # re-evaluate all matches in descending order of length of match, in case attached actions
+ # might change whether or how much they match of the input.
+ matches.sort(key=itemgetter(0), reverse=True)
+
+ if not doActions:
+ # no further conditions or parse actions to change the selection of
+ # alternative, so the first match will be the best match
+ best_expr = matches[0][1]
+ return best_expr._parse(instring, loc, doActions)
+
+ longest = -1, None
+ for loc1, expr1 in matches:
+ if loc1 <= longest[0]:
+ # already have a longer match than this one will deliver, we are done
+ return longest
+
+ try:
+ loc2, toks = expr1._parse(instring, loc, doActions)
+ except ParseException as err:
+ err.__traceback__ = None
+ if err.loc > maxExcLoc:
+ maxException = err
+ maxExcLoc = err.loc
+ else:
+ if loc2 >= loc1:
+ return loc2, toks
+ # didn't match as much as before
+ elif loc2 > longest[0]:
+ longest = loc2, toks
+
+ if longest != (-1, None):
+ return longest
+
+ if fatals:
+ if len(fatals) > 1:
+ fatals.sort(key=lambda e: -e.loc)
+ if fatals[0].loc == fatals[1].loc:
+ fatals.sort(key=lambda e: (-e.loc, -len(str(e.parserElement))))
+ max_fatal = fatals[0]
+ raise max_fatal
+
+ if maxException is not None:
+ maxException.msg = self.errmsg
+ raise maxException
+ else:
+ raise ParseException(
+ instring, loc, "no defined alternatives to match", self
+ )
+
+ def __ixor__(self, other):
+ if isinstance(other, str_type):
+ other = self._literalStringClass(other)
+ return self.append(other) # Or([self, other])
+
+ def _generateDefaultName(self):
+ return "{" + " ^ ".join(str(e) for e in self.exprs) + "}"
+
+ def _setResultsName(self, name, listAllMatches=False):
+ if (
+ __diag__.warn_multiple_tokens_in_named_alternation
+ and Diagnostics.warn_multiple_tokens_in_named_alternation
+ not in self.suppress_warnings_
+ ):
+ if any(
+ isinstance(e, And)
+ and Diagnostics.warn_multiple_tokens_in_named_alternation
+ not in e.suppress_warnings_
+ for e in self.exprs
+ ):
+ warnings.warn(
+ "{}: setting results name {!r} on {} expression "
+ "will return a list of all parsed tokens in an And alternative, "
+ "in prior versions only the first token was returned; enclose "
+ "contained argument in Group".format(
+ "warn_multiple_tokens_in_named_alternation",
+ name,
+ type(self).__name__,
+ ),
+ stacklevel=3,
+ )
+
+ return super()._setResultsName(name, listAllMatches)
+
+
+class MatchFirst(ParseExpression):
+ """Requires that at least one :class:`ParseExpression` is found. If
+ more than one expression matches, the first one listed is the one that will
+ match. May be constructed using the ``'|'`` operator.
+
+ Example::
+
+ # construct MatchFirst using '|' operator
+
+ # watch the order of expressions to match
+ number = Word(nums) | Combine(Word(nums) + '.' + Word(nums))
+ print(number.search_string("123 3.1416 789")) # Fail! -> [['123'], ['3'], ['1416'], ['789']]
+
+ # put more selective expression first
+ number = Combine(Word(nums) + '.' + Word(nums)) | Word(nums)
+ print(number.search_string("123 3.1416 789")) # Better -> [['123'], ['3.1416'], ['789']]
+ """
+
+ def __init__(self, exprs: IterableType[ParserElement], savelist: bool = False):
+ super().__init__(exprs, savelist)
+ if self.exprs:
+ self.mayReturnEmpty = any(e.mayReturnEmpty for e in self.exprs)
+ self.skipWhitespace = all(e.skipWhitespace for e in self.exprs)
+ else:
+ self.mayReturnEmpty = True
+
+ def streamline(self) -> ParserElement:
+ if self.streamlined:
+ return self
+
+ super().streamline()
+ if self.exprs:
+ self.saveAsList = any(e.saveAsList for e in self.exprs)
+ self.mayReturnEmpty = any(e.mayReturnEmpty for e in self.exprs)
+ self.skipWhitespace = all(
+ e.skipWhitespace and not isinstance(e, White) for e in self.exprs
+ )
+ else:
+ self.saveAsList = False
+ self.mayReturnEmpty = True
+ return self
+
+ def parseImpl(self, instring, loc, doActions=True):
+ maxExcLoc = -1
+ maxException = None
+
+ for e in self.exprs:
+ try:
+ return e._parse(
+ instring,
+ loc,
+ doActions,
+ )
+ except ParseFatalException as pfe:
+ pfe.__traceback__ = None
+ pfe.parserElement = e
+ raise
+ except ParseException as err:
+ if err.loc > maxExcLoc:
+ maxException = err
+ maxExcLoc = err.loc
+ except IndexError:
+ if len(instring) > maxExcLoc:
+ maxException = ParseException(
+ instring, len(instring), e.errmsg, self
+ )
+ maxExcLoc = len(instring)
+
+ if maxException is not None:
+ maxException.msg = self.errmsg
+ raise maxException
+ else:
+ raise ParseException(
+ instring, loc, "no defined alternatives to match", self
+ )
+
+ def __ior__(self, other):
+ if isinstance(other, str_type):
+ other = self._literalStringClass(other)
+ return self.append(other) # MatchFirst([self, other])
+
+ def _generateDefaultName(self):
+ return "{" + " | ".join(str(e) for e in self.exprs) + "}"
+
+ def _setResultsName(self, name, listAllMatches=False):
+ if (
+ __diag__.warn_multiple_tokens_in_named_alternation
+ and Diagnostics.warn_multiple_tokens_in_named_alternation
+ not in self.suppress_warnings_
+ ):
+ if any(
+ isinstance(e, And)
+ and Diagnostics.warn_multiple_tokens_in_named_alternation
+ not in e.suppress_warnings_
+ for e in self.exprs
+ ):
+ warnings.warn(
+ "{}: setting results name {!r} on {} expression "
+ "will return a list of all parsed tokens in an And alternative, "
+ "in prior versions only the first token was returned; enclose "
+ "contained argument in Group".format(
+ "warn_multiple_tokens_in_named_alternation",
+ name,
+ type(self).__name__,
+ ),
+ stacklevel=3,
+ )
+
+ return super()._setResultsName(name, listAllMatches)
+
+
+class Each(ParseExpression):
+ """Requires all given :class:`ParseExpression` s to be found, but in
+ any order. Expressions may be separated by whitespace.
+
+ May be constructed using the ``'&'`` operator.
+
+ Example::
+
+ color = one_of("RED ORANGE YELLOW GREEN BLUE PURPLE BLACK WHITE BROWN")
+ shape_type = one_of("SQUARE CIRCLE TRIANGLE STAR HEXAGON OCTAGON")
+ integer = Word(nums)
+ shape_attr = "shape:" + shape_type("shape")
+ posn_attr = "posn:" + Group(integer("x") + ',' + integer("y"))("posn")
+ color_attr = "color:" + color("color")
+ size_attr = "size:" + integer("size")
+
+ # use Each (using operator '&') to accept attributes in any order
+ # (shape and posn are required, color and size are optional)
+ shape_spec = shape_attr & posn_attr & Opt(color_attr) & Opt(size_attr)
+
+ shape_spec.run_tests('''
+ shape: SQUARE color: BLACK posn: 100, 120
+ shape: CIRCLE size: 50 color: BLUE posn: 50,80
+ color:GREEN size:20 shape:TRIANGLE posn:20,40
+ '''
+ )
+
+ prints::
+
+ shape: SQUARE color: BLACK posn: 100, 120
+ ['shape:', 'SQUARE', 'color:', 'BLACK', 'posn:', ['100', ',', '120']]
+ - color: BLACK
+ - posn: ['100', ',', '120']
+ - x: 100
+ - y: 120
+ - shape: SQUARE
+
+
+ shape: CIRCLE size: 50 color: BLUE posn: 50,80
+ ['shape:', 'CIRCLE', 'size:', '50', 'color:', 'BLUE', 'posn:', ['50', ',', '80']]
+ - color: BLUE
+ - posn: ['50', ',', '80']
+ - x: 50
+ - y: 80
+ - shape: CIRCLE
+ - size: 50
+
+
+ color: GREEN size: 20 shape: TRIANGLE posn: 20,40
+ ['color:', 'GREEN', 'size:', '20', 'shape:', 'TRIANGLE', 'posn:', ['20', ',', '40']]
+ - color: GREEN
+ - posn: ['20', ',', '40']
+ - x: 20
+ - y: 40
+ - shape: TRIANGLE
+ - size: 20
+ """
+
+ def __init__(self, exprs: IterableType[ParserElement], savelist: bool = True):
+ super().__init__(exprs, savelist)
+ if self.exprs:
+ self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs)
+ else:
+ self.mayReturnEmpty = True
+ self.skipWhitespace = True
+ self.initExprGroups = True
+ self.saveAsList = True
+
+ def streamline(self) -> ParserElement:
+ super().streamline()
+ if self.exprs:
+ self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs)
+ else:
+ self.mayReturnEmpty = True
+ return self
+
+ def parseImpl(self, instring, loc, doActions=True):
+ if self.initExprGroups:
+ self.opt1map = dict(
+ (id(e.expr), e) for e in self.exprs if isinstance(e, Opt)
+ )
+ opt1 = [e.expr for e in self.exprs if isinstance(e, Opt)]
+ opt2 = [
+ e
+ for e in self.exprs
+ if e.mayReturnEmpty and not isinstance(e, (Opt, Regex, ZeroOrMore))
+ ]
+ self.optionals = opt1 + opt2
+ self.multioptionals = [
+ e.expr.set_results_name(e.resultsName, list_all_matches=True)
+ for e in self.exprs
+ if isinstance(e, _MultipleMatch)
+ ]
+ self.multirequired = [
+ e.expr.set_results_name(e.resultsName, list_all_matches=True)
+ for e in self.exprs
+ if isinstance(e, OneOrMore)
+ ]
+ self.required = [
+ e for e in self.exprs if not isinstance(e, (Opt, ZeroOrMore, OneOrMore))
+ ]
+ self.required += self.multirequired
+ self.initExprGroups = False
+
+ tmpLoc = loc
+ tmpReqd = self.required[:]
+ tmpOpt = self.optionals[:]
+ multis = self.multioptionals[:]
+ matchOrder = []
+
+ keepMatching = True
+ failed = []
+ fatals = []
+ while keepMatching:
+ tmpExprs = tmpReqd + tmpOpt + multis
+ failed.clear()
+ fatals.clear()
+ for e in tmpExprs:
+ try:
+ tmpLoc = e.try_parse(instring, tmpLoc, raise_fatal=True)
+ except ParseFatalException as pfe:
+ pfe.__traceback__ = None
+ pfe.parserElement = e
+ fatals.append(pfe)
+ failed.append(e)
+ except ParseException:
+ failed.append(e)
+ else:
+ matchOrder.append(self.opt1map.get(id(e), e))
+ if e in tmpReqd:
+ tmpReqd.remove(e)
+ elif e in tmpOpt:
+ tmpOpt.remove(e)
+ if len(failed) == len(tmpExprs):
+ keepMatching = False
+
+ # look for any ParseFatalExceptions
+ if fatals:
+ if len(fatals) > 1:
+ fatals.sort(key=lambda e: -e.loc)
+ if fatals[0].loc == fatals[1].loc:
+ fatals.sort(key=lambda e: (-e.loc, -len(str(e.parserElement))))
+ max_fatal = fatals[0]
+ raise max_fatal
+
+ if tmpReqd:
+ missing = ", ".join([str(e) for e in tmpReqd])
+ raise ParseException(
+ instring,
+ loc,
+ "Missing one or more required elements ({})".format(missing),
+ )
+
+ # add any unmatched Opts, in case they have default values defined
+ matchOrder += [e for e in self.exprs if isinstance(e, Opt) and e.expr in tmpOpt]
+
+ total_results = ParseResults([])
+ for e in matchOrder:
+ loc, results = e._parse(instring, loc, doActions)
+ total_results += results
+
+ return loc, total_results
+
+ def _generateDefaultName(self):
+ return "{" + " & ".join(str(e) for e in self.exprs) + "}"
+
+
+class ParseElementEnhance(ParserElement):
+ """Abstract subclass of :class:`ParserElement`, for combining and
+ post-processing parsed tokens.
+ """
+
+ def __init__(self, expr: Union[ParserElement, str], savelist: bool = False):
+ super().__init__(savelist)
+ if isinstance(expr, str_type):
+ if issubclass(self._literalStringClass, Token):
+ expr = self._literalStringClass(expr)
+ elif issubclass(type(self), self._literalStringClass):
+ expr = Literal(expr)
+ else:
+ expr = self._literalStringClass(Literal(expr))
+ self.expr = expr
+ if expr is not None:
+ self.mayIndexError = expr.mayIndexError
+ self.mayReturnEmpty = expr.mayReturnEmpty
+ self.set_whitespace_chars(
+ expr.whiteChars, copy_defaults=expr.copyDefaultWhiteChars
+ )
+ self.skipWhitespace = expr.skipWhitespace
+ self.saveAsList = expr.saveAsList
+ self.callPreparse = expr.callPreparse
+ self.ignoreExprs.extend(expr.ignoreExprs)
+
+ def recurse(self) -> Sequence[ParserElement]:
+ return [self.expr] if self.expr is not None else []
+
+ def parseImpl(self, instring, loc, doActions=True):
+ if self.expr is not None:
+ return self.expr._parse(instring, loc, doActions, callPreParse=False)
+ else:
+ raise ParseException(instring, loc, "No expression defined", self)
+
+ def leave_whitespace(self, recursive: bool = True) -> ParserElement:
+ super().leave_whitespace(recursive)
+
+ if recursive:
+ self.expr = self.expr.copy()
+ if self.expr is not None:
+ self.expr.leave_whitespace(recursive)
+ return self
+
+ def ignore_whitespace(self, recursive: bool = True) -> ParserElement:
+ super().ignore_whitespace(recursive)
+
+ if recursive:
+ self.expr = self.expr.copy()
+ if self.expr is not None:
+ self.expr.ignore_whitespace(recursive)
+ return self
+
+ def ignore(self, other) -> ParserElement:
+ if isinstance(other, Suppress):
+ if other not in self.ignoreExprs:
+ super().ignore(other)
+ if self.expr is not None:
+ self.expr.ignore(self.ignoreExprs[-1])
+ else:
+ super().ignore(other)
+ if self.expr is not None:
+ self.expr.ignore(self.ignoreExprs[-1])
+ return self
+
+ def streamline(self) -> ParserElement:
+ super().streamline()
+ if self.expr is not None:
+ self.expr.streamline()
+ return self
+
+ def _checkRecursion(self, parseElementList):
+ if self in parseElementList:
+ raise RecursiveGrammarException(parseElementList + [self])
+ subRecCheckList = parseElementList[:] + [self]
+ if self.expr is not None:
+ self.expr._checkRecursion(subRecCheckList)
+
+ def validate(self, validateTrace=None) -> None:
+ if validateTrace is None:
+ validateTrace = []
+ tmp = validateTrace[:] + [self]
+ if self.expr is not None:
+ self.expr.validate(tmp)
+ self._checkRecursion([])
+
+ def _generateDefaultName(self):
+ return "{}:({})".format(self.__class__.__name__, str(self.expr))
+
+ ignoreWhitespace = ignore_whitespace
+ leaveWhitespace = leave_whitespace
+
+
+class IndentedBlock(ParseElementEnhance):
+ """
+ Expression to match one or more expressions at a given indentation level.
+ Useful for parsing text where structure is implied by indentation (like Python source code).
+ """
+
+ class _Indent(Empty):
+ def __init__(self, ref_col: int):
+ super().__init__()
+ self.errmsg = "expected indent at column {}".format(ref_col)
+ self.add_condition(lambda s, l, t: col(l, s) == ref_col)
+
+ class _IndentGreater(Empty):
+ def __init__(self, ref_col: int):
+ super().__init__()
+ self.errmsg = "expected indent at column greater than {}".format(ref_col)
+ self.add_condition(lambda s, l, t: col(l, s) > ref_col)
+
+ def __init__(
+ self, expr: ParserElement, *, recursive: bool = False, grouped: bool = True
+ ):
+ super().__init__(expr, savelist=True)
+ # if recursive:
+ # raise NotImplementedError("IndentedBlock with recursive is not implemented")
+ self._recursive = recursive
+ self._grouped = grouped
+ self.parent_anchor = 1
+
+ def parseImpl(self, instring, loc, doActions=True):
+ # advance parse position to non-whitespace by using an Empty()
+ # this should be the column to be used for all subsequent indented lines
+ anchor_loc = Empty().preParse(instring, loc)
+
+ # see if self.expr matches at the current location - if not it will raise an exception
+ # and no further work is necessary
+ self.expr.try_parse(instring, anchor_loc, doActions)
+
+ indent_col = col(anchor_loc, instring)
+ peer_detect_expr = self._Indent(indent_col)
+
+ inner_expr = Empty() + peer_detect_expr + self.expr
+ if self._recursive:
+ sub_indent = self._IndentGreater(indent_col)
+ nested_block = IndentedBlock(
+ self.expr, recursive=self._recursive, grouped=self._grouped
+ )
+ nested_block.set_debug(self.debug)
+ nested_block.parent_anchor = indent_col
+ inner_expr += Opt(sub_indent + nested_block)
+
+ inner_expr.set_name(f"inner {hex(id(inner_expr))[-4:].upper()}@{indent_col}")
+ block = OneOrMore(inner_expr)
+
+ trailing_undent = self._Indent(self.parent_anchor) | StringEnd()
+
+ if self._grouped:
+ wrapper = Group
+ else:
+ wrapper = lambda expr: expr
+ return (wrapper(block) + Optional(trailing_undent)).parseImpl(
+ instring, anchor_loc, doActions
+ )
+
+
+class AtStringStart(ParseElementEnhance):
+ """Matches if expression matches at the beginning of the parse
+ string::
+
+ AtStringStart(Word(nums)).parse_string("123")
+ # prints ["123"]
+
+ AtStringStart(Word(nums)).parse_string(" 123")
+ # raises ParseException
+ """
+
+ def __init__(self, expr: Union[ParserElement, str]):
+ super().__init__(expr)
+ self.callPreparse = False
+
+ def parseImpl(self, instring, loc, doActions=True):
+ if loc != 0:
+ raise ParseException(instring, loc, "not found at string start")
+ return super().parseImpl(instring, loc, doActions)
+
+
+class AtLineStart(ParseElementEnhance):
+ r"""Matches if an expression matches at the beginning of a line within
+ the parse string
+
+ Example::
+
+ test = '''\
+ AAA this line
+ AAA and this line
+ AAA but not this one
+ B AAA and definitely not this one
+ '''
+
+ for t in (AtLineStart('AAA') + restOfLine).search_string(test):
+ print(t)
+
+ prints::
+
+ ['AAA', ' this line']
+ ['AAA', ' and this line']
+
+ """
+
+ def __init__(self, expr: Union[ParserElement, str]):
+ super().__init__(expr)
+ self.callPreparse = False
+
+ def parseImpl(self, instring, loc, doActions=True):
+ if col(loc, instring) != 1:
+ raise ParseException(instring, loc, "not found at line start")
+ return super().parseImpl(instring, loc, doActions)
+
+
+class FollowedBy(ParseElementEnhance):
+ """Lookahead matching of the given parse expression.
+ ``FollowedBy`` does *not* advance the parsing position within
+ the input string, it only verifies that the specified parse
+ expression matches at the current position. ``FollowedBy``
+ always returns a null token list. If any results names are defined
+ in the lookahead expression, those *will* be returned for access by
+ name.
+
+ Example::
+
+ # use FollowedBy to match a label only if it is followed by a ':'
+ data_word = Word(alphas)
+ label = data_word + FollowedBy(':')
+ attr_expr = Group(label + Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join))
+
+ OneOrMore(attr_expr).parse_string("shape: SQUARE color: BLACK posn: upper left").pprint()
+
+ prints::
+
+ [['shape', 'SQUARE'], ['color', 'BLACK'], ['posn', 'upper left']]
+ """
+
+ def __init__(self, expr: Union[ParserElement, str]):
+ super().__init__(expr)
+ self.mayReturnEmpty = True
+
+ def parseImpl(self, instring, loc, doActions=True):
+ # by using self._expr.parse and deleting the contents of the returned ParseResults list
+ # we keep any named results that were defined in the FollowedBy expression
+ _, ret = self.expr._parse(instring, loc, doActions=doActions)
+ del ret[:]
+
+ return loc, ret
+
+
+class PrecededBy(ParseElementEnhance):
+ """Lookbehind matching of the given parse expression.
+ ``PrecededBy`` does not advance the parsing position within the
+ input string, it only verifies that the specified parse expression
+ matches prior to the current position. ``PrecededBy`` always
+ returns a null token list, but if a results name is defined on the
+ given expression, it is returned.
+
+ Parameters:
+
+ - expr - expression that must match prior to the current parse
+ location
+ - retreat - (default= ``None``) - (int) maximum number of characters
+ to lookbehind prior to the current parse location
+
+ If the lookbehind expression is a string, :class:`Literal`,
+ :class:`Keyword`, or a :class:`Word` or :class:`CharsNotIn`
+ with a specified exact or maximum length, then the retreat
+ parameter is not required. Otherwise, retreat must be specified to
+ give a maximum number of characters to look back from
+ the current parse position for a lookbehind match.
+
+ Example::
+
+ # VB-style variable names with type prefixes
+ int_var = PrecededBy("#") + pyparsing_common.identifier
+ str_var = PrecededBy("$") + pyparsing_common.identifier
+
+ """
+
+ def __init__(
+ self, expr: Union[ParserElement, str], retreat: OptionalType[int] = None
+ ):
+ super().__init__(expr)
+ self.expr = self.expr().leave_whitespace()
+ self.mayReturnEmpty = True
+ self.mayIndexError = False
+ self.exact = False
+ if isinstance(expr, str_type):
+ retreat = len(expr)
+ self.exact = True
+ elif isinstance(expr, (Literal, Keyword)):
+ retreat = expr.matchLen
+ self.exact = True
+ elif isinstance(expr, (Word, CharsNotIn)) and expr.maxLen != _MAX_INT:
+ retreat = expr.maxLen
+ self.exact = True
+ elif isinstance(expr, PositionToken):
+ retreat = 0
+ self.exact = True
+ self.retreat = retreat
+ self.errmsg = "not preceded by " + str(expr)
+ self.skipWhitespace = False
+ self.parseAction.append(lambda s, l, t: t.__delitem__(slice(None, None)))
+
+ def parseImpl(self, instring, loc=0, doActions=True):
+ if self.exact:
+ if loc < self.retreat:
+ raise ParseException(instring, loc, self.errmsg)
+ start = loc - self.retreat
+ _, ret = self.expr._parse(instring, start)
+ else:
+ # retreat specified a maximum lookbehind window, iterate
+ test_expr = self.expr + StringEnd()
+ instring_slice = instring[max(0, loc - self.retreat) : loc]
+ last_expr = ParseException(instring, loc, self.errmsg)
+ for offset in range(1, min(loc, self.retreat + 1) + 1):
+ try:
+ # print('trying', offset, instring_slice, repr(instring_slice[loc - offset:]))
+ _, ret = test_expr._parse(
+ instring_slice, len(instring_slice) - offset
+ )
+ except ParseBaseException as pbe:
+ last_expr = pbe
+ else:
+ break
+ else:
+ raise last_expr
+ return loc, ret
+
+
+class Located(ParseElementEnhance):
+ """
+ Decorates a returned token with its starting and ending
+ locations in the input string.
+
+ This helper adds the following results names:
+
+ - ``locn_start`` - location where matched expression begins
+ - ``locn_end`` - location where matched expression ends
+ - ``value`` - the actual parsed results
+
+ Be careful if the input text contains ``<TAB>`` characters, you
+ may want to call :class:`ParserElement.parse_with_tabs`
+
+ Example::
+
+ wd = Word(alphas)
+ for match in Located(wd).search_string("ljsdf123lksdjjf123lkkjj1222"):
+ print(match)
+
+ prints::
+
+ [0, ['ljsdf'], 5]
+ [8, ['lksdjjf'], 15]
+ [18, ['lkkjj'], 23]
+
+ """
+
+ def parseImpl(self, instring, loc, doActions=True):
+ start = loc
+ loc, tokens = self.expr._parse(instring, start, doActions, callPreParse=False)
+ ret_tokens = ParseResults([start, tokens, loc])
+ ret_tokens["locn_start"] = start
+ ret_tokens["value"] = tokens
+ ret_tokens["locn_end"] = loc
+ if self.resultsName:
+ # must return as a list, so that the name will be attached to the complete group
+ return loc, [ret_tokens]
+ else:
+ return loc, ret_tokens
+
+
+class NotAny(ParseElementEnhance):
+ """
+ Lookahead to disallow matching with the given parse expression.
+ ``NotAny`` does *not* advance the parsing position within the
+ input string, it only verifies that the specified parse expression
+ does *not* match at the current position. Also, ``NotAny`` does
+ *not* skip over leading whitespace. ``NotAny`` always returns
+ a null token list. May be constructed using the ``'~'`` operator.
+
+ Example::
+
+ AND, OR, NOT = map(CaselessKeyword, "AND OR NOT".split())
+
+ # take care not to mistake keywords for identifiers
+ ident = ~(AND | OR | NOT) + Word(alphas)
+ boolean_term = Opt(NOT) + ident
+
+ # very crude boolean expression - to support parenthesis groups and
+ # operation hierarchy, use infix_notation
+ boolean_expr = boolean_term + ZeroOrMore((AND | OR) + boolean_term)
+
+ # integers that are followed by "." are actually floats
+ integer = Word(nums) + ~Char(".")
+ """
+
+ def __init__(self, expr: Union[ParserElement, str]):
+ super().__init__(expr)
+ # do NOT use self.leave_whitespace(), don't want to propagate to exprs
+ # self.leave_whitespace()
+ self.skipWhitespace = False
+
+ self.mayReturnEmpty = True
+ self.errmsg = "Found unwanted token, " + str(self.expr)
+
+ def parseImpl(self, instring, loc, doActions=True):
+ if self.expr.can_parse_next(instring, loc):
+ raise ParseException(instring, loc, self.errmsg, self)
+ return loc, []
+
+ def _generateDefaultName(self):
+ return "~{" + str(self.expr) + "}"
+
+
+class _MultipleMatch(ParseElementEnhance):
+ def __init__(
+ self,
+ expr: ParserElement,
+ stop_on: OptionalType[Union[ParserElement, str]] = None,
+ *,
+ stopOn: OptionalType[Union[ParserElement, str]] = None,
+ ):
+ super().__init__(expr)
+ stopOn = stopOn or stop_on
+ self.saveAsList = True
+ ender = stopOn
+ if isinstance(ender, str_type):
+ ender = self._literalStringClass(ender)
+ self.stopOn(ender)
+
+ def stopOn(self, ender) -> ParserElement:
+ if isinstance(ender, str_type):
+ ender = self._literalStringClass(ender)
+ self.not_ender = ~ender if ender is not None else None
+ return self
+
+ def parseImpl(self, instring, loc, doActions=True):
+ self_expr_parse = self.expr._parse
+ self_skip_ignorables = self._skipIgnorables
+ check_ender = self.not_ender is not None
+ if check_ender:
+ try_not_ender = self.not_ender.tryParse
+
+ # must be at least one (but first see if we are the stopOn sentinel;
+ # if so, fail)
+ if check_ender:
+ try_not_ender(instring, loc)
+ loc, tokens = self_expr_parse(instring, loc, doActions)
+ try:
+ hasIgnoreExprs = not not self.ignoreExprs
+ while 1:
+ if check_ender:
+ try_not_ender(instring, loc)
+ if hasIgnoreExprs:
+ preloc = self_skip_ignorables(instring, loc)
+ else:
+ preloc = loc
+ loc, tmptokens = self_expr_parse(instring, preloc, doActions)
+ if tmptokens or tmptokens.haskeys():
+ tokens += tmptokens
+ except (ParseException, IndexError):
+ pass
+
+ return loc, tokens
+
+ def _setResultsName(self, name, listAllMatches=False):
+ if (
+ __diag__.warn_ungrouped_named_tokens_in_collection
+ and Diagnostics.warn_ungrouped_named_tokens_in_collection
+ not in self.suppress_warnings_
+ ):
+ for e in [self.expr] + self.expr.recurse():
+ if (
+ isinstance(e, ParserElement)
+ and e.resultsName
+ and Diagnostics.warn_ungrouped_named_tokens_in_collection
+ not in e.suppress_warnings_
+ ):
+ warnings.warn(
+ "{}: setting results name {!r} on {} expression "
+ "collides with {!r} on contained expression".format(
+ "warn_ungrouped_named_tokens_in_collection",
+ name,
+ type(self).__name__,
+ e.resultsName,
+ ),
+ stacklevel=3,
+ )
+
+ return super()._setResultsName(name, listAllMatches)
+
+
+class OneOrMore(_MultipleMatch):
+ """
+ Repetition of one or more of the given expression.
+
+ Parameters:
+ - expr - expression that must match one or more times
+ - stop_on - (default= ``None``) - expression for a terminating sentinel
+ (only required if the sentinel would ordinarily match the repetition
+ expression)
+
+ Example::
+
+ data_word = Word(alphas)
+ label = data_word + FollowedBy(':')
+ attr_expr = Group(label + Suppress(':') + OneOrMore(data_word).set_parse_action(' '.join))
+
+ text = "shape: SQUARE posn: upper left color: BLACK"
+ OneOrMore(attr_expr).parse_string(text).pprint() # Fail! read 'color' as data instead of next label -> [['shape', 'SQUARE color']]
+
+ # use stop_on attribute for OneOrMore to avoid reading label string as part of the data
+ attr_expr = Group(label + Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join))
+ OneOrMore(attr_expr).parse_string(text).pprint() # Better -> [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'BLACK']]
+
+ # could also be written as
+ (attr_expr * (1,)).parse_string(text).pprint()
+ """
+
+ def _generateDefaultName(self):
+ return "{" + str(self.expr) + "}..."
+
+
+class ZeroOrMore(_MultipleMatch):
+ """
+ Optional repetition of zero or more of the given expression.
+
+ Parameters:
+ - ``expr`` - expression that must match zero or more times
+ - ``stop_on`` - expression for a terminating sentinel
+ (only required if the sentinel would ordinarily match the repetition
+ expression) - (default= ``None``)
+
+ Example: similar to :class:`OneOrMore`
+ """
+
+ def __init__(
+ self,
+ expr: ParserElement,
+ stop_on: OptionalType[Union[ParserElement, str]] = None,
+ *,
+ stopOn: OptionalType[Union[ParserElement, str]] = None,
+ ):
+ super().__init__(expr, stopOn=stopOn or stop_on)
+ self.mayReturnEmpty = True
+
+ def parseImpl(self, instring, loc, doActions=True):
+ try:
+ return super().parseImpl(instring, loc, doActions)
+ except (ParseException, IndexError):
+ return loc, ParseResults([], name=self.resultsName)
+
+ def _generateDefaultName(self):
+ return "[" + str(self.expr) + "]..."
+
+
+class _NullToken:
+ def __bool__(self):
+ return False
+
+ def __str__(self):
+ return ""
+
+
+class Opt(ParseElementEnhance):
+ """
+ Optional matching of the given expression.
+
+ Parameters:
+ - ``expr`` - expression that must match zero or more times
+ - ``default`` (optional) - value to be returned if the optional expression is not found.
+
+ Example::
+
+ # US postal code can be a 5-digit zip, plus optional 4-digit qualifier
+ zip = Combine(Word(nums, exact=5) + Opt('-' + Word(nums, exact=4)))
+ zip.run_tests('''
+ # traditional ZIP code
+ 12345
+
+ # ZIP+4 form
+ 12101-0001
+
+ # invalid ZIP
+ 98765-
+ ''')
+
+ prints::
+
+ # traditional ZIP code
+ 12345
+ ['12345']
+
+ # ZIP+4 form
+ 12101-0001
+ ['12101-0001']
+
+ # invalid ZIP
+ 98765-
+ ^
+ FAIL: Expected end of text (at char 5), (line:1, col:6)
+ """
+
+ __optionalNotMatched = _NullToken()
+
+ def __init__(
+ self, expr: Union[ParserElement, str], default: Any = __optionalNotMatched
+ ):
+ super().__init__(expr, savelist=False)
+ self.saveAsList = self.expr.saveAsList
+ self.defaultValue = default
+ self.mayReturnEmpty = True
+
+ def parseImpl(self, instring, loc, doActions=True):
+ self_expr = self.expr
+ try:
+ loc, tokens = self_expr._parse(instring, loc, doActions, callPreParse=False)
+ except (ParseException, IndexError):
+ default_value = self.defaultValue
+ if default_value is not self.__optionalNotMatched:
+ if self_expr.resultsName:
+ tokens = ParseResults([default_value])
+ tokens[self_expr.resultsName] = default_value
+ else:
+ tokens = [default_value]
+ else:
+ tokens = []
+ return loc, tokens
+
+ def _generateDefaultName(self):
+ inner = str(self.expr)
+ # strip off redundant inner {}'s
+ while len(inner) > 1 and inner[0 :: len(inner) - 1] == "{}":
+ inner = inner[1:-1]
+ return "[" + inner + "]"
+
+
+Optional = Opt
+
+
+class SkipTo(ParseElementEnhance):
+ """
+ Token for skipping over all undefined text until the matched
+ expression is found.
+
+ Parameters:
+ - ``expr`` - target expression marking the end of the data to be skipped
+ - ``include`` - if ``True``, the target expression is also parsed
+ (the skipped text and target expression are returned as a 2-element
+ list) (default= ``False``).
+ - ``ignore`` - (default= ``None``) used to define grammars (typically quoted strings and
+ comments) that might contain false matches to the target expression
+ - ``fail_on`` - (default= ``None``) define expressions that are not allowed to be
+ included in the skipped test; if found before the target expression is found,
+ the :class:`SkipTo` is not a match
+
+ Example::
+
+ report = '''
+ Outstanding Issues Report - 1 Jan 2000
+
+ # | Severity | Description | Days Open
+ -----+----------+-------------------------------------------+-----------
+ 101 | Critical | Intermittent system crash | 6
+ 94 | Cosmetic | Spelling error on Login ('log|n') | 14
+ 79 | Minor | System slow when running too many reports | 47
+ '''
+ integer = Word(nums)
+ SEP = Suppress('|')
+ # use SkipTo to simply match everything up until the next SEP
+ # - ignore quoted strings, so that a '|' character inside a quoted string does not match
+ # - parse action will call token.strip() for each matched token, i.e., the description body
+ string_data = SkipTo(SEP, ignore=quoted_string)
+ string_data.set_parse_action(token_map(str.strip))
+ ticket_expr = (integer("issue_num") + SEP
+ + string_data("sev") + SEP
+ + string_data("desc") + SEP
+ + integer("days_open"))
+
+ for tkt in ticket_expr.search_string(report):
+ print tkt.dump()
+
+ prints::
+
+ ['101', 'Critical', 'Intermittent system crash', '6']
+ - days_open: '6'
+ - desc: 'Intermittent system crash'
+ - issue_num: '101'
+ - sev: 'Critical'
+ ['94', 'Cosmetic', "Spelling error on Login ('log|n')", '14']
+ - days_open: '14'
+ - desc: "Spelling error on Login ('log|n')"
+ - issue_num: '94'
+ - sev: 'Cosmetic'
+ ['79', 'Minor', 'System slow when running too many reports', '47']
+ - days_open: '47'
+ - desc: 'System slow when running too many reports'
+ - issue_num: '79'
+ - sev: 'Minor'
+ """
+
+ def __init__(
+ self,
+ other: Union[ParserElement, str],
+ include: bool = False,
+ ignore: bool = None,
+ fail_on: OptionalType[Union[ParserElement, str]] = None,
+ *,
+ failOn: Union[ParserElement, str] = None,
+ ):
+ super().__init__(other)
+ failOn = failOn or fail_on
+ self.ignoreExpr = ignore
+ self.mayReturnEmpty = True
+ self.mayIndexError = False
+ self.includeMatch = include
+ self.saveAsList = False
+ if isinstance(failOn, str_type):
+ self.failOn = self._literalStringClass(failOn)
+ else:
+ self.failOn = failOn
+ self.errmsg = "No match found for " + str(self.expr)
+
+ def parseImpl(self, instring, loc, doActions=True):
+ startloc = loc
+ instrlen = len(instring)
+ self_expr_parse = self.expr._parse
+ self_failOn_canParseNext = (
+ self.failOn.canParseNext if self.failOn is not None else None
+ )
+ self_ignoreExpr_tryParse = (
+ self.ignoreExpr.tryParse if self.ignoreExpr is not None else None
+ )
+
+ tmploc = loc
+ while tmploc <= instrlen:
+ if self_failOn_canParseNext is not None:
+ # break if failOn expression matches
+ if self_failOn_canParseNext(instring, tmploc):
+ break
+
+ if self_ignoreExpr_tryParse is not None:
+ # advance past ignore expressions
+ while 1:
+ try:
+ tmploc = self_ignoreExpr_tryParse(instring, tmploc)
+ except ParseBaseException:
+ break
+
+ try:
+ self_expr_parse(instring, tmploc, doActions=False, callPreParse=False)
+ except (ParseException, IndexError):
+ # no match, advance loc in string
+ tmploc += 1
+ else:
+ # matched skipto expr, done
+ break
+
+ else:
+ # ran off the end of the input string without matching skipto expr, fail
+ raise ParseException(instring, loc, self.errmsg, self)
+
+ # build up return values
+ loc = tmploc
+ skiptext = instring[startloc:loc]
+ skipresult = ParseResults(skiptext)
+
+ if self.includeMatch:
+ loc, mat = self_expr_parse(instring, loc, doActions, callPreParse=False)
+ skipresult += mat
+
+ return loc, skipresult
+
+
+class Forward(ParseElementEnhance):
+ """
+ Forward declaration of an expression to be defined later -
+ used for recursive grammars, such as algebraic infix notation.
+ When the expression is known, it is assigned to the ``Forward``
+ variable using the ``'<<'`` operator.
+
+ Note: take care when assigning to ``Forward`` not to overlook
+ precedence of operators.
+
+ Specifically, ``'|'`` has a lower precedence than ``'<<'``, so that::
+
+ fwd_expr << a | b | c
+
+ will actually be evaluated as::
+
+ (fwd_expr << a) | b | c
+
+ thereby leaving b and c out as parseable alternatives. It is recommended that you
+ explicitly group the values inserted into the ``Forward``::
+
+ fwd_expr << (a | b | c)
+
+ Converting to use the ``'<<='`` operator instead will avoid this problem.
+
+ See :class:`ParseResults.pprint` for an example of a recursive
+ parser created using ``Forward``.
+ """
+
+ def __init__(self, other: OptionalType[Union[ParserElement, str]] = None):
+ self.caller_frame = traceback.extract_stack(limit=2)[0]
+ super().__init__(other, savelist=False)
+ self.lshift_line = None
+
+ def __lshift__(self, other):
+ if hasattr(self, "caller_frame"):
+ del self.caller_frame
+ if isinstance(other, str_type):
+ other = self._literalStringClass(other)
+ self.expr = other
+ self.mayIndexError = self.expr.mayIndexError
+ self.mayReturnEmpty = self.expr.mayReturnEmpty
+ self.set_whitespace_chars(
+ self.expr.whiteChars, copy_defaults=self.expr.copyDefaultWhiteChars
+ )
+ self.skipWhitespace = self.expr.skipWhitespace
+ self.saveAsList = self.expr.saveAsList
+ self.ignoreExprs.extend(self.expr.ignoreExprs)
+ self.lshift_line = traceback.extract_stack(limit=2)[-2]
+ return self
+
+ def __ilshift__(self, other):
+ return self << other
+
+ def __or__(self, other):
+ caller_line = traceback.extract_stack(limit=2)[-2]
+ if (
+ __diag__.warn_on_match_first_with_lshift_operator
+ and caller_line == self.lshift_line
+ and Diagnostics.warn_on_match_first_with_lshift_operator
+ not in self.suppress_warnings_
+ ):
+ warnings.warn(
+ "using '<<' operator with '|' is probably an error, use '<<='",
+ stacklevel=2,
+ )
+ ret = super().__or__(other)
+ return ret
+
+ def __del__(self):
+ # see if we are getting dropped because of '=' reassignment of var instead of '<<=' or '<<'
+ if (
+ self.expr is None
+ and __diag__.warn_on_assignment_to_Forward
+ and Diagnostics.warn_on_assignment_to_Forward not in self.suppress_warnings_
+ ):
+ warnings.warn_explicit(
+ "Forward defined here but no expression attached later using '<<=' or '<<'",
+ UserWarning,
+ filename=self.caller_frame.filename,
+ lineno=self.caller_frame.lineno,
+ )
+
+ def parseImpl(self, instring, loc, doActions=True):
+ if (
+ self.expr is None
+ and __diag__.warn_on_parse_using_empty_Forward
+ and Diagnostics.warn_on_parse_using_empty_Forward
+ not in self.suppress_warnings_
+ ):
+ # walk stack until parse_string, scan_string, search_string, or transform_string is found
+ parse_fns = [
+ "parse_string",
+ "scan_string",
+ "search_string",
+ "transform_string",
+ ]
+ tb = traceback.extract_stack(limit=200)
+ for i, frm in enumerate(reversed(tb), start=1):
+ if frm.name in parse_fns:
+ stacklevel = i + 1
+ break
+ else:
+ stacklevel = 2
+ warnings.warn(
+ "Forward expression was never assigned a value, will not parse any input",
+ stacklevel=stacklevel,
+ )
+ if not ParserElement._left_recursion_enabled:
+ return super().parseImpl(instring, loc, doActions)
+ # ## Bounded Recursion algorithm ##
+ # Recursion only needs to be processed at ``Forward`` elements, since they are
+ # the only ones that can actually refer to themselves. The general idea is
+ # to handle recursion stepwise: We start at no recursion, then recurse once,
+ # recurse twice, ..., until more recursion offers no benefit (we hit the bound).
+ #
+ # The "trick" here is that each ``Forward`` gets evaluated in two contexts
+ # - to *match* a specific recursion level, and
+ # - to *search* the bounded recursion level
+ # and the two run concurrently. The *search* must *match* each recursion level
+ # to find the best possible match. This is handled by a memo table, which
+ # provides the previous match to the next level match attempt.
+ #
+ # See also "Left Recursion in Parsing Expression Grammars", Medeiros et al.
+ #
+ # There is a complication since we not only *parse* but also *transform* via
+ # actions: We do not want to run the actions too often while expanding. Thus,
+ # we expand using `doActions=False` and only run `doActions=True` if the next
+ # recursion level is acceptable.
+ with ParserElement.recursion_lock:
+ memo = ParserElement.recursion_memos
+ try:
+ # we are parsing at a specific recursion expansion - use it as-is
+ prev_loc, prev_result = memo[loc, self, doActions]
+ if isinstance(prev_result, Exception):
+ raise prev_result
+ return prev_loc, prev_result.copy()
+ except KeyError:
+ act_key = (loc, self, True)
+ peek_key = (loc, self, False)
+ # we are searching for the best recursion expansion - keep on improving
+ # both `doActions` cases must be tracked separately here!
+ prev_loc, prev_peek = memo[peek_key] = (
+ loc - 1,
+ ParseException(
+ instring, loc, "Forward recursion without base case", self
+ ),
+ )
+ if doActions:
+ memo[act_key] = memo[peek_key]
+ while True:
+ try:
+ new_loc, new_peek = super().parseImpl(instring, loc, False)
+ except ParseException:
+ # we failed before getting any match – do not hide the error
+ if isinstance(prev_peek, Exception):
+ raise
+ new_loc, new_peek = prev_loc, prev_peek
+ # the match did not get better: we are done
+ if new_loc <= prev_loc:
+ if doActions:
+ # replace the match for doActions=False as well,
+ # in case the action did backtrack
+ prev_loc, prev_result = memo[peek_key] = memo[act_key]
+ del memo[peek_key], memo[act_key]
+ return prev_loc, prev_result.copy()
+ del memo[peek_key]
+ return prev_loc, prev_peek.copy()
+ # the match did get better: see if we can improve further
+ else:
+ if doActions:
+ try:
+ memo[act_key] = super().parseImpl(instring, loc, True)
+ except ParseException as e:
+ memo[peek_key] = memo[act_key] = (new_loc, e)
+ raise
+ prev_loc, prev_peek = memo[peek_key] = new_loc, new_peek
+
+ def leave_whitespace(self, recursive: bool = True) -> ParserElement:
+ self.skipWhitespace = False
+ return self
+
+ def ignore_whitespace(self, recursive: bool = True) -> ParserElement:
+ self.skipWhitespace = True
+ return self
+
+ def streamline(self) -> ParserElement:
+ if not self.streamlined:
+ self.streamlined = True
+ if self.expr is not None:
+ self.expr.streamline()
+ return self
+
+ def validate(self, validateTrace=None) -> None:
+ if validateTrace is None:
+ validateTrace = []
+
+ if self not in validateTrace:
+ tmp = validateTrace[:] + [self]
+ if self.expr is not None:
+ self.expr.validate(tmp)
+ self._checkRecursion([])
+
+ def _generateDefaultName(self):
+ # Avoid infinite recursion by setting a temporary _defaultName
+ self._defaultName = ": ..."
+
+ # Use the string representation of main expression.
+ retString = "..."
+ try:
+ if self.expr is not None:
+ retString = str(self.expr)[:1000]
+ else:
+ retString = "None"
+ finally:
+ return self.__class__.__name__ + ": " + retString
+
+ def copy(self) -> ParserElement:
+ if self.expr is not None:
+ return super().copy()
+ else:
+ ret = Forward()
+ ret <<= self
+ return ret
+
+ def _setResultsName(self, name, list_all_matches=False):
+ if (
+ __diag__.warn_name_set_on_empty_Forward
+ and Diagnostics.warn_name_set_on_empty_Forward
+ not in self.suppress_warnings_
+ ):
+ if self.expr is None:
+ warnings.warn(
+ "{}: setting results name {!r} on {} expression "
+ "that has no contained expression".format(
+ "warn_name_set_on_empty_Forward", name, type(self).__name__
+ ),
+ stacklevel=3,
+ )
+
+ return super()._setResultsName(name, list_all_matches)
+
+ ignoreWhitespace = ignore_whitespace
+ leaveWhitespace = leave_whitespace
+
+
+class TokenConverter(ParseElementEnhance):
+ """
+ Abstract subclass of :class:`ParseExpression`, for converting parsed results.
+ """
+
+ def __init__(self, expr: Union[ParserElement, str], savelist=False):
+ super().__init__(expr) # , savelist)
+ self.saveAsList = False
+
+
+class Combine(TokenConverter):
+ """Converter to concatenate all matching tokens to a single string.
+ By default, the matching patterns must also be contiguous in the
+ input string; this can be disabled by specifying
+ ``'adjacent=False'`` in the constructor.
+
+ Example::
+
+ real = Word(nums) + '.' + Word(nums)
+ print(real.parse_string('3.1416')) # -> ['3', '.', '1416']
+ # will also erroneously match the following
+ print(real.parse_string('3. 1416')) # -> ['3', '.', '1416']
+
+ real = Combine(Word(nums) + '.' + Word(nums))
+ print(real.parse_string('3.1416')) # -> ['3.1416']
+ # no match when there are internal spaces
+ print(real.parse_string('3. 1416')) # -> Exception: Expected W:(0123...)
+ """
+
+ def __init__(
+ self,
+ expr: ParserElement,
+ join_string: str = "",
+ adjacent: bool = True,
+ *,
+ joinString: OptionalType[str] = None,
+ ):
+ super().__init__(expr)
+ joinString = joinString if joinString is not None else join_string
+ # suppress whitespace-stripping in contained parse expressions, but re-enable it on the Combine itself
+ if adjacent:
+ self.leave_whitespace()
+ self.adjacent = adjacent
+ self.skipWhitespace = True
+ self.joinString = joinString
+ self.callPreparse = True
+
+ def ignore(self, other) -> ParserElement:
+ if self.adjacent:
+ ParserElement.ignore(self, other)
+ else:
+ super().ignore(other)
+ return self
+
+ def postParse(self, instring, loc, tokenlist):
+ retToks = tokenlist.copy()
+ del retToks[:]
+ retToks += ParseResults(
+ ["".join(tokenlist._asStringList(self.joinString))], modal=self.modalResults
+ )
+
+ if self.resultsName and retToks.haskeys():
+ return [retToks]
+ else:
+ return retToks
+
+
+class Group(TokenConverter):
+ """Converter to return the matched tokens as a list - useful for
+ returning tokens of :class:`ZeroOrMore` and :class:`OneOrMore` expressions.
+
+ The optional ``aslist`` argument when set to True will return the
+ parsed tokens as a Python list instead of a pyparsing ParseResults.
+
+ Example::
+
+ ident = Word(alphas)
+ num = Word(nums)
+ term = ident | num
+ func = ident + Opt(delimited_list(term))
+ print(func.parse_string("fn a, b, 100"))
+ # -> ['fn', 'a', 'b', '100']
+
+ func = ident + Group(Opt(delimited_list(term)))
+ print(func.parse_string("fn a, b, 100"))
+ # -> ['fn', ['a', 'b', '100']]
+ """
+
+ def __init__(self, expr: ParserElement, aslist: bool = False):
+ super().__init__(expr)
+ self.saveAsList = True
+ self._asPythonList = aslist
+
+ def postParse(self, instring, loc, tokenlist):
+ if self._asPythonList:
+ return ParseResults.List(
+ tokenlist.asList()
+ if isinstance(tokenlist, ParseResults)
+ else list(tokenlist)
+ )
+ else:
+ return [tokenlist]
+
+
+class Dict(TokenConverter):
+ """Converter to return a repetitive expression as a list, but also
+ as a dictionary. Each element can also be referenced using the first
+ token in the expression as its key. Useful for tabular report
+ scraping when the first column can be used as a item key.
+
+ The optional ``asdict`` argument when set to True will return the
+ parsed tokens as a Python dict instead of a pyparsing ParseResults.
+
+ Example::
+
+ data_word = Word(alphas)
+ label = data_word + FollowedBy(':')
+
+ text = "shape: SQUARE posn: upper left color: light blue texture: burlap"
+ attr_expr = (label + Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join))
+
+ # print attributes as plain groups
+ print(OneOrMore(attr_expr).parse_string(text).dump())
+
+ # instead of OneOrMore(expr), parse using Dict(OneOrMore(Group(expr))) - Dict will auto-assign names
+ result = Dict(OneOrMore(Group(attr_expr))).parse_string(text)
+ print(result.dump())
+
+ # access named fields as dict entries, or output as dict
+ print(result['shape'])
+ print(result.as_dict())
+
+ prints::
+
+ ['shape', 'SQUARE', 'posn', 'upper left', 'color', 'light blue', 'texture', 'burlap']
+ [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']]
+ - color: 'light blue'
+ - posn: 'upper left'
+ - shape: 'SQUARE'
+ - texture: 'burlap'
+ SQUARE
+ {'color': 'light blue', 'posn': 'upper left', 'texture': 'burlap', 'shape': 'SQUARE'}
+
+ See more examples at :class:`ParseResults` of accessing fields by results name.
+ """
+
+ def __init__(self, expr: ParserElement, asdict: bool = False):
+ super().__init__(expr)
+ self.saveAsList = True
+ self._asPythonDict = asdict
+
+ def postParse(self, instring, loc, tokenlist):
+ for i, tok in enumerate(tokenlist):
+ if len(tok) == 0:
+ continue
+
+ ikey = tok[0]
+ if isinstance(ikey, int):
+ ikey = str(ikey).strip()
+
+ if len(tok) == 1:
+ tokenlist[ikey] = _ParseResultsWithOffset("", i)
+
+ elif len(tok) == 2 and not isinstance(tok[1], ParseResults):
+ tokenlist[ikey] = _ParseResultsWithOffset(tok[1], i)
+
+ else:
+ try:
+ dictvalue = tok.copy() # ParseResults(i)
+ except Exception:
+ exc = TypeError(
+ "could not extract dict values from parsed results"
+ " - Dict expression must contain Grouped expressions"
+ )
+ raise exc from None
+
+ del dictvalue[0]
+
+ if len(dictvalue) != 1 or (
+ isinstance(dictvalue, ParseResults) and dictvalue.haskeys()
+ ):
+ tokenlist[ikey] = _ParseResultsWithOffset(dictvalue, i)
+ else:
+ tokenlist[ikey] = _ParseResultsWithOffset(dictvalue[0], i)
+
+ if self._asPythonDict:
+ return [tokenlist.as_dict()] if self.resultsName else tokenlist.as_dict()
+ else:
+ return [tokenlist] if self.resultsName else tokenlist
+
+
+class Suppress(TokenConverter):
+ """Converter for ignoring the results of a parsed expression.
+
+ Example::
+
+ source = "a, b, c,d"
+ wd = Word(alphas)
+ wd_list1 = wd + ZeroOrMore(',' + wd)
+ print(wd_list1.parse_string(source))
+
+ # often, delimiters that are useful during parsing are just in the
+ # way afterward - use Suppress to keep them out of the parsed output
+ wd_list2 = wd + ZeroOrMore(Suppress(',') + wd)
+ print(wd_list2.parse_string(source))
+
+ # Skipped text (using '...') can be suppressed as well
+ source = "lead in START relevant text END trailing text"
+ start_marker = Keyword("START")
+ end_marker = Keyword("END")
+ find_body = Suppress(...) + start_marker + ... + end_marker
+ print(find_body.parse_string(source)
+
+ prints::
+
+ ['a', ',', 'b', ',', 'c', ',', 'd']
+ ['a', 'b', 'c', 'd']
+ ['START', 'relevant text ', 'END']
+
+ (See also :class:`delimited_list`.)
+ """
+
+ def __init__(self, expr: Union[ParserElement, str], savelist: bool = False):
+ if expr is ...:
+ expr = _PendingSkip(NoMatch())
+ super().__init__(expr)
+
+ def __add__(self, other) -> "ParserElement":
+ if isinstance(self.expr, _PendingSkip):
+ return Suppress(SkipTo(other)) + other
+ else:
+ return super().__add__(other)
+
+ def __sub__(self, other) -> "ParserElement":
+ if isinstance(self.expr, _PendingSkip):
+ return Suppress(SkipTo(other)) - other
+ else:
+ return super().__sub__(other)
+
+ def postParse(self, instring, loc, tokenlist):
+ return []
+
+ def suppress(self) -> ParserElement:
+ return self
+
+
+def trace_parse_action(f: ParseAction) -> ParseAction:
+ """Decorator for debugging parse actions.
+
+ When the parse action is called, this decorator will print
+ ``">> entering method-name(line:<current_source_line>, <parse_location>, <matched_tokens>)"``.
+ When the parse action completes, the decorator will print
+ ``"<<"`` followed by the returned value, or any exception that the parse action raised.
+
+ Example::
+
+ wd = Word(alphas)
+
+ @trace_parse_action
+ def remove_duplicate_chars(tokens):
+ return ''.join(sorted(set(''.join(tokens))))
+
+ wds = OneOrMore(wd).set_parse_action(remove_duplicate_chars)
+ print(wds.parse_string("slkdjs sld sldd sdlf sdljf"))
+
+ prints::
+
+ >>entering remove_duplicate_chars(line: 'slkdjs sld sldd sdlf sdljf', 0, (['slkdjs', 'sld', 'sldd', 'sdlf', 'sdljf'], {}))
+ <<leaving remove_duplicate_chars (ret: 'dfjkls')
+ ['dfjkls']
+ """
+ f = _trim_arity(f)
+
+ def z(*paArgs):
+ thisFunc = f.__name__
+ s, l, t = paArgs[-3:]
+ if len(paArgs) > 3:
+ thisFunc = paArgs[0].__class__.__name__ + "." + thisFunc
+ sys.stderr.write(
+ ">>entering {}(line: {!r}, {}, {!r})\n".format(thisFunc, line(l, s), l, t)
+ )
+ try:
+ ret = f(*paArgs)
+ except Exception as exc:
+ sys.stderr.write("<<leaving {} (exception: {})\n".format(thisFunc, exc))
+ raise
+ sys.stderr.write("<<leaving {} (ret: {!r})\n".format(thisFunc, ret))
+ return ret
+
+ z.__name__ = f.__name__
+ return z
+
+
+# convenience constants for positional expressions
+empty = Empty().set_name("empty")
+line_start = LineStart().set_name("line_start")
+line_end = LineEnd().set_name("line_end")
+string_start = StringStart().set_name("string_start")
+string_end = StringEnd().set_name("string_end")
+
+_escapedPunc = Word(_bslash, r"\[]-*.$+^?()~ ", exact=2).set_parse_action(
+ lambda s, l, t: t[0][1]
+)
+_escapedHexChar = Regex(r"\\0?[xX][0-9a-fA-F]+").set_parse_action(
+ lambda s, l, t: chr(int(t[0].lstrip(r"\0x"), 16))
+)
+_escapedOctChar = Regex(r"\\0[0-7]+").set_parse_action(
+ lambda s, l, t: chr(int(t[0][1:], 8))
+)
+_singleChar = (
+ _escapedPunc | _escapedHexChar | _escapedOctChar | CharsNotIn(r"\]", exact=1)
+)
+_charRange = Group(_singleChar + Suppress("-") + _singleChar)
+_reBracketExpr = (
+ Literal("[")
+ + Opt("^").set_results_name("negate")
+ + Group(OneOrMore(_charRange | _singleChar)).set_results_name("body")
+ + "]"
+)
+
+
+def srange(s: str) -> str:
+ r"""Helper to easily define string ranges for use in :class:`Word`
+ construction. Borrows syntax from regexp ``'[]'`` string range
+ definitions::
+
+ srange("[0-9]") -> "0123456789"
+ srange("[a-z]") -> "abcdefghijklmnopqrstuvwxyz"
+ srange("[a-z$_]") -> "abcdefghijklmnopqrstuvwxyz$_"
+
+ The input string must be enclosed in []'s, and the returned string
+ is the expanded character set joined into a single string. The
+ values enclosed in the []'s may be:
+
+ - a single character
+ - an escaped character with a leading backslash (such as ``\-``
+ or ``\]``)
+ - an escaped hex character with a leading ``'\x'``
+ (``\x21``, which is a ``'!'`` character) (``\0x##``
+ is also supported for backwards compatibility)
+ - an escaped octal character with a leading ``'\0'``
+ (``\041``, which is a ``'!'`` character)
+ - a range of any of the above, separated by a dash (``'a-z'``,
+ etc.)
+ - any combination of the above (``'aeiouy'``,
+ ``'a-zA-Z0-9_$'``, etc.)
+ """
+ _expanded = (
+ lambda p: p
+ if not isinstance(p, ParseResults)
+ else "".join(chr(c) for c in range(ord(p[0]), ord(p[1]) + 1))
+ )
+ try:
+ return "".join(_expanded(part) for part in _reBracketExpr.parse_string(s).body)
+ except Exception:
+ return ""
+
+
+def token_map(func, *args) -> ParseAction:
+ """Helper to define a parse action by mapping a function to all
+ elements of a :class:`ParseResults` list. If any additional args are passed,
+ they are forwarded to the given function as additional arguments
+ after the token, as in
+ ``hex_integer = Word(hexnums).set_parse_action(token_map(int, 16))``,
+ which will convert the parsed data to an integer using base 16.
+
+ Example (compare the last to example in :class:`ParserElement.transform_string`::
+
+ hex_ints = OneOrMore(Word(hexnums)).set_parse_action(token_map(int, 16))
+ hex_ints.run_tests('''
+ 00 11 22 aa FF 0a 0d 1a
+ ''')
+
+ upperword = Word(alphas).set_parse_action(token_map(str.upper))
+ OneOrMore(upperword).run_tests('''
+ my kingdom for a horse
+ ''')
+
+ wd = Word(alphas).set_parse_action(token_map(str.title))
+ OneOrMore(wd).set_parse_action(' '.join).run_tests('''
+ now is the winter of our discontent made glorious summer by this sun of york
+ ''')
+
+ prints::
+
+ 00 11 22 aa FF 0a 0d 1a
+ [0, 17, 34, 170, 255, 10, 13, 26]
+
+ my kingdom for a horse
+ ['MY', 'KINGDOM', 'FOR', 'A', 'HORSE']
+
+ now is the winter of our discontent made glorious summer by this sun of york
+ ['Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York']
+ """
+
+ def pa(s, l, t):
+ return [func(tokn, *args) for tokn in t]
+
+ func_name = getattr(func, "__name__", getattr(func, "__class__").__name__)
+ pa.__name__ = func_name
+
+ return pa
+
+
+def autoname_elements() -> None:
+ """
+ Utility to simplify mass-naming of parser elements, for
+ generating railroad diagram with named subdiagrams.
+ """
+ for name, var in sys._getframe().f_back.f_locals.items():
+ if isinstance(var, ParserElement) and not var.customName:
+ var.set_name(name)
+
+
+dbl_quoted_string = Combine(
+ Regex(r'"(?:[^"\n\r\\]|(?:"")|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*') + '"'
+).set_name("string enclosed in double quotes")
+
+sgl_quoted_string = Combine(
+ Regex(r"'(?:[^'\n\r\\]|(?:'')|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*") + "'"
+).set_name("string enclosed in single quotes")
+
+quoted_string = Combine(
+ Regex(r'"(?:[^"\n\r\\]|(?:"")|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*') + '"'
+ | Regex(r"'(?:[^'\n\r\\]|(?:'')|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*") + "'"
+).set_name("quotedString using single or double quotes")
+
+unicode_string = Combine("u" + quoted_string.copy()).set_name("unicode string literal")
+
+
+alphas8bit = srange(r"[\0xc0-\0xd6\0xd8-\0xf6\0xf8-\0xff]")
+punc8bit = srange(r"[\0xa1-\0xbf\0xd7\0xf7]")
+
+# build list of built-in expressions, for future reference if a global default value
+# gets updated
+_builtin_exprs = [v for v in vars().values() if isinstance(v, ParserElement)]
+
+# backward compatibility names
+tokenMap = token_map
+conditionAsParseAction = condition_as_parse_action
+nullDebugAction = null_debug_action
+sglQuotedString = sgl_quoted_string
+dblQuotedString = dbl_quoted_string
+quotedString = quoted_string
+unicodeString = unicode_string
+lineStart = line_start
+lineEnd = line_end
+stringStart = string_start
+stringEnd = string_end
+traceParseAction = trace_parse_action
diff --git a/setuptools/_vendor/pyparsing/diagram/__init__.py b/setuptools/_vendor/pyparsing/diagram/__init__.py
new file mode 100644
index 00000000..2d0c587c
--- /dev/null
+++ b/setuptools/_vendor/pyparsing/diagram/__init__.py
@@ -0,0 +1,611 @@
+import railroad
+import pyparsing
+from pkg_resources import resource_filename
+from typing import (
+ List,
+ Optional,
+ NamedTuple,
+ Generic,
+ TypeVar,
+ Dict,
+ Callable,
+ Set,
+ Iterable,
+)
+from jinja2 import Template
+from io import StringIO
+import inspect
+
+
+with open(resource_filename(__name__, "template.jinja2"), encoding="utf-8") as fp:
+ template = Template(fp.read())
+
+# Note: ideally this would be a dataclass, but we're supporting Python 3.5+ so we can't do this yet
+NamedDiagram = NamedTuple(
+ "NamedDiagram",
+ [("name", str), ("diagram", Optional[railroad.DiagramItem]), ("index", int)],
+)
+"""
+A simple structure for associating a name with a railroad diagram
+"""
+
+T = TypeVar("T")
+
+
+class EachItem(railroad.Group):
+ """
+ Custom railroad item to compose a:
+ - Group containing a
+ - OneOrMore containing a
+ - Choice of the elements in the Each
+ with the group label indicating that all must be matched
+ """
+
+ all_label = "[ALL]"
+
+ def __init__(self, *items):
+ choice_item = railroad.Choice(len(items) - 1, *items)
+ one_or_more_item = railroad.OneOrMore(item=choice_item)
+ super().__init__(one_or_more_item, label=self.all_label)
+
+
+class AnnotatedItem(railroad.Group):
+ """
+ Simple subclass of Group that creates an annotation label
+ """
+
+ def __init__(self, label: str, item):
+ super().__init__(item=item, label="[{}]".format(label) if label else label)
+
+
+class EditablePartial(Generic[T]):
+ """
+ Acts like a functools.partial, but can be edited. In other words, it represents a type that hasn't yet been
+ constructed.
+ """
+
+ # We need this here because the railroad constructors actually transform the data, so can't be called until the
+ # entire tree is assembled
+
+ def __init__(self, func: Callable[..., T], args: list, kwargs: dict):
+ self.func = func
+ self.args = args
+ self.kwargs = kwargs
+
+ @classmethod
+ def from_call(cls, func: Callable[..., T], *args, **kwargs) -> "EditablePartial[T]":
+ """
+ If you call this function in the same way that you would call the constructor, it will store the arguments
+ as you expect. For example EditablePartial.from_call(Fraction, 1, 3)() == Fraction(1, 3)
+ """
+ return EditablePartial(func=func, args=list(args), kwargs=kwargs)
+
+ @property
+ def name(self):
+ return self.kwargs["name"]
+
+ def __call__(self) -> T:
+ """
+ Evaluate the partial and return the result
+ """
+ args = self.args.copy()
+ kwargs = self.kwargs.copy()
+
+ # This is a helpful hack to allow you to specify varargs parameters (e.g. *args) as keyword args (e.g.
+ # args=['list', 'of', 'things'])
+ arg_spec = inspect.getfullargspec(self.func)
+ if arg_spec.varargs in self.kwargs:
+ args += kwargs.pop(arg_spec.varargs)
+
+ return self.func(*args, **kwargs)
+
+
+def railroad_to_html(diagrams: List[NamedDiagram], **kwargs) -> str:
+ """
+ Given a list of NamedDiagram, produce a single HTML string that visualises those diagrams
+ :params kwargs: kwargs to be passed in to the template
+ """
+ data = []
+ for diagram in diagrams:
+ io = StringIO()
+ diagram.diagram.writeSvg(io.write)
+ title = diagram.name
+ if diagram.index == 0:
+ title += " (root)"
+ data.append({"title": title, "text": "", "svg": io.getvalue()})
+
+ return template.render(diagrams=data, **kwargs)
+
+
+def resolve_partial(partial: "EditablePartial[T]") -> T:
+ """
+ Recursively resolves a collection of Partials into whatever type they are
+ """
+ if isinstance(partial, EditablePartial):
+ partial.args = resolve_partial(partial.args)
+ partial.kwargs = resolve_partial(partial.kwargs)
+ return partial()
+ elif isinstance(partial, list):
+ return [resolve_partial(x) for x in partial]
+ elif isinstance(partial, dict):
+ return {key: resolve_partial(x) for key, x in partial.items()}
+ else:
+ return partial
+
+
+def to_railroad(
+ element: pyparsing.ParserElement,
+ diagram_kwargs: Optional[dict] = None,
+ vertical: int = 3,
+ show_results_names: bool = False,
+ show_groups: bool = False,
+) -> List[NamedDiagram]:
+ """
+ Convert a pyparsing element tree into a list of diagrams. This is the recommended entrypoint to diagram
+ creation if you want to access the Railroad tree before it is converted to HTML
+ :param element: base element of the parser being diagrammed
+ :param diagram_kwargs: kwargs to pass to the Diagram() constructor
+ :param vertical: (optional) - int - limit at which number of alternatives should be
+ shown vertically instead of horizontally
+ :param show_results_names - bool to indicate whether results name annotations should be
+ included in the diagram
+ :param show_groups - bool to indicate whether groups should be highlighted with an unlabeled
+ surrounding box
+ """
+ # Convert the whole tree underneath the root
+ lookup = ConverterState(diagram_kwargs=diagram_kwargs or {})
+ _to_diagram_element(
+ element,
+ lookup=lookup,
+ parent=None,
+ vertical=vertical,
+ show_results_names=show_results_names,
+ show_groups=show_groups,
+ )
+
+ root_id = id(element)
+ # Convert the root if it hasn't been already
+ if root_id in lookup:
+ if not element.customName:
+ lookup[root_id].name = ""
+ lookup[root_id].mark_for_extraction(root_id, lookup, force=True)
+
+ # Now that we're finished, we can convert from intermediate structures into Railroad elements
+ diags = list(lookup.diagrams.values())
+ if len(diags) > 1:
+ # collapse out duplicate diags with the same name
+ seen = set()
+ deduped_diags = []
+ for d in diags:
+ # don't extract SkipTo elements, they are uninformative as subdiagrams
+ if d.name == "...":
+ continue
+ if d.name is not None and d.name not in seen:
+ seen.add(d.name)
+ deduped_diags.append(d)
+ resolved = [resolve_partial(partial) for partial in deduped_diags]
+ else:
+ # special case - if just one diagram, always display it, even if
+ # it has no name
+ resolved = [resolve_partial(partial) for partial in diags]
+ return sorted(resolved, key=lambda diag: diag.index)
+
+
+def _should_vertical(
+ specification: int, exprs: Iterable[pyparsing.ParserElement]
+) -> bool:
+ """
+ Returns true if we should return a vertical list of elements
+ """
+ if specification is None:
+ return False
+ else:
+ return len(_visible_exprs(exprs)) >= specification
+
+
+class ElementState:
+ """
+ State recorded for an individual pyparsing Element
+ """
+
+ # Note: this should be a dataclass, but we have to support Python 3.5
+ def __init__(
+ self,
+ element: pyparsing.ParserElement,
+ converted: EditablePartial,
+ parent: EditablePartial,
+ number: int,
+ name: str = None,
+ parent_index: Optional[int] = None,
+ ):
+ #: The pyparsing element that this represents
+ self.element: pyparsing.ParserElement = element
+ #: The name of the element
+ self.name: str = name
+ #: The output Railroad element in an unconverted state
+ self.converted: EditablePartial = converted
+ #: The parent Railroad element, which we store so that we can extract this if it's duplicated
+ self.parent: EditablePartial = parent
+ #: The order in which we found this element, used for sorting diagrams if this is extracted into a diagram
+ self.number: int = number
+ #: The index of this inside its parent
+ self.parent_index: Optional[int] = parent_index
+ #: If true, we should extract this out into a subdiagram
+ self.extract: bool = False
+ #: If true, all of this element's children have been filled out
+ self.complete: bool = False
+
+ def mark_for_extraction(
+ self, el_id: int, state: "ConverterState", name: str = None, force: bool = False
+ ):
+ """
+ Called when this instance has been seen twice, and thus should eventually be extracted into a sub-diagram
+ :param el_id: id of the element
+ :param state: element/diagram state tracker
+ :param name: name to use for this element's text
+ :param force: If true, force extraction now, regardless of the state of this. Only useful for extracting the
+ root element when we know we're finished
+ """
+ self.extract = True
+
+ # Set the name
+ if not self.name:
+ if name:
+ # Allow forcing a custom name
+ self.name = name
+ elif self.element.customName:
+ self.name = self.element.customName
+ else:
+ self.name = ""
+
+ # Just because this is marked for extraction doesn't mean we can do it yet. We may have to wait for children
+ # to be added
+ # Also, if this is just a string literal etc, don't bother extracting it
+ if force or (self.complete and _worth_extracting(self.element)):
+ state.extract_into_diagram(el_id)
+
+
+class ConverterState:
+ """
+ Stores some state that persists between recursions into the element tree
+ """
+
+ def __init__(self, diagram_kwargs: Optional[dict] = None):
+ #: A dictionary mapping ParserElements to state relating to them
+ self._element_diagram_states: Dict[int, ElementState] = {}
+ #: A dictionary mapping ParserElement IDs to subdiagrams generated from them
+ self.diagrams: Dict[int, EditablePartial[NamedDiagram]] = {}
+ #: The index of the next unnamed element
+ self.unnamed_index: int = 1
+ #: The index of the next element. This is used for sorting
+ self.index: int = 0
+ #: Shared kwargs that are used to customize the construction of diagrams
+ self.diagram_kwargs: dict = diagram_kwargs or {}
+ self.extracted_diagram_names: Set[str] = set()
+
+ def __setitem__(self, key: int, value: ElementState):
+ self._element_diagram_states[key] = value
+
+ def __getitem__(self, key: int) -> ElementState:
+ return self._element_diagram_states[key]
+
+ def __delitem__(self, key: int):
+ del self._element_diagram_states[key]
+
+ def __contains__(self, key: int):
+ return key in self._element_diagram_states
+
+ def generate_unnamed(self) -> int:
+ """
+ Generate a number used in the name of an otherwise unnamed diagram
+ """
+ self.unnamed_index += 1
+ return self.unnamed_index
+
+ def generate_index(self) -> int:
+ """
+ Generate a number used to index a diagram
+ """
+ self.index += 1
+ return self.index
+
+ def extract_into_diagram(self, el_id: int):
+ """
+ Used when we encounter the same token twice in the same tree. When this
+ happens, we replace all instances of that token with a terminal, and
+ create a new subdiagram for the token
+ """
+ position = self[el_id]
+
+ # Replace the original definition of this element with a regular block
+ if position.parent:
+ ret = EditablePartial.from_call(railroad.NonTerminal, text=position.name)
+ if "item" in position.parent.kwargs:
+ position.parent.kwargs["item"] = ret
+ elif "items" in position.parent.kwargs:
+ position.parent.kwargs["items"][position.parent_index] = ret
+
+ # If the element we're extracting is a group, skip to its content but keep the title
+ if position.converted.func == railroad.Group:
+ content = position.converted.kwargs["item"]
+ else:
+ content = position.converted
+
+ self.diagrams[el_id] = EditablePartial.from_call(
+ NamedDiagram,
+ name=position.name,
+ diagram=EditablePartial.from_call(
+ railroad.Diagram, content, **self.diagram_kwargs
+ ),
+ index=position.number,
+ )
+
+ del self[el_id]
+
+
+def _worth_extracting(element: pyparsing.ParserElement) -> bool:
+ """
+ Returns true if this element is worth having its own sub-diagram. Simply, if any of its children
+ themselves have children, then its complex enough to extract
+ """
+ children = element.recurse()
+ return any(child.recurse() for child in children)
+
+
+def _apply_diagram_item_enhancements(fn):
+ """
+ decorator to ensure enhancements to a diagram item (such as results name annotations)
+ get applied on return from _to_diagram_element (we do this since there are several
+ returns in _to_diagram_element)
+ """
+
+ def _inner(
+ element: pyparsing.ParserElement,
+ parent: Optional[EditablePartial],
+ lookup: ConverterState = None,
+ vertical: int = None,
+ index: int = 0,
+ name_hint: str = None,
+ show_results_names: bool = False,
+ show_groups: bool = False,
+ ) -> Optional[EditablePartial]:
+
+ ret = fn(
+ element,
+ parent,
+ lookup,
+ vertical,
+ index,
+ name_hint,
+ show_results_names,
+ show_groups,
+ )
+
+ # apply annotation for results name, if present
+ if show_results_names and ret is not None:
+ element_results_name = element.resultsName
+ if element_results_name:
+ # add "*" to indicate if this is a "list all results" name
+ element_results_name += "" if element.modalResults else "*"
+ ret = EditablePartial.from_call(
+ railroad.Group, item=ret, label=element_results_name
+ )
+
+ return ret
+
+ return _inner
+
+
+def _visible_exprs(exprs: Iterable[pyparsing.ParserElement]):
+ non_diagramming_exprs = (
+ pyparsing.ParseElementEnhance,
+ pyparsing.PositionToken,
+ pyparsing.And._ErrorStop,
+ )
+ return [
+ e
+ for e in exprs
+ if not (e.customName or e.resultsName or isinstance(e, non_diagramming_exprs))
+ ]
+
+
+@_apply_diagram_item_enhancements
+def _to_diagram_element(
+ element: pyparsing.ParserElement,
+ parent: Optional[EditablePartial],
+ lookup: ConverterState = None,
+ vertical: int = None,
+ index: int = 0,
+ name_hint: str = None,
+ show_results_names: bool = False,
+ show_groups: bool = False,
+) -> Optional[EditablePartial]:
+ """
+ Recursively converts a PyParsing Element to a railroad Element
+ :param lookup: The shared converter state that keeps track of useful things
+ :param index: The index of this element within the parent
+ :param parent: The parent of this element in the output tree
+ :param vertical: Controls at what point we make a list of elements vertical. If this is an integer (the default),
+ it sets the threshold of the number of items before we go vertical. If True, always go vertical, if False, never
+ do so
+ :param name_hint: If provided, this will override the generated name
+ :param show_results_names: bool flag indicating whether to add annotations for results names
+ :returns: The converted version of the input element, but as a Partial that hasn't yet been constructed
+ :param show_groups: bool flag indicating whether to show groups using bounding box
+ """
+ exprs = element.recurse()
+ name = name_hint or element.customName or element.__class__.__name__
+
+ # Python's id() is used to provide a unique identifier for elements
+ el_id = id(element)
+
+ element_results_name = element.resultsName
+
+ # Here we basically bypass processing certain wrapper elements if they contribute nothing to the diagram
+ if not element.customName:
+ if isinstance(
+ element,
+ (
+ # pyparsing.TokenConverter,
+ # pyparsing.Forward,
+ pyparsing.Located,
+ ),
+ ):
+ # However, if this element has a useful custom name, and its child does not, we can pass it on to the child
+ if exprs:
+ if not exprs[0].customName:
+ propagated_name = name
+ else:
+ propagated_name = None
+
+ return _to_diagram_element(
+ element.expr,
+ parent=parent,
+ lookup=lookup,
+ vertical=vertical,
+ index=index,
+ name_hint=propagated_name,
+ show_results_names=show_results_names,
+ show_groups=show_groups,
+ )
+
+ # If the element isn't worth extracting, we always treat it as the first time we say it
+ if _worth_extracting(element):
+ if el_id in lookup:
+ # If we've seen this element exactly once before, we are only just now finding out that it's a duplicate,
+ # so we have to extract it into a new diagram.
+ looked_up = lookup[el_id]
+ looked_up.mark_for_extraction(el_id, lookup, name=name_hint)
+ ret = EditablePartial.from_call(railroad.NonTerminal, text=looked_up.name)
+ return ret
+
+ elif el_id in lookup.diagrams:
+ # If we have seen the element at least twice before, and have already extracted it into a subdiagram, we
+ # just put in a marker element that refers to the sub-diagram
+ ret = EditablePartial.from_call(
+ railroad.NonTerminal, text=lookup.diagrams[el_id].kwargs["name"]
+ )
+ return ret
+
+ # Recursively convert child elements
+ # Here we find the most relevant Railroad element for matching pyparsing Element
+ # We use ``items=[]`` here to hold the place for where the child elements will go once created
+ if isinstance(element, pyparsing.And):
+ # detect And's created with ``expr*N`` notation - for these use a OneOrMore with a repeat
+ # (all will have the same name, and resultsName)
+ if not exprs:
+ return None
+ if len(set((e.name, e.resultsName) for e in exprs)) == 1:
+ ret = EditablePartial.from_call(
+ railroad.OneOrMore, item="", repeat=str(len(exprs))
+ )
+ elif _should_vertical(vertical, exprs):
+ ret = EditablePartial.from_call(railroad.Stack, items=[])
+ else:
+ ret = EditablePartial.from_call(railroad.Sequence, items=[])
+ elif isinstance(element, (pyparsing.Or, pyparsing.MatchFirst)):
+ if not exprs:
+ return None
+ if _should_vertical(vertical, exprs):
+ ret = EditablePartial.from_call(railroad.Choice, 0, items=[])
+ else:
+ ret = EditablePartial.from_call(railroad.HorizontalChoice, items=[])
+ elif isinstance(element, pyparsing.Each):
+ if not exprs:
+ return None
+ ret = EditablePartial.from_call(EachItem, items=[])
+ elif isinstance(element, pyparsing.NotAny):
+ ret = EditablePartial.from_call(AnnotatedItem, label="NOT", item="")
+ elif isinstance(element, pyparsing.FollowedBy):
+ ret = EditablePartial.from_call(AnnotatedItem, label="LOOKAHEAD", item="")
+ elif isinstance(element, pyparsing.PrecededBy):
+ ret = EditablePartial.from_call(AnnotatedItem, label="LOOKBEHIND", item="")
+ elif isinstance(element, pyparsing.Group):
+ if show_groups:
+ ret = EditablePartial.from_call(AnnotatedItem, label="", item="")
+ else:
+ ret = EditablePartial.from_call(railroad.Group, label="", item="")
+ elif isinstance(element, pyparsing.TokenConverter):
+ ret = EditablePartial.from_call(AnnotatedItem, label=type(element).__name__.lower(), item="")
+ elif isinstance(element, pyparsing.Opt):
+ ret = EditablePartial.from_call(railroad.Optional, item="")
+ elif isinstance(element, pyparsing.OneOrMore):
+ ret = EditablePartial.from_call(railroad.OneOrMore, item="")
+ elif isinstance(element, pyparsing.ZeroOrMore):
+ ret = EditablePartial.from_call(railroad.ZeroOrMore, item="")
+ elif isinstance(element, pyparsing.Group):
+ ret = EditablePartial.from_call(
+ railroad.Group, item=None, label=element_results_name
+ )
+ elif isinstance(element, pyparsing.Empty) and not element.customName:
+ # Skip unnamed "Empty" elements
+ ret = None
+ elif len(exprs) > 1:
+ ret = EditablePartial.from_call(railroad.Sequence, items=[])
+ elif len(exprs) > 0 and not element_results_name:
+ ret = EditablePartial.from_call(railroad.Group, item="", label=name)
+ else:
+ terminal = EditablePartial.from_call(railroad.Terminal, element.defaultName)
+ ret = terminal
+
+ if ret is None:
+ return
+
+ # Indicate this element's position in the tree so we can extract it if necessary
+ lookup[el_id] = ElementState(
+ element=element,
+ converted=ret,
+ parent=parent,
+ parent_index=index,
+ number=lookup.generate_index(),
+ )
+ if element.customName:
+ lookup[el_id].mark_for_extraction(el_id, lookup, element.customName)
+
+ i = 0
+ for expr in exprs:
+ # Add a placeholder index in case we have to extract the child before we even add it to the parent
+ if "items" in ret.kwargs:
+ ret.kwargs["items"].insert(i, None)
+
+ item = _to_diagram_element(
+ expr,
+ parent=ret,
+ lookup=lookup,
+ vertical=vertical,
+ index=i,
+ show_results_names=show_results_names,
+ show_groups=show_groups,
+ )
+
+ # Some elements don't need to be shown in the diagram
+ if item is not None:
+ if "item" in ret.kwargs:
+ ret.kwargs["item"] = item
+ elif "items" in ret.kwargs:
+ # If we've already extracted the child, don't touch this index, since it's occupied by a nonterminal
+ ret.kwargs["items"][i] = item
+ i += 1
+ elif "items" in ret.kwargs:
+ # If we're supposed to skip this element, remove it from the parent
+ del ret.kwargs["items"][i]
+
+ # If all this items children are none, skip this item
+ if ret and (
+ ("items" in ret.kwargs and len(ret.kwargs["items"]) == 0)
+ or ("item" in ret.kwargs and ret.kwargs["item"] is None)
+ ):
+ ret = EditablePartial.from_call(railroad.Terminal, name)
+
+ # Mark this element as "complete", ie it has all of its children
+ if el_id in lookup:
+ lookup[el_id].complete = True
+
+ if el_id in lookup and lookup[el_id].extract and lookup[el_id].complete:
+ lookup.extract_into_diagram(el_id)
+ if ret is not None:
+ ret = EditablePartial.from_call(
+ railroad.NonTerminal, text=lookup.diagrams[el_id].kwargs["name"]
+ )
+
+ return ret
diff --git a/setuptools/_vendor/pyparsing/diagram/template.jinja2 b/setuptools/_vendor/pyparsing/diagram/template.jinja2
new file mode 100644
index 00000000..d2219fb0
--- /dev/null
+++ b/setuptools/_vendor/pyparsing/diagram/template.jinja2
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<html>
+<head>
+ {% if not head %}
+ <style type="text/css">
+ .railroad-heading {
+ font-family: monospace;
+ }
+ </style>
+ {% else %}
+ {{ hear | safe }}
+ {% endif %}
+</head>
+<body>
+{{ body | safe }}
+{% for diagram in diagrams %}
+ <div class="railroad-group">
+ <h1 class="railroad-heading">{{ diagram.title }}</h1>
+ <div class="railroad-description">{{ diagram.text }}</div>
+ <div class="railroad-svg">
+ {{ diagram.svg }}
+ </div>
+ </div>
+{% endfor %}
+</body>
+</html>
diff --git a/setuptools/_vendor/pyparsing/exceptions.py b/setuptools/_vendor/pyparsing/exceptions.py
new file mode 100644
index 00000000..e06513eb
--- /dev/null
+++ b/setuptools/_vendor/pyparsing/exceptions.py
@@ -0,0 +1,267 @@
+# exceptions.py
+
+import re
+import sys
+from typing import Optional
+
+from .util import col, line, lineno, _collapse_string_to_ranges
+from .unicode import pyparsing_unicode as ppu
+
+
+class ExceptionWordUnicode(ppu.Latin1, ppu.LatinA, ppu.LatinB, ppu.Greek, ppu.Cyrillic):
+ pass
+
+
+_extract_alphanums = _collapse_string_to_ranges(ExceptionWordUnicode.alphanums)
+_exception_word_extractor = re.compile("([" + _extract_alphanums + "]{1,16})|.")
+
+
+class ParseBaseException(Exception):
+ """base exception class for all parsing runtime exceptions"""
+
+ # Performance tuning: we construct a *lot* of these, so keep this
+ # constructor as small and fast as possible
+ def __init__(
+ self,
+ pstr: str,
+ loc: int = 0,
+ msg: Optional[str] = None,
+ elem=None,
+ ):
+ self.loc = loc
+ if msg is None:
+ self.msg = pstr
+ self.pstr = ""
+ else:
+ self.msg = msg
+ self.pstr = pstr
+ self.parser_element = self.parserElement = elem
+ self.args = (pstr, loc, msg)
+
+ @staticmethod
+ def explain_exception(exc, depth=16):
+ """
+ Method to take an exception and translate the Python internal traceback into a list
+ of the pyparsing expressions that caused the exception to be raised.
+
+ Parameters:
+
+ - exc - exception raised during parsing (need not be a ParseException, in support
+ of Python exceptions that might be raised in a parse action)
+ - depth (default=16) - number of levels back in the stack trace to list expression
+ and function names; if None, the full stack trace names will be listed; if 0, only
+ the failing input line, marker, and exception string will be shown
+
+ Returns a multi-line string listing the ParserElements and/or function names in the
+ exception's stack trace.
+ """
+ import inspect
+ from .core import ParserElement
+
+ if depth is None:
+ depth = sys.getrecursionlimit()
+ ret = []
+ if isinstance(exc, ParseBaseException):
+ ret.append(exc.line)
+ ret.append(" " * (exc.column - 1) + "^")
+ ret.append("{}: {}".format(type(exc).__name__, exc))
+
+ if depth > 0:
+ callers = inspect.getinnerframes(exc.__traceback__, context=depth)
+ seen = set()
+ for i, ff in enumerate(callers[-depth:]):
+ frm = ff[0]
+
+ f_self = frm.f_locals.get("self", None)
+ if isinstance(f_self, ParserElement):
+ if frm.f_code.co_name not in ("parseImpl", "_parseNoCache"):
+ continue
+ if id(f_self) in seen:
+ continue
+ seen.add(id(f_self))
+
+ self_type = type(f_self)
+ ret.append(
+ "{}.{} - {}".format(
+ self_type.__module__, self_type.__name__, f_self
+ )
+ )
+
+ elif f_self is not None:
+ self_type = type(f_self)
+ ret.append("{}.{}".format(self_type.__module__, self_type.__name__))
+
+ else:
+ code = frm.f_code
+ if code.co_name in ("wrapper", "<module>"):
+ continue
+
+ ret.append("{}".format(code.co_name))
+
+ depth -= 1
+ if not depth:
+ break
+
+ return "\n".join(ret)
+
+ @classmethod
+ def _from_exception(cls, pe):
+ """
+ internal factory method to simplify creating one type of ParseException
+ from another - avoids having __init__ signature conflicts among subclasses
+ """
+ return cls(pe.pstr, pe.loc, pe.msg, pe.parserElement)
+
+ @property
+ def line(self) -> str:
+ """
+ Return the line of text where the exception occurred.
+ """
+ return line(self.loc, self.pstr)
+
+ @property
+ def lineno(self) -> int:
+ """
+ Return the 1-based line number of text where the exception occurred.
+ """
+ return lineno(self.loc, self.pstr)
+
+ @property
+ def col(self) -> int:
+ """
+ Return the 1-based column on the line of text where the exception occurred.
+ """
+ return col(self.loc, self.pstr)
+
+ @property
+ def column(self) -> int:
+ """
+ Return the 1-based column on the line of text where the exception occurred.
+ """
+ return col(self.loc, self.pstr)
+
+ def __str__(self) -> str:
+ if self.pstr:
+ if self.loc >= len(self.pstr):
+ foundstr = ", found end of text"
+ else:
+ # pull out next word at error location
+ found_match = _exception_word_extractor.match(self.pstr, self.loc)
+ if found_match is not None:
+ found = found_match.group(0)
+ else:
+ found = self.pstr[self.loc : self.loc + 1]
+ foundstr = (", found %r" % found).replace(r"\\", "\\")
+ else:
+ foundstr = ""
+ return "{}{} (at char {}), (line:{}, col:{})".format(
+ self.msg, foundstr, self.loc, self.lineno, self.column
+ )
+
+ def __repr__(self):
+ return str(self)
+
+ def mark_input_line(self, marker_string: str = None, *, markerString=">!<") -> str:
+ """
+ Extracts the exception line from the input string, and marks
+ the location of the exception with a special symbol.
+ """
+ markerString = marker_string if marker_string is not None else markerString
+ line_str = self.line
+ line_column = self.column - 1
+ if markerString:
+ line_str = "".join(
+ (line_str[:line_column], markerString, line_str[line_column:])
+ )
+ return line_str.strip()
+
+ def explain(self, depth=16) -> str:
+ """
+ Method to translate the Python internal traceback into a list
+ of the pyparsing expressions that caused the exception to be raised.
+
+ Parameters:
+
+ - depth (default=16) - number of levels back in the stack trace to list expression
+ and function names; if None, the full stack trace names will be listed; if 0, only
+ the failing input line, marker, and exception string will be shown
+
+ Returns a multi-line string listing the ParserElements and/or function names in the
+ exception's stack trace.
+
+ Example::
+
+ expr = pp.Word(pp.nums) * 3
+ try:
+ expr.parse_string("123 456 A789")
+ except pp.ParseException as pe:
+ print(pe.explain(depth=0))
+
+ prints::
+
+ 123 456 A789
+ ^
+ ParseException: Expected W:(0-9), found 'A' (at char 8), (line:1, col:9)
+
+ Note: the diagnostic output will include string representations of the expressions
+ that failed to parse. These representations will be more helpful if you use `set_name` to
+ give identifiable names to your expressions. Otherwise they will use the default string
+ forms, which may be cryptic to read.
+
+ Note: pyparsing's default truncation of exception tracebacks may also truncate the
+ stack of expressions that are displayed in the ``explain`` output. To get the full listing
+ of parser expressions, you may have to set ``ParserElement.verbose_stacktrace = True``
+ """
+ return self.explain_exception(self, depth)
+
+ markInputline = mark_input_line
+
+
+class ParseException(ParseBaseException):
+ """
+ Exception thrown when a parse expression doesn't match the input string
+
+ Example::
+
+ try:
+ Word(nums).set_name("integer").parse_string("ABC")
+ except ParseException as pe:
+ print(pe)
+ print("column: {}".format(pe.column))
+
+ prints::
+
+ Expected integer (at char 0), (line:1, col:1)
+ column: 1
+
+ """
+
+
+class ParseFatalException(ParseBaseException):
+ """
+ User-throwable exception thrown when inconsistent parse content
+ is found; stops all parsing immediately
+ """
+
+
+class ParseSyntaxException(ParseFatalException):
+ """
+ Just like :class:`ParseFatalException`, but thrown internally
+ when an :class:`ErrorStop<And._ErrorStop>` ('-' operator) indicates
+ that parsing is to stop immediately because an unbacktrackable
+ syntax error has been found.
+ """
+
+
+class RecursiveGrammarException(Exception):
+ """
+ Exception thrown by :class:`ParserElement.validate` if the
+ grammar could be left-recursive; parser may need to enable
+ left recursion using :class:`ParserElement.enable_left_recursion<ParserElement.enable_left_recursion>`
+ """
+
+ def __init__(self, parseElementList):
+ self.parseElementTrace = parseElementList
+
+ def __str__(self) -> str:
+ return "RecursiveGrammarException: {}".format(self.parseElementTrace)
diff --git a/setuptools/_vendor/pyparsing/helpers.py b/setuptools/_vendor/pyparsing/helpers.py
new file mode 100644
index 00000000..be8a3657
--- /dev/null
+++ b/setuptools/_vendor/pyparsing/helpers.py
@@ -0,0 +1,1083 @@
+# helpers.py
+import html.entities
+import re
+
+from . import __diag__
+from .core import *
+from .util import _bslash, _flatten, _escape_regex_range_chars
+
+
+#
+# global helpers
+#
+def delimited_list(
+ expr: Union[str, ParserElement],
+ delim: Union[str, ParserElement] = ",",
+ combine: bool = False,
+ min: OptionalType[int] = None,
+ max: OptionalType[int] = None,
+ *,
+ allow_trailing_delim: bool = False,
+) -> ParserElement:
+ """Helper to define a delimited list of expressions - the delimiter
+ defaults to ','. By default, the list elements and delimiters can
+ have intervening whitespace, and comments, but this can be
+ overridden by passing ``combine=True`` in the constructor. If
+ ``combine`` is set to ``True``, the matching tokens are
+ returned as a single token string, with the delimiters included;
+ otherwise, the matching tokens are returned as a list of tokens,
+ with the delimiters suppressed.
+
+ If ``allow_trailing_delim`` is set to True, then the list may end with
+ a delimiter.
+
+ Example::
+
+ delimited_list(Word(alphas)).parse_string("aa,bb,cc") # -> ['aa', 'bb', 'cc']
+ delimited_list(Word(hexnums), delim=':', combine=True).parse_string("AA:BB:CC:DD:EE") # -> ['AA:BB:CC:DD:EE']
+ """
+ if isinstance(expr, str_type):
+ expr = ParserElement._literalStringClass(expr)
+
+ dlName = "{expr} [{delim} {expr}]...{end}".format(
+ expr=str(expr.copy().streamline()),
+ delim=str(delim),
+ end=" [{}]".format(str(delim)) if allow_trailing_delim else "",
+ )
+
+ if not combine:
+ delim = Suppress(delim)
+
+ if min is not None:
+ if min < 1:
+ raise ValueError("min must be greater than 0")
+ min -= 1
+ if max is not None:
+ if min is not None and max <= min:
+ raise ValueError("max must be greater than, or equal to min")
+ max -= 1
+ delimited_list_expr = expr + (delim + expr)[min, max]
+
+ if allow_trailing_delim:
+ delimited_list_expr += Opt(delim)
+
+ if combine:
+ return Combine(delimited_list_expr).set_name(dlName)
+ else:
+ return delimited_list_expr.set_name(dlName)
+
+
+def counted_array(
+ expr: ParserElement,
+ int_expr: OptionalType[ParserElement] = None,
+ *,
+ intExpr: OptionalType[ParserElement] = None,
+) -> ParserElement:
+ """Helper to define a counted list of expressions.
+
+ This helper defines a pattern of the form::
+
+ integer expr expr expr...
+
+ where the leading integer tells how many expr expressions follow.
+ The matched tokens returns the array of expr tokens as a list - the
+ leading count token is suppressed.
+
+ If ``int_expr`` is specified, it should be a pyparsing expression
+ that produces an integer value.
+
+ Example::
+
+ counted_array(Word(alphas)).parse_string('2 ab cd ef') # -> ['ab', 'cd']
+
+ # in this parser, the leading integer value is given in binary,
+ # '10' indicating that 2 values are in the array
+ binary_constant = Word('01').set_parse_action(lambda t: int(t[0], 2))
+ counted_array(Word(alphas), int_expr=binary_constant).parse_string('10 ab cd ef') # -> ['ab', 'cd']
+
+ # if other fields must be parsed after the count but before the
+ # list items, give the fields results names and they will
+ # be preserved in the returned ParseResults:
+ count_with_metadata = integer + Word(alphas)("type")
+ typed_array = counted_array(Word(alphanums), int_expr=count_with_metadata)("items")
+ result = typed_array.parse_string("3 bool True True False")
+ print(result.dump())
+
+ # prints
+ # ['True', 'True', 'False']
+ # - items: ['True', 'True', 'False']
+ # - type: 'bool'
+ """
+ intExpr = intExpr or int_expr
+ array_expr = Forward()
+
+ def count_field_parse_action(s, l, t):
+ nonlocal array_expr
+ n = t[0]
+ array_expr <<= (expr * n) if n else Empty()
+ # clear list contents, but keep any named results
+ del t[:]
+
+ if intExpr is None:
+ intExpr = Word(nums).set_parse_action(lambda t: int(t[0]))
+ else:
+ intExpr = intExpr.copy()
+ intExpr.set_name("arrayLen")
+ intExpr.add_parse_action(count_field_parse_action, call_during_try=True)
+ return (intExpr + array_expr).set_name("(len) " + str(expr) + "...")
+
+
+def match_previous_literal(expr: ParserElement) -> ParserElement:
+ """Helper to define an expression that is indirectly defined from
+ the tokens matched in a previous expression, that is, it looks for
+ a 'repeat' of a previous expression. For example::
+
+ first = Word(nums)
+ second = match_previous_literal(first)
+ match_expr = first + ":" + second
+
+ will match ``"1:1"``, but not ``"1:2"``. Because this
+ matches a previous literal, will also match the leading
+ ``"1:1"`` in ``"1:10"``. If this is not desired, use
+ :class:`match_previous_expr`. Do *not* use with packrat parsing
+ enabled.
+ """
+ rep = Forward()
+
+ def copy_token_to_repeater(s, l, t):
+ if t:
+ if len(t) == 1:
+ rep << t[0]
+ else:
+ # flatten t tokens
+ tflat = _flatten(t.as_list())
+ rep << And(Literal(tt) for tt in tflat)
+ else:
+ rep << Empty()
+
+ expr.add_parse_action(copy_token_to_repeater, callDuringTry=True)
+ rep.set_name("(prev) " + str(expr))
+ return rep
+
+
+def match_previous_expr(expr: ParserElement) -> ParserElement:
+ """Helper to define an expression that is indirectly defined from
+ the tokens matched in a previous expression, that is, it looks for
+ a 'repeat' of a previous expression. For example::
+
+ first = Word(nums)
+ second = match_previous_expr(first)
+ match_expr = first + ":" + second
+
+ will match ``"1:1"``, but not ``"1:2"``. Because this
+ matches by expressions, will *not* match the leading ``"1:1"``
+ in ``"1:10"``; the expressions are evaluated first, and then
+ compared, so ``"1"`` is compared with ``"10"``. Do *not* use
+ with packrat parsing enabled.
+ """
+ rep = Forward()
+ e2 = expr.copy()
+ rep <<= e2
+
+ def copy_token_to_repeater(s, l, t):
+ matchTokens = _flatten(t.as_list())
+
+ def must_match_these_tokens(s, l, t):
+ theseTokens = _flatten(t.as_list())
+ if theseTokens != matchTokens:
+ raise ParseException(
+ s, l, "Expected {}, found{}".format(matchTokens, theseTokens)
+ )
+
+ rep.set_parse_action(must_match_these_tokens, callDuringTry=True)
+
+ expr.add_parse_action(copy_token_to_repeater, callDuringTry=True)
+ rep.set_name("(prev) " + str(expr))
+ return rep
+
+
+def one_of(
+ strs: Union[IterableType[str], str],
+ caseless: bool = False,
+ use_regex: bool = True,
+ as_keyword: bool = False,
+ *,
+ useRegex: bool = True,
+ asKeyword: bool = False,
+) -> ParserElement:
+ """Helper to quickly define a set of alternative :class:`Literal` s,
+ and makes sure to do longest-first testing when there is a conflict,
+ regardless of the input order, but returns
+ a :class:`MatchFirst` for best performance.
+
+ Parameters:
+
+ - ``strs`` - a string of space-delimited literals, or a collection of
+ string literals
+ - ``caseless`` - treat all literals as caseless - (default= ``False``)
+ - ``use_regex`` - as an optimization, will
+ generate a :class:`Regex` object; otherwise, will generate
+ a :class:`MatchFirst` object (if ``caseless=True`` or ``asKeyword=True``, or if
+ creating a :class:`Regex` raises an exception) - (default= ``True``)
+ - ``as_keyword`` - enforce :class:`Keyword`-style matching on the
+ generated expressions - (default= ``False``)
+ - ``asKeyword`` and ``useRegex`` are retained for pre-PEP8 compatibility,
+ but will be removed in a future release
+
+ Example::
+
+ comp_oper = one_of("< = > <= >= !=")
+ var = Word(alphas)
+ number = Word(nums)
+ term = var | number
+ comparison_expr = term + comp_oper + term
+ print(comparison_expr.search_string("B = 12 AA=23 B<=AA AA>12"))
+
+ prints::
+
+ [['B', '=', '12'], ['AA', '=', '23'], ['B', '<=', 'AA'], ['AA', '>', '12']]
+ """
+ asKeyword = asKeyword or as_keyword
+ useRegex = useRegex and use_regex
+
+ if (
+ isinstance(caseless, str_type)
+ and __diag__.warn_on_multiple_string_args_to_oneof
+ ):
+ warnings.warn(
+ "More than one string argument passed to one_of, pass"
+ " choices as a list or space-delimited string",
+ stacklevel=2,
+ )
+
+ if caseless:
+ isequal = lambda a, b: a.upper() == b.upper()
+ masks = lambda a, b: b.upper().startswith(a.upper())
+ parseElementClass = CaselessKeyword if asKeyword else CaselessLiteral
+ else:
+ isequal = lambda a, b: a == b
+ masks = lambda a, b: b.startswith(a)
+ parseElementClass = Keyword if asKeyword else Literal
+
+ symbols: List[str] = []
+ if isinstance(strs, str_type):
+ symbols = strs.split()
+ elif isinstance(strs, Iterable):
+ symbols = list(strs)
+ else:
+ raise TypeError("Invalid argument to one_of, expected string or iterable")
+ if not symbols:
+ return NoMatch()
+
+ # reorder given symbols to take care to avoid masking longer choices with shorter ones
+ # (but only if the given symbols are not just single characters)
+ if any(len(sym) > 1 for sym in symbols):
+ i = 0
+ while i < len(symbols) - 1:
+ cur = symbols[i]
+ for j, other in enumerate(symbols[i + 1 :]):
+ if isequal(other, cur):
+ del symbols[i + j + 1]
+ break
+ elif masks(cur, other):
+ del symbols[i + j + 1]
+ symbols.insert(i, other)
+ break
+ else:
+ i += 1
+
+ if useRegex:
+ re_flags: int = re.IGNORECASE if caseless else 0
+
+ try:
+ if all(len(sym) == 1 for sym in symbols):
+ # symbols are just single characters, create range regex pattern
+ patt = "[{}]".format(
+ "".join(_escape_regex_range_chars(sym) for sym in symbols)
+ )
+ else:
+ patt = "|".join(re.escape(sym) for sym in symbols)
+
+ # wrap with \b word break markers if defining as keywords
+ if asKeyword:
+ patt = r"\b(?:{})\b".format(patt)
+
+ ret = Regex(patt, flags=re_flags).set_name(" | ".join(symbols))
+
+ if caseless:
+ # add parse action to return symbols as specified, not in random
+ # casing as found in input string
+ symbol_map = {sym.lower(): sym for sym in symbols}
+ ret.add_parse_action(lambda s, l, t: symbol_map[t[0].lower()])
+
+ return ret
+
+ except re.error:
+ warnings.warn(
+ "Exception creating Regex for one_of, building MatchFirst", stacklevel=2
+ )
+
+ # last resort, just use MatchFirst
+ return MatchFirst(parseElementClass(sym) for sym in symbols).set_name(
+ " | ".join(symbols)
+ )
+
+
+def dict_of(key: ParserElement, value: ParserElement) -> ParserElement:
+ """Helper to easily and clearly define a dictionary by specifying
+ the respective patterns for the key and value. Takes care of
+ defining the :class:`Dict`, :class:`ZeroOrMore`, and
+ :class:`Group` tokens in the proper order. The key pattern
+ can include delimiting markers or punctuation, as long as they are
+ suppressed, thereby leaving the significant key text. The value
+ pattern can include named results, so that the :class:`Dict` results
+ can include named token fields.
+
+ Example::
+
+ text = "shape: SQUARE posn: upper left color: light blue texture: burlap"
+ attr_expr = (label + Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join))
+ print(OneOrMore(attr_expr).parse_string(text).dump())
+
+ attr_label = label
+ attr_value = Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join)
+
+ # similar to Dict, but simpler call format
+ result = dict_of(attr_label, attr_value).parse_string(text)
+ print(result.dump())
+ print(result['shape'])
+ print(result.shape) # object attribute access works too
+ print(result.as_dict())
+
+ prints::
+
+ [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']]
+ - color: 'light blue'
+ - posn: 'upper left'
+ - shape: 'SQUARE'
+ - texture: 'burlap'
+ SQUARE
+ SQUARE
+ {'color': 'light blue', 'shape': 'SQUARE', 'posn': 'upper left', 'texture': 'burlap'}
+ """
+ return Dict(OneOrMore(Group(key + value)))
+
+
+def original_text_for(
+ expr: ParserElement, as_string: bool = True, *, asString: bool = True
+) -> ParserElement:
+ """Helper to return the original, untokenized text for a given
+ expression. Useful to restore the parsed fields of an HTML start
+ tag into the raw tag text itself, or to revert separate tokens with
+ intervening whitespace back to the original matching input text. By
+ default, returns astring containing the original parsed text.
+
+ If the optional ``as_string`` argument is passed as
+ ``False``, then the return value is
+ a :class:`ParseResults` containing any results names that
+ were originally matched, and a single token containing the original
+ matched text from the input string. So if the expression passed to
+ :class:`original_text_for` contains expressions with defined
+ results names, you must set ``as_string`` to ``False`` if you
+ want to preserve those results name values.
+
+ The ``asString`` pre-PEP8 argument is retained for compatibility,
+ but will be removed in a future release.
+
+ Example::
+
+ src = "this is test <b> bold <i>text</i> </b> normal text "
+ for tag in ("b", "i"):
+ opener, closer = make_html_tags(tag)
+ patt = original_text_for(opener + SkipTo(closer) + closer)
+ print(patt.search_string(src)[0])
+
+ prints::
+
+ ['<b> bold <i>text</i> </b>']
+ ['<i>text</i>']
+ """
+ asString = asString and as_string
+
+ locMarker = Empty().set_parse_action(lambda s, loc, t: loc)
+ endlocMarker = locMarker.copy()
+ endlocMarker.callPreparse = False
+ matchExpr = locMarker("_original_start") + expr + endlocMarker("_original_end")
+ if asString:
+ extractText = lambda s, l, t: s[t._original_start : t._original_end]
+ else:
+
+ def extractText(s, l, t):
+ t[:] = [s[t.pop("_original_start") : t.pop("_original_end")]]
+
+ matchExpr.set_parse_action(extractText)
+ matchExpr.ignoreExprs = expr.ignoreExprs
+ matchExpr.suppress_warning(Diagnostics.warn_ungrouped_named_tokens_in_collection)
+ return matchExpr
+
+
+def ungroup(expr: ParserElement) -> ParserElement:
+ """Helper to undo pyparsing's default grouping of And expressions,
+ even if all but one are non-empty.
+ """
+ return TokenConverter(expr).add_parse_action(lambda t: t[0])
+
+
+def locatedExpr(expr: ParserElement) -> ParserElement:
+ """
+ (DEPRECATED - future code should use the Located class)
+ Helper to decorate a returned token with its starting and ending
+ locations in the input string.
+
+ This helper adds the following results names:
+
+ - ``locn_start`` - location where matched expression begins
+ - ``locn_end`` - location where matched expression ends
+ - ``value`` - the actual parsed results
+
+ Be careful if the input text contains ``<TAB>`` characters, you
+ may want to call :class:`ParserElement.parseWithTabs`
+
+ Example::
+
+ wd = Word(alphas)
+ for match in locatedExpr(wd).searchString("ljsdf123lksdjjf123lkkjj1222"):
+ print(match)
+
+ prints::
+
+ [[0, 'ljsdf', 5]]
+ [[8, 'lksdjjf', 15]]
+ [[18, 'lkkjj', 23]]
+ """
+ locator = Empty().set_parse_action(lambda ss, ll, tt: ll)
+ return Group(
+ locator("locn_start")
+ + expr("value")
+ + locator.copy().leaveWhitespace()("locn_end")
+ )
+
+
+def nested_expr(
+ opener: Union[str, ParserElement] = "(",
+ closer: Union[str, ParserElement] = ")",
+ content: OptionalType[ParserElement] = None,
+ ignore_expr: ParserElement = quoted_string(),
+ *,
+ ignoreExpr: ParserElement = quoted_string(),
+) -> ParserElement:
+ """Helper method for defining nested lists enclosed in opening and
+ closing delimiters (``"("`` and ``")"`` are the default).
+
+ Parameters:
+ - ``opener`` - opening character for a nested list
+ (default= ``"("``); can also be a pyparsing expression
+ - ``closer`` - closing character for a nested list
+ (default= ``")"``); can also be a pyparsing expression
+ - ``content`` - expression for items within the nested lists
+ (default= ``None``)
+ - ``ignore_expr`` - expression for ignoring opening and closing delimiters
+ (default= :class:`quoted_string`)
+ - ``ignoreExpr`` - this pre-PEP8 argument is retained for compatibility
+ but will be removed in a future release
+
+ If an expression is not provided for the content argument, the
+ nested expression will capture all whitespace-delimited content
+ between delimiters as a list of separate values.
+
+ Use the ``ignore_expr`` argument to define expressions that may
+ contain opening or closing characters that should not be treated as
+ opening or closing characters for nesting, such as quoted_string or
+ a comment expression. Specify multiple expressions using an
+ :class:`Or` or :class:`MatchFirst`. The default is
+ :class:`quoted_string`, but if no expressions are to be ignored, then
+ pass ``None`` for this argument.
+
+ Example::
+
+ data_type = one_of("void int short long char float double")
+ decl_data_type = Combine(data_type + Opt(Word('*')))
+ ident = Word(alphas+'_', alphanums+'_')
+ number = pyparsing_common.number
+ arg = Group(decl_data_type + ident)
+ LPAR, RPAR = map(Suppress, "()")
+
+ code_body = nested_expr('{', '}', ignore_expr=(quoted_string | c_style_comment))
+
+ c_function = (decl_data_type("type")
+ + ident("name")
+ + LPAR + Opt(delimited_list(arg), [])("args") + RPAR
+ + code_body("body"))
+ c_function.ignore(c_style_comment)
+
+ source_code = '''
+ int is_odd(int x) {
+ return (x%2);
+ }
+
+ int dec_to_hex(char hchar) {
+ if (hchar >= '0' && hchar <= '9') {
+ return (ord(hchar)-ord('0'));
+ } else {
+ return (10+ord(hchar)-ord('A'));
+ }
+ }
+ '''
+ for func in c_function.search_string(source_code):
+ print("%(name)s (%(type)s) args: %(args)s" % func)
+
+
+ prints::
+
+ is_odd (int) args: [['int', 'x']]
+ dec_to_hex (int) args: [['char', 'hchar']]
+ """
+ if ignoreExpr != ignore_expr:
+ ignoreExpr = ignore_expr if ignoreExpr == quoted_string() else ignoreExpr
+ if opener == closer:
+ raise ValueError("opening and closing strings cannot be the same")
+ if content is None:
+ if isinstance(opener, str_type) and isinstance(closer, str_type):
+ if len(opener) == 1 and len(closer) == 1:
+ if ignoreExpr is not None:
+ content = Combine(
+ OneOrMore(
+ ~ignoreExpr
+ + CharsNotIn(
+ opener + closer + ParserElement.DEFAULT_WHITE_CHARS,
+ exact=1,
+ )
+ )
+ ).set_parse_action(lambda t: t[0].strip())
+ else:
+ content = empty.copy() + CharsNotIn(
+ opener + closer + ParserElement.DEFAULT_WHITE_CHARS
+ ).set_parse_action(lambda t: t[0].strip())
+ else:
+ if ignoreExpr is not None:
+ content = Combine(
+ OneOrMore(
+ ~ignoreExpr
+ + ~Literal(opener)
+ + ~Literal(closer)
+ + CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS, exact=1)
+ )
+ ).set_parse_action(lambda t: t[0].strip())
+ else:
+ content = Combine(
+ OneOrMore(
+ ~Literal(opener)
+ + ~Literal(closer)
+ + CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS, exact=1)
+ )
+ ).set_parse_action(lambda t: t[0].strip())
+ else:
+ raise ValueError(
+ "opening and closing arguments must be strings if no content expression is given"
+ )
+ ret = Forward()
+ if ignoreExpr is not None:
+ ret <<= Group(
+ Suppress(opener) + ZeroOrMore(ignoreExpr | ret | content) + Suppress(closer)
+ )
+ else:
+ ret <<= Group(Suppress(opener) + ZeroOrMore(ret | content) + Suppress(closer))
+ ret.set_name("nested %s%s expression" % (opener, closer))
+ return ret
+
+
+def _makeTags(tagStr, xml, suppress_LT=Suppress("<"), suppress_GT=Suppress(">")):
+ """Internal helper to construct opening and closing tag expressions, given a tag name"""
+ if isinstance(tagStr, str_type):
+ resname = tagStr
+ tagStr = Keyword(tagStr, caseless=not xml)
+ else:
+ resname = tagStr.name
+
+ tagAttrName = Word(alphas, alphanums + "_-:")
+ if xml:
+ tagAttrValue = dbl_quoted_string.copy().set_parse_action(remove_quotes)
+ openTag = (
+ suppress_LT
+ + tagStr("tag")
+ + Dict(ZeroOrMore(Group(tagAttrName + Suppress("=") + tagAttrValue)))
+ + Opt("/", default=[False])("empty").set_parse_action(
+ lambda s, l, t: t[0] == "/"
+ )
+ + suppress_GT
+ )
+ else:
+ tagAttrValue = quoted_string.copy().set_parse_action(remove_quotes) | Word(
+ printables, exclude_chars=">"
+ )
+ openTag = (
+ suppress_LT
+ + tagStr("tag")
+ + Dict(
+ ZeroOrMore(
+ Group(
+ tagAttrName.set_parse_action(lambda t: t[0].lower())
+ + Opt(Suppress("=") + tagAttrValue)
+ )
+ )
+ )
+ + Opt("/", default=[False])("empty").set_parse_action(
+ lambda s, l, t: t[0] == "/"
+ )
+ + suppress_GT
+ )
+ closeTag = Combine(Literal("</") + tagStr + ">", adjacent=False)
+
+ openTag.set_name("<%s>" % resname)
+ # add start<tagname> results name in parse action now that ungrouped names are not reported at two levels
+ openTag.add_parse_action(
+ lambda t: t.__setitem__(
+ "start" + "".join(resname.replace(":", " ").title().split()), t.copy()
+ )
+ )
+ closeTag = closeTag(
+ "end" + "".join(resname.replace(":", " ").title().split())
+ ).set_name("</%s>" % resname)
+ openTag.tag = resname
+ closeTag.tag = resname
+ openTag.tag_body = SkipTo(closeTag())
+ return openTag, closeTag
+
+
+def make_html_tags(
+ tag_str: Union[str, ParserElement]
+) -> Tuple[ParserElement, ParserElement]:
+ """Helper to construct opening and closing tag expressions for HTML,
+ given a tag name. Matches tags in either upper or lower case,
+ attributes with namespaces and with quoted or unquoted values.
+
+ Example::
+
+ text = '<td>More info at the <a href="https://github.com/pyparsing/pyparsing/wiki">pyparsing</a> wiki page</td>'
+ # make_html_tags returns pyparsing expressions for the opening and
+ # closing tags as a 2-tuple
+ a, a_end = make_html_tags("A")
+ link_expr = a + SkipTo(a_end)("link_text") + a_end
+
+ for link in link_expr.search_string(text):
+ # attributes in the <A> tag (like "href" shown here) are
+ # also accessible as named results
+ print(link.link_text, '->', link.href)
+
+ prints::
+
+ pyparsing -> https://github.com/pyparsing/pyparsing/wiki
+ """
+ return _makeTags(tag_str, False)
+
+
+def make_xml_tags(
+ tag_str: Union[str, ParserElement]
+) -> Tuple[ParserElement, ParserElement]:
+ """Helper to construct opening and closing tag expressions for XML,
+ given a tag name. Matches tags only in the given upper/lower case.
+
+ Example: similar to :class:`make_html_tags`
+ """
+ return _makeTags(tag_str, True)
+
+
+any_open_tag, any_close_tag = make_html_tags(
+ Word(alphas, alphanums + "_:").set_name("any tag")
+)
+
+_htmlEntityMap = {k.rstrip(";"): v for k, v in html.entities.html5.items()}
+common_html_entity = Regex("&(?P<entity>" + "|".join(_htmlEntityMap) + ");").set_name(
+ "common HTML entity"
+)
+
+
+def replace_html_entity(t):
+ """Helper parser action to replace common HTML entities with their special characters"""
+ return _htmlEntityMap.get(t.entity)
+
+
+class OpAssoc(Enum):
+ LEFT = 1
+ RIGHT = 2
+
+
+InfixNotationOperatorArgType = Union[
+ ParserElement, str, Tuple[Union[ParserElement, str], Union[ParserElement, str]]
+]
+InfixNotationOperatorSpec = Union[
+ Tuple[
+ InfixNotationOperatorArgType,
+ int,
+ OpAssoc,
+ OptionalType[ParseAction],
+ ],
+ Tuple[
+ InfixNotationOperatorArgType,
+ int,
+ OpAssoc,
+ ],
+]
+
+
+def infix_notation(
+ base_expr: ParserElement,
+ op_list: List[InfixNotationOperatorSpec],
+ lpar: Union[str, ParserElement] = Suppress("("),
+ rpar: Union[str, ParserElement] = Suppress(")"),
+) -> ParserElement:
+ """Helper method for constructing grammars of expressions made up of
+ operators working in a precedence hierarchy. Operators may be unary
+ or binary, left- or right-associative. Parse actions can also be
+ attached to operator expressions. The generated parser will also
+ recognize the use of parentheses to override operator precedences
+ (see example below).
+
+ Note: if you define a deep operator list, you may see performance
+ issues when using infix_notation. See
+ :class:`ParserElement.enable_packrat` for a mechanism to potentially
+ improve your parser performance.
+
+ Parameters:
+ - ``base_expr`` - expression representing the most basic operand to
+ be used in the expression
+ - ``op_list`` - list of tuples, one for each operator precedence level
+ in the expression grammar; each tuple is of the form ``(op_expr,
+ num_operands, right_left_assoc, (optional)parse_action)``, where:
+
+ - ``op_expr`` is the pyparsing expression for the operator; may also
+ be a string, which will be converted to a Literal; if ``num_operands``
+ is 3, ``op_expr`` is a tuple of two expressions, for the two
+ operators separating the 3 terms
+ - ``num_operands`` is the number of terms for this operator (must be 1,
+ 2, or 3)
+ - ``right_left_assoc`` is the indicator whether the operator is right
+ or left associative, using the pyparsing-defined constants
+ ``OpAssoc.RIGHT`` and ``OpAssoc.LEFT``.
+ - ``parse_action`` is the parse action to be associated with
+ expressions matching this operator expression (the parse action
+ tuple member may be omitted); if the parse action is passed
+ a tuple or list of functions, this is equivalent to calling
+ ``set_parse_action(*fn)``
+ (:class:`ParserElement.set_parse_action`)
+ - ``lpar`` - expression for matching left-parentheses; if passed as a
+ str, then will be parsed as Suppress(lpar). If lpar is passed as
+ an expression (such as ``Literal('(')``), then it will be kept in
+ the parsed results, and grouped with them. (default= ``Suppress('(')``)
+ - ``rpar`` - expression for matching right-parentheses; if passed as a
+ str, then will be parsed as Suppress(rpar). If rpar is passed as
+ an expression (such as ``Literal(')')``), then it will be kept in
+ the parsed results, and grouped with them. (default= ``Suppress(')')``)
+
+ Example::
+
+ # simple example of four-function arithmetic with ints and
+ # variable names
+ integer = pyparsing_common.signed_integer
+ varname = pyparsing_common.identifier
+
+ arith_expr = infix_notation(integer | varname,
+ [
+ ('-', 1, OpAssoc.RIGHT),
+ (one_of('* /'), 2, OpAssoc.LEFT),
+ (one_of('+ -'), 2, OpAssoc.LEFT),
+ ])
+
+ arith_expr.run_tests('''
+ 5+3*6
+ (5+3)*6
+ -2--11
+ ''', full_dump=False)
+
+ prints::
+
+ 5+3*6
+ [[5, '+', [3, '*', 6]]]
+
+ (5+3)*6
+ [[[5, '+', 3], '*', 6]]
+
+ -2--11
+ [[['-', 2], '-', ['-', 11]]]
+ """
+ # captive version of FollowedBy that does not do parse actions or capture results names
+ class _FB(FollowedBy):
+ def parseImpl(self, instring, loc, doActions=True):
+ self.expr.try_parse(instring, loc)
+ return loc, []
+
+ _FB.__name__ = "FollowedBy>"
+
+ ret = Forward()
+ if isinstance(lpar, str):
+ lpar = Suppress(lpar)
+ if isinstance(rpar, str):
+ rpar = Suppress(rpar)
+
+ # if lpar and rpar are not suppressed, wrap in group
+ if not (isinstance(rpar, Suppress) and isinstance(rpar, Suppress)):
+ lastExpr = base_expr | Group(lpar + ret + rpar)
+ else:
+ lastExpr = base_expr | (lpar + ret + rpar)
+
+ for i, operDef in enumerate(op_list):
+ opExpr, arity, rightLeftAssoc, pa = (operDef + (None,))[:4]
+ if isinstance(opExpr, str_type):
+ opExpr = ParserElement._literalStringClass(opExpr)
+ if arity == 3:
+ if not isinstance(opExpr, (tuple, list)) or len(opExpr) != 2:
+ raise ValueError(
+ "if numterms=3, opExpr must be a tuple or list of two expressions"
+ )
+ opExpr1, opExpr2 = opExpr
+ term_name = "{}{} term".format(opExpr1, opExpr2)
+ else:
+ term_name = "{} term".format(opExpr)
+
+ if not 1 <= arity <= 3:
+ raise ValueError("operator must be unary (1), binary (2), or ternary (3)")
+
+ if rightLeftAssoc not in (OpAssoc.LEFT, OpAssoc.RIGHT):
+ raise ValueError("operator must indicate right or left associativity")
+
+ thisExpr = Forward().set_name(term_name)
+ if rightLeftAssoc is OpAssoc.LEFT:
+ if arity == 1:
+ matchExpr = _FB(lastExpr + opExpr) + Group(lastExpr + opExpr[1, ...])
+ elif arity == 2:
+ if opExpr is not None:
+ matchExpr = _FB(lastExpr + opExpr + lastExpr) + Group(
+ lastExpr + (opExpr + lastExpr)[1, ...]
+ )
+ else:
+ matchExpr = _FB(lastExpr + lastExpr) + Group(lastExpr[2, ...])
+ elif arity == 3:
+ matchExpr = _FB(
+ lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr
+ ) + Group(lastExpr + OneOrMore(opExpr1 + lastExpr + opExpr2 + lastExpr))
+ elif rightLeftAssoc is OpAssoc.RIGHT:
+ if arity == 1:
+ # try to avoid LR with this extra test
+ if not isinstance(opExpr, Opt):
+ opExpr = Opt(opExpr)
+ matchExpr = _FB(opExpr.expr + thisExpr) + Group(opExpr + thisExpr)
+ elif arity == 2:
+ if opExpr is not None:
+ matchExpr = _FB(lastExpr + opExpr + thisExpr) + Group(
+ lastExpr + (opExpr + thisExpr)[1, ...]
+ )
+ else:
+ matchExpr = _FB(lastExpr + thisExpr) + Group(
+ lastExpr + thisExpr[1, ...]
+ )
+ elif arity == 3:
+ matchExpr = _FB(
+ lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr
+ ) + Group(lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr)
+ if pa:
+ if isinstance(pa, (tuple, list)):
+ matchExpr.set_parse_action(*pa)
+ else:
+ matchExpr.set_parse_action(pa)
+ thisExpr <<= (matchExpr | lastExpr).setName(term_name)
+ lastExpr = thisExpr
+ ret <<= lastExpr
+ return ret
+
+
+def indentedBlock(blockStatementExpr, indentStack, indent=True, backup_stacks=[]):
+ """
+ (DEPRECATED - use IndentedBlock class instead)
+ Helper method for defining space-delimited indentation blocks,
+ such as those used to define block statements in Python source code.
+
+ Parameters:
+
+ - ``blockStatementExpr`` - expression defining syntax of statement that
+ is repeated within the indented block
+ - ``indentStack`` - list created by caller to manage indentation stack
+ (multiple ``statementWithIndentedBlock`` expressions within a single
+ grammar should share a common ``indentStack``)
+ - ``indent`` - boolean indicating whether block must be indented beyond
+ the current level; set to ``False`` for block of left-most statements
+ (default= ``True``)
+
+ A valid block must contain at least one ``blockStatement``.
+
+ (Note that indentedBlock uses internal parse actions which make it
+ incompatible with packrat parsing.)
+
+ Example::
+
+ data = '''
+ def A(z):
+ A1
+ B = 100
+ G = A2
+ A2
+ A3
+ B
+ def BB(a,b,c):
+ BB1
+ def BBA():
+ bba1
+ bba2
+ bba3
+ C
+ D
+ def spam(x,y):
+ def eggs(z):
+ pass
+ '''
+
+
+ indentStack = [1]
+ stmt = Forward()
+
+ identifier = Word(alphas, alphanums)
+ funcDecl = ("def" + identifier + Group("(" + Opt(delimitedList(identifier)) + ")") + ":")
+ func_body = indentedBlock(stmt, indentStack)
+ funcDef = Group(funcDecl + func_body)
+
+ rvalue = Forward()
+ funcCall = Group(identifier + "(" + Opt(delimitedList(rvalue)) + ")")
+ rvalue << (funcCall | identifier | Word(nums))
+ assignment = Group(identifier + "=" + rvalue)
+ stmt << (funcDef | assignment | identifier)
+
+ module_body = OneOrMore(stmt)
+
+ parseTree = module_body.parseString(data)
+ parseTree.pprint()
+
+ prints::
+
+ [['def',
+ 'A',
+ ['(', 'z', ')'],
+ ':',
+ [['A1'], [['B', '=', '100']], [['G', '=', 'A2']], ['A2'], ['A3']]],
+ 'B',
+ ['def',
+ 'BB',
+ ['(', 'a', 'b', 'c', ')'],
+ ':',
+ [['BB1'], [['def', 'BBA', ['(', ')'], ':', [['bba1'], ['bba2'], ['bba3']]]]]],
+ 'C',
+ 'D',
+ ['def',
+ 'spam',
+ ['(', 'x', 'y', ')'],
+ ':',
+ [[['def', 'eggs', ['(', 'z', ')'], ':', [['pass']]]]]]]
+ """
+ backup_stacks.append(indentStack[:])
+
+ def reset_stack():
+ indentStack[:] = backup_stacks[-1]
+
+ def checkPeerIndent(s, l, t):
+ if l >= len(s):
+ return
+ curCol = col(l, s)
+ if curCol != indentStack[-1]:
+ if curCol > indentStack[-1]:
+ raise ParseException(s, l, "illegal nesting")
+ raise ParseException(s, l, "not a peer entry")
+
+ def checkSubIndent(s, l, t):
+ curCol = col(l, s)
+ if curCol > indentStack[-1]:
+ indentStack.append(curCol)
+ else:
+ raise ParseException(s, l, "not a subentry")
+
+ def checkUnindent(s, l, t):
+ if l >= len(s):
+ return
+ curCol = col(l, s)
+ if not (indentStack and curCol in indentStack):
+ raise ParseException(s, l, "not an unindent")
+ if curCol < indentStack[-1]:
+ indentStack.pop()
+
+ NL = OneOrMore(LineEnd().set_whitespace_chars("\t ").suppress())
+ INDENT = (Empty() + Empty().set_parse_action(checkSubIndent)).set_name("INDENT")
+ PEER = Empty().set_parse_action(checkPeerIndent).set_name("")
+ UNDENT = Empty().set_parse_action(checkUnindent).set_name("UNINDENT")
+ if indent:
+ smExpr = Group(
+ Opt(NL)
+ + INDENT
+ + OneOrMore(PEER + Group(blockStatementExpr) + Opt(NL))
+ + UNDENT
+ )
+ else:
+ smExpr = Group(
+ Opt(NL)
+ + OneOrMore(PEER + Group(blockStatementExpr) + Opt(NL))
+ + Opt(UNDENT)
+ )
+
+ # add a parse action to remove backup_stack from list of backups
+ smExpr.add_parse_action(
+ lambda: backup_stacks.pop(-1) and None if backup_stacks else None
+ )
+ smExpr.set_fail_action(lambda a, b, c, d: reset_stack())
+ blockStatementExpr.ignore(_bslash + LineEnd())
+ return smExpr.set_name("indented block")
+
+
+# it's easy to get these comment structures wrong - they're very common, so may as well make them available
+c_style_comment = Combine(Regex(r"/\*(?:[^*]|\*(?!/))*") + "*/").set_name(
+ "C style comment"
+)
+"Comment of the form ``/* ... */``"
+
+html_comment = Regex(r"<!--[\s\S]*?-->").set_name("HTML comment")
+"Comment of the form ``<!-- ... -->``"
+
+rest_of_line = Regex(r".*").leave_whitespace().set_name("rest of line")
+dbl_slash_comment = Regex(r"//(?:\\\n|[^\n])*").set_name("// comment")
+"Comment of the form ``// ... (to end of line)``"
+
+cpp_style_comment = Combine(
+ Regex(r"/\*(?:[^*]|\*(?!/))*") + "*/" | dbl_slash_comment
+).set_name("C++ style comment")
+"Comment of either form :class:`c_style_comment` or :class:`dbl_slash_comment`"
+
+java_style_comment = cpp_style_comment
+"Same as :class:`cpp_style_comment`"
+
+python_style_comment = Regex(r"#.*").set_name("Python style comment")
+"Comment of the form ``# ... (to end of line)``"
+
+
+# build list of built-in expressions, for future reference if a global default value
+# gets updated
+_builtin_exprs = [v for v in vars().values() if isinstance(v, ParserElement)]
+
+
+# pre-PEP8 compatible names
+delimitedList = delimited_list
+countedArray = counted_array
+matchPreviousLiteral = match_previous_literal
+matchPreviousExpr = match_previous_expr
+oneOf = one_of
+dictOf = dict_of
+originalTextFor = original_text_for
+nestedExpr = nested_expr
+makeHTMLTags = make_html_tags
+makeXMLTags = make_xml_tags
+anyOpenTag, anyCloseTag = any_open_tag, any_close_tag
+commonHTMLEntity = common_html_entity
+replaceHTMLEntity = replace_html_entity
+opAssoc = OpAssoc
+infixNotation = infix_notation
+cStyleComment = c_style_comment
+htmlComment = html_comment
+restOfLine = rest_of_line
+dblSlashComment = dbl_slash_comment
+cppStyleComment = cpp_style_comment
+javaStyleComment = java_style_comment
+pythonStyleComment = python_style_comment
diff --git a/setuptools/_vendor/pyparsing/py.typed b/setuptools/_vendor/pyparsing/py.typed
new file mode 100644
index 00000000..e69de29b
--- /dev/null
+++ b/setuptools/_vendor/pyparsing/py.typed
diff --git a/setuptools/_vendor/pyparsing/results.py b/setuptools/_vendor/pyparsing/results.py
new file mode 100644
index 00000000..bb444df4
--- /dev/null
+++ b/setuptools/_vendor/pyparsing/results.py
@@ -0,0 +1,760 @@
+# results.py
+from collections.abc import MutableMapping, Mapping, MutableSequence, Iterator
+import pprint
+from weakref import ref as wkref
+from typing import Tuple, Any
+
+str_type: Tuple[type, ...] = (str, bytes)
+_generator_type = type((_ for _ in ()))
+
+
+class _ParseResultsWithOffset:
+ __slots__ = ["tup"]
+
+ def __init__(self, p1, p2):
+ self.tup = (p1, p2)
+
+ def __getitem__(self, i):
+ return self.tup[i]
+
+ def __getstate__(self):
+ return self.tup
+
+ def __setstate__(self, *args):
+ self.tup = args[0]
+
+
+class ParseResults:
+ """Structured parse results, to provide multiple means of access to
+ the parsed data:
+
+ - as a list (``len(results)``)
+ - by list index (``results[0], results[1]``, etc.)
+ - by attribute (``results.<results_name>`` - see :class:`ParserElement.set_results_name`)
+
+ Example::
+
+ integer = Word(nums)
+ date_str = (integer.set_results_name("year") + '/'
+ + integer.set_results_name("month") + '/'
+ + integer.set_results_name("day"))
+ # equivalent form:
+ # date_str = (integer("year") + '/'
+ # + integer("month") + '/'
+ # + integer("day"))
+
+ # parse_string returns a ParseResults object
+ result = date_str.parse_string("1999/12/31")
+
+ def test(s, fn=repr):
+ print("{} -> {}".format(s, fn(eval(s))))
+ test("list(result)")
+ test("result[0]")
+ test("result['month']")
+ test("result.day")
+ test("'month' in result")
+ test("'minutes' in result")
+ test("result.dump()", str)
+
+ prints::
+
+ list(result) -> ['1999', '/', '12', '/', '31']
+ result[0] -> '1999'
+ result['month'] -> '12'
+ result.day -> '31'
+ 'month' in result -> True
+ 'minutes' in result -> False
+ result.dump() -> ['1999', '/', '12', '/', '31']
+ - day: '31'
+ - month: '12'
+ - year: '1999'
+ """
+
+ _null_values: Tuple[Any, ...] = (None, [], "", ())
+
+ __slots__ = [
+ "_name",
+ "_parent",
+ "_all_names",
+ "_modal",
+ "_toklist",
+ "_tokdict",
+ "__weakref__",
+ ]
+
+ class List(list):
+ """
+ Simple wrapper class to distinguish parsed list results that should be preserved
+ as actual Python lists, instead of being converted to :class:`ParseResults`:
+
+ LBRACK, RBRACK = map(pp.Suppress, "[]")
+ element = pp.Forward()
+ item = ppc.integer
+ element_list = LBRACK + pp.delimited_list(element) + RBRACK
+
+ # add parse actions to convert from ParseResults to actual Python collection types
+ def as_python_list(t):
+ return pp.ParseResults.List(t.as_list())
+ element_list.add_parse_action(as_python_list)
+
+ element <<= item | element_list
+
+ element.run_tests('''
+ 100
+ [2,3,4]
+ [[2, 1],3,4]
+ [(2, 1),3,4]
+ (2,3,4)
+ ''', post_parse=lambda s, r: (r[0], type(r[0])))
+
+ prints:
+
+ 100
+ (100, <class 'int'>)
+
+ [2,3,4]
+ ([2, 3, 4], <class 'list'>)
+
+ [[2, 1],3,4]
+ ([[2, 1], 3, 4], <class 'list'>)
+
+ (Used internally by :class:`Group` when `aslist=True`.)
+ """
+
+ def __new__(cls, contained=None):
+ if contained is None:
+ contained = []
+
+ if not isinstance(contained, list):
+ raise TypeError(
+ "{} may only be constructed with a list,"
+ " not {}".format(cls.__name__, type(contained).__name__)
+ )
+
+ return list.__new__(cls)
+
+ def __new__(cls, toklist=None, name=None, **kwargs):
+ if isinstance(toklist, ParseResults):
+ return toklist
+ self = object.__new__(cls)
+ self._name = None
+ self._parent = None
+ self._all_names = set()
+
+ if toklist is None:
+ self._toklist = []
+ elif isinstance(toklist, (list, _generator_type)):
+ self._toklist = (
+ [toklist[:]]
+ if isinstance(toklist, ParseResults.List)
+ else list(toklist)
+ )
+ else:
+ self._toklist = [toklist]
+ self._tokdict = dict()
+ return self
+
+ # Performance tuning: we construct a *lot* of these, so keep this
+ # constructor as small and fast as possible
+ def __init__(
+ self, toklist=None, name=None, asList=True, modal=True, isinstance=isinstance
+ ):
+ self._modal = modal
+ if name is not None and name != "":
+ if isinstance(name, int):
+ name = str(name)
+ if not modal:
+ self._all_names = {name}
+ self._name = name
+ if toklist not in self._null_values:
+ if isinstance(toklist, (str_type, type)):
+ toklist = [toklist]
+ if asList:
+ if isinstance(toklist, ParseResults):
+ self[name] = _ParseResultsWithOffset(
+ ParseResults(toklist._toklist), 0
+ )
+ else:
+ self[name] = _ParseResultsWithOffset(
+ ParseResults(toklist[0]), 0
+ )
+ self[name]._name = name
+ else:
+ try:
+ self[name] = toklist[0]
+ except (KeyError, TypeError, IndexError):
+ if toklist is not self:
+ self[name] = toklist
+ else:
+ self._name = name
+
+ def __getitem__(self, i):
+ if isinstance(i, (int, slice)):
+ return self._toklist[i]
+ else:
+ if i not in self._all_names:
+ return self._tokdict[i][-1][0]
+ else:
+ return ParseResults([v[0] for v in self._tokdict[i]])
+
+ def __setitem__(self, k, v, isinstance=isinstance):
+ if isinstance(v, _ParseResultsWithOffset):
+ self._tokdict[k] = self._tokdict.get(k, list()) + [v]
+ sub = v[0]
+ elif isinstance(k, (int, slice)):
+ self._toklist[k] = v
+ sub = v
+ else:
+ self._tokdict[k] = self._tokdict.get(k, list()) + [
+ _ParseResultsWithOffset(v, 0)
+ ]
+ sub = v
+ if isinstance(sub, ParseResults):
+ sub._parent = wkref(self)
+
+ def __delitem__(self, i):
+ if isinstance(i, (int, slice)):
+ mylen = len(self._toklist)
+ del self._toklist[i]
+
+ # convert int to slice
+ if isinstance(i, int):
+ if i < 0:
+ i += mylen
+ i = slice(i, i + 1)
+ # get removed indices
+ removed = list(range(*i.indices(mylen)))
+ removed.reverse()
+ # fixup indices in token dictionary
+ for name, occurrences in self._tokdict.items():
+ for j in removed:
+ for k, (value, position) in enumerate(occurrences):
+ occurrences[k] = _ParseResultsWithOffset(
+ value, position - (position > j)
+ )
+ else:
+ del self._tokdict[i]
+
+ def __contains__(self, k) -> bool:
+ return k in self._tokdict
+
+ def __len__(self) -> int:
+ return len(self._toklist)
+
+ def __bool__(self) -> bool:
+ return not not (self._toklist or self._tokdict)
+
+ def __iter__(self) -> Iterator:
+ return iter(self._toklist)
+
+ def __reversed__(self) -> Iterator:
+ return iter(self._toklist[::-1])
+
+ def keys(self):
+ return iter(self._tokdict)
+
+ def values(self):
+ return (self[k] for k in self.keys())
+
+ def items(self):
+ return ((k, self[k]) for k in self.keys())
+
+ def haskeys(self) -> bool:
+ """
+ Since ``keys()`` returns an iterator, this method is helpful in bypassing
+ code that looks for the existence of any defined results names."""
+ return bool(self._tokdict)
+
+ def pop(self, *args, **kwargs):
+ """
+ Removes and returns item at specified index (default= ``last``).
+ Supports both ``list`` and ``dict`` semantics for ``pop()``. If
+ passed no argument or an integer argument, it will use ``list``
+ semantics and pop tokens from the list of parsed tokens. If passed
+ a non-integer argument (most likely a string), it will use ``dict``
+ semantics and pop the corresponding value from any defined results
+ names. A second default return value argument is supported, just as in
+ ``dict.pop()``.
+
+ Example::
+
+ numlist = Word(nums)[...]
+ print(numlist.parse_string("0 123 321")) # -> ['0', '123', '321']
+
+ def remove_first(tokens):
+ tokens.pop(0)
+ numlist.add_parse_action(remove_first)
+ print(numlist.parse_string("0 123 321")) # -> ['123', '321']
+
+ label = Word(alphas)
+ patt = label("LABEL") + OneOrMore(Word(nums))
+ print(patt.parse_string("AAB 123 321").dump())
+
+ # Use pop() in a parse action to remove named result (note that corresponding value is not
+ # removed from list form of results)
+ def remove_LABEL(tokens):
+ tokens.pop("LABEL")
+ return tokens
+ patt.add_parse_action(remove_LABEL)
+ print(patt.parse_string("AAB 123 321").dump())
+
+ prints::
+
+ ['AAB', '123', '321']
+ - LABEL: 'AAB'
+
+ ['AAB', '123', '321']
+ """
+ if not args:
+ args = [-1]
+ for k, v in kwargs.items():
+ if k == "default":
+ args = (args[0], v)
+ else:
+ raise TypeError(
+ "pop() got an unexpected keyword argument {!r}".format(k)
+ )
+ if isinstance(args[0], int) or len(args) == 1 or args[0] in self:
+ index = args[0]
+ ret = self[index]
+ del self[index]
+ return ret
+ else:
+ defaultvalue = args[1]
+ return defaultvalue
+
+ def get(self, key, default_value=None):
+ """
+ Returns named result matching the given key, or if there is no
+ such name, then returns the given ``default_value`` or ``None`` if no
+ ``default_value`` is specified.
+
+ Similar to ``dict.get()``.
+
+ Example::
+
+ integer = Word(nums)
+ date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
+
+ result = date_str.parse_string("1999/12/31")
+ print(result.get("year")) # -> '1999'
+ print(result.get("hour", "not specified")) # -> 'not specified'
+ print(result.get("hour")) # -> None
+ """
+ if key in self:
+ return self[key]
+ else:
+ return default_value
+
+ def insert(self, index, ins_string):
+ """
+ Inserts new element at location index in the list of parsed tokens.
+
+ Similar to ``list.insert()``.
+
+ Example::
+
+ numlist = Word(nums)[...]
+ print(numlist.parse_string("0 123 321")) # -> ['0', '123', '321']
+
+ # use a parse action to insert the parse location in the front of the parsed results
+ def insert_locn(locn, tokens):
+ tokens.insert(0, locn)
+ numlist.add_parse_action(insert_locn)
+ print(numlist.parse_string("0 123 321")) # -> [0, '0', '123', '321']
+ """
+ self._toklist.insert(index, ins_string)
+ # fixup indices in token dictionary
+ for name, occurrences in self._tokdict.items():
+ for k, (value, position) in enumerate(occurrences):
+ occurrences[k] = _ParseResultsWithOffset(
+ value, position + (position > index)
+ )
+
+ def append(self, item):
+ """
+ Add single element to end of ``ParseResults`` list of elements.
+
+ Example::
+
+ numlist = Word(nums)[...]
+ print(numlist.parse_string("0 123 321")) # -> ['0', '123', '321']
+
+ # use a parse action to compute the sum of the parsed integers, and add it to the end
+ def append_sum(tokens):
+ tokens.append(sum(map(int, tokens)))
+ numlist.add_parse_action(append_sum)
+ print(numlist.parse_string("0 123 321")) # -> ['0', '123', '321', 444]
+ """
+ self._toklist.append(item)
+
+ def extend(self, itemseq):
+ """
+ Add sequence of elements to end of ``ParseResults`` list of elements.
+
+ Example::
+
+ patt = OneOrMore(Word(alphas))
+
+ # use a parse action to append the reverse of the matched strings, to make a palindrome
+ def make_palindrome(tokens):
+ tokens.extend(reversed([t[::-1] for t in tokens]))
+ return ''.join(tokens)
+ patt.add_parse_action(make_palindrome)
+ print(patt.parse_string("lskdj sdlkjf lksd")) # -> 'lskdjsdlkjflksddsklfjkldsjdksl'
+ """
+ if isinstance(itemseq, ParseResults):
+ self.__iadd__(itemseq)
+ else:
+ self._toklist.extend(itemseq)
+
+ def clear(self):
+ """
+ Clear all elements and results names.
+ """
+ del self._toklist[:]
+ self._tokdict.clear()
+
+ def __getattr__(self, name):
+ try:
+ return self[name]
+ except KeyError:
+ if name.startswith("__"):
+ raise AttributeError(name)
+ return ""
+
+ def __add__(self, other) -> "ParseResults":
+ ret = self.copy()
+ ret += other
+ return ret
+
+ def __iadd__(self, other) -> "ParseResults":
+ if other._tokdict:
+ offset = len(self._toklist)
+ addoffset = lambda a: offset if a < 0 else a + offset
+ otheritems = other._tokdict.items()
+ otherdictitems = [
+ (k, _ParseResultsWithOffset(v[0], addoffset(v[1])))
+ for k, vlist in otheritems
+ for v in vlist
+ ]
+ for k, v in otherdictitems:
+ self[k] = v
+ if isinstance(v[0], ParseResults):
+ v[0]._parent = wkref(self)
+
+ self._toklist += other._toklist
+ self._all_names |= other._all_names
+ return self
+
+ def __radd__(self, other) -> "ParseResults":
+ if isinstance(other, int) and other == 0:
+ # useful for merging many ParseResults using sum() builtin
+ return self.copy()
+ else:
+ # this may raise a TypeError - so be it
+ return other + self
+
+ def __repr__(self) -> str:
+ return "{}({!r}, {})".format(type(self).__name__, self._toklist, self.as_dict())
+
+ def __str__(self) -> str:
+ return (
+ "["
+ + ", ".join(
+ [
+ str(i) if isinstance(i, ParseResults) else repr(i)
+ for i in self._toklist
+ ]
+ )
+ + "]"
+ )
+
+ def _asStringList(self, sep=""):
+ out = []
+ for item in self._toklist:
+ if out and sep:
+ out.append(sep)
+ if isinstance(item, ParseResults):
+ out += item._asStringList()
+ else:
+ out.append(str(item))
+ return out
+
+ def as_list(self) -> list:
+ """
+ Returns the parse results as a nested list of matching tokens, all converted to strings.
+
+ Example::
+
+ patt = OneOrMore(Word(alphas))
+ result = patt.parse_string("sldkj lsdkj sldkj")
+ # even though the result prints in string-like form, it is actually a pyparsing ParseResults
+ print(type(result), result) # -> <class 'pyparsing.ParseResults'> ['sldkj', 'lsdkj', 'sldkj']
+
+ # Use as_list() to create an actual list
+ result_list = result.as_list()
+ print(type(result_list), result_list) # -> <class 'list'> ['sldkj', 'lsdkj', 'sldkj']
+ """
+ return [
+ res.as_list() if isinstance(res, ParseResults) else res
+ for res in self._toklist
+ ]
+
+ def as_dict(self) -> dict:
+ """
+ Returns the named parse results as a nested dictionary.
+
+ Example::
+
+ integer = Word(nums)
+ date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
+
+ result = date_str.parse_string('12/31/1999')
+ print(type(result), repr(result)) # -> <class 'pyparsing.ParseResults'> (['12', '/', '31', '/', '1999'], {'day': [('1999', 4)], 'year': [('12', 0)], 'month': [('31', 2)]})
+
+ result_dict = result.as_dict()
+ print(type(result_dict), repr(result_dict)) # -> <class 'dict'> {'day': '1999', 'year': '12', 'month': '31'}
+
+ # even though a ParseResults supports dict-like access, sometime you just need to have a dict
+ import json
+ print(json.dumps(result)) # -> Exception: TypeError: ... is not JSON serializable
+ print(json.dumps(result.as_dict())) # -> {"month": "31", "day": "1999", "year": "12"}
+ """
+
+ def to_item(obj):
+ if isinstance(obj, ParseResults):
+ return obj.as_dict() if obj.haskeys() else [to_item(v) for v in obj]
+ else:
+ return obj
+
+ return dict((k, to_item(v)) for k, v in self.items())
+
+ def copy(self) -> "ParseResults":
+ """
+ Returns a new copy of a :class:`ParseResults` object.
+ """
+ ret = ParseResults(self._toklist)
+ ret._tokdict = self._tokdict.copy()
+ ret._parent = self._parent
+ ret._all_names |= self._all_names
+ ret._name = self._name
+ return ret
+
+ def get_name(self):
+ r"""
+ Returns the results name for this token expression. Useful when several
+ different expressions might match at a particular location.
+
+ Example::
+
+ integer = Word(nums)
+ ssn_expr = Regex(r"\d\d\d-\d\d-\d\d\d\d")
+ house_number_expr = Suppress('#') + Word(nums, alphanums)
+ user_data = (Group(house_number_expr)("house_number")
+ | Group(ssn_expr)("ssn")
+ | Group(integer)("age"))
+ user_info = OneOrMore(user_data)
+
+ result = user_info.parse_string("22 111-22-3333 #221B")
+ for item in result:
+ print(item.get_name(), ':', item[0])
+
+ prints::
+
+ age : 22
+ ssn : 111-22-3333
+ house_number : 221B
+ """
+ if self._name:
+ return self._name
+ elif self._parent:
+ par = self._parent()
+
+ def find_in_parent(sub):
+ return next(
+ (
+ k
+ for k, vlist in par._tokdict.items()
+ for v, loc in vlist
+ if sub is v
+ ),
+ None,
+ )
+
+ return find_in_parent(self) if par else None
+ elif (
+ len(self) == 1
+ and len(self._tokdict) == 1
+ and next(iter(self._tokdict.values()))[0][1] in (0, -1)
+ ):
+ return next(iter(self._tokdict.keys()))
+ else:
+ return None
+
+ def dump(self, indent="", full=True, include_list=True, _depth=0) -> str:
+ """
+ Diagnostic method for listing out the contents of
+ a :class:`ParseResults`. Accepts an optional ``indent`` argument so
+ that this string can be embedded in a nested display of other data.
+
+ Example::
+
+ integer = Word(nums)
+ date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
+
+ result = date_str.parse_string('1999/12/31')
+ print(result.dump())
+
+ prints::
+
+ ['1999', '/', '12', '/', '31']
+ - day: '31'
+ - month: '12'
+ - year: '1999'
+ """
+ out = []
+ NL = "\n"
+ out.append(indent + str(self.as_list()) if include_list else "")
+
+ if full:
+ if self.haskeys():
+ items = sorted((str(k), v) for k, v in self.items())
+ for k, v in items:
+ if out:
+ out.append(NL)
+ out.append("{}{}- {}: ".format(indent, (" " * _depth), k))
+ if isinstance(v, ParseResults):
+ if v:
+ out.append(
+ v.dump(
+ indent=indent,
+ full=full,
+ include_list=include_list,
+ _depth=_depth + 1,
+ )
+ )
+ else:
+ out.append(str(v))
+ else:
+ out.append(repr(v))
+ if any(isinstance(vv, ParseResults) for vv in self):
+ v = self
+ for i, vv in enumerate(v):
+ if isinstance(vv, ParseResults):
+ out.append(
+ "\n{}{}[{}]:\n{}{}{}".format(
+ indent,
+ (" " * (_depth)),
+ i,
+ indent,
+ (" " * (_depth + 1)),
+ vv.dump(
+ indent=indent,
+ full=full,
+ include_list=include_list,
+ _depth=_depth + 1,
+ ),
+ )
+ )
+ else:
+ out.append(
+ "\n%s%s[%d]:\n%s%s%s"
+ % (
+ indent,
+ (" " * (_depth)),
+ i,
+ indent,
+ (" " * (_depth + 1)),
+ str(vv),
+ )
+ )
+
+ return "".join(out)
+
+ def pprint(self, *args, **kwargs):
+ """
+ Pretty-printer for parsed results as a list, using the
+ `pprint <https://docs.python.org/3/library/pprint.html>`_ module.
+ Accepts additional positional or keyword args as defined for
+ `pprint.pprint <https://docs.python.org/3/library/pprint.html#pprint.pprint>`_ .
+
+ Example::
+
+ ident = Word(alphas, alphanums)
+ num = Word(nums)
+ func = Forward()
+ term = ident | num | Group('(' + func + ')')
+ func <<= ident + Group(Optional(delimited_list(term)))
+ result = func.parse_string("fna a,b,(fnb c,d,200),100")
+ result.pprint(width=40)
+
+ prints::
+
+ ['fna',
+ ['a',
+ 'b',
+ ['(', 'fnb', ['c', 'd', '200'], ')'],
+ '100']]
+ """
+ pprint.pprint(self.as_list(), *args, **kwargs)
+
+ # add support for pickle protocol
+ def __getstate__(self):
+ return (
+ self._toklist,
+ (
+ self._tokdict.copy(),
+ self._parent is not None and self._parent() or None,
+ self._all_names,
+ self._name,
+ ),
+ )
+
+ def __setstate__(self, state):
+ self._toklist, (self._tokdict, par, inAccumNames, self._name) = state
+ self._all_names = set(inAccumNames)
+ if par is not None:
+ self._parent = wkref(par)
+ else:
+ self._parent = None
+
+ def __getnewargs__(self):
+ return self._toklist, self._name
+
+ def __dir__(self):
+ return dir(type(self)) + list(self.keys())
+
+ @classmethod
+ def from_dict(cls, other, name=None) -> "ParseResults":
+ """
+ Helper classmethod to construct a ``ParseResults`` from a ``dict``, preserving the
+ name-value relations as results names. If an optional ``name`` argument is
+ given, a nested ``ParseResults`` will be returned.
+ """
+
+ def is_iterable(obj):
+ try:
+ iter(obj)
+ except Exception:
+ return False
+ else:
+ return not isinstance(obj, str_type)
+
+ ret = cls([])
+ for k, v in other.items():
+ if isinstance(v, Mapping):
+ ret += cls.from_dict(v, name=k)
+ else:
+ ret += cls([v], name=k, asList=is_iterable(v))
+ if name is not None:
+ ret = cls([ret], name=name)
+ return ret
+
+ asList = as_list
+ asDict = as_dict
+ getName = get_name
+
+
+MutableMapping.register(ParseResults)
+MutableSequence.register(ParseResults)
diff --git a/setuptools/_vendor/pyparsing/testing.py b/setuptools/_vendor/pyparsing/testing.py
new file mode 100644
index 00000000..991972f3
--- /dev/null
+++ b/setuptools/_vendor/pyparsing/testing.py
@@ -0,0 +1,331 @@
+# testing.py
+
+from contextlib import contextmanager
+from typing import Optional
+
+from .core import (
+ ParserElement,
+ ParseException,
+ Keyword,
+ __diag__,
+ __compat__,
+)
+
+
+class pyparsing_test:
+ """
+ namespace class for classes useful in writing unit tests
+ """
+
+ class reset_pyparsing_context:
+ """
+ Context manager to be used when writing unit tests that modify pyparsing config values:
+ - packrat parsing
+ - bounded recursion parsing
+ - default whitespace characters.
+ - default keyword characters
+ - literal string auto-conversion class
+ - __diag__ settings
+
+ Example::
+
+ with reset_pyparsing_context():
+ # test that literals used to construct a grammar are automatically suppressed
+ ParserElement.inlineLiteralsUsing(Suppress)
+
+ term = Word(alphas) | Word(nums)
+ group = Group('(' + term[...] + ')')
+
+ # assert that the '()' characters are not included in the parsed tokens
+ self.assertParseAndCheckList(group, "(abc 123 def)", ['abc', '123', 'def'])
+
+ # after exiting context manager, literals are converted to Literal expressions again
+ """
+
+ def __init__(self):
+ self._save_context = {}
+
+ def save(self):
+ self._save_context["default_whitespace"] = ParserElement.DEFAULT_WHITE_CHARS
+ self._save_context["default_keyword_chars"] = Keyword.DEFAULT_KEYWORD_CHARS
+
+ self._save_context[
+ "literal_string_class"
+ ] = ParserElement._literalStringClass
+
+ self._save_context["verbose_stacktrace"] = ParserElement.verbose_stacktrace
+
+ self._save_context["packrat_enabled"] = ParserElement._packratEnabled
+ if ParserElement._packratEnabled:
+ self._save_context[
+ "packrat_cache_size"
+ ] = ParserElement.packrat_cache.size
+ else:
+ self._save_context["packrat_cache_size"] = None
+ self._save_context["packrat_parse"] = ParserElement._parse
+ self._save_context[
+ "recursion_enabled"
+ ] = ParserElement._left_recursion_enabled
+
+ self._save_context["__diag__"] = {
+ name: getattr(__diag__, name) for name in __diag__._all_names
+ }
+
+ self._save_context["__compat__"] = {
+ "collect_all_And_tokens": __compat__.collect_all_And_tokens
+ }
+
+ return self
+
+ def restore(self):
+ # reset pyparsing global state
+ if (
+ ParserElement.DEFAULT_WHITE_CHARS
+ != self._save_context["default_whitespace"]
+ ):
+ ParserElement.set_default_whitespace_chars(
+ self._save_context["default_whitespace"]
+ )
+
+ ParserElement.verbose_stacktrace = self._save_context["verbose_stacktrace"]
+
+ Keyword.DEFAULT_KEYWORD_CHARS = self._save_context["default_keyword_chars"]
+ ParserElement.inlineLiteralsUsing(
+ self._save_context["literal_string_class"]
+ )
+
+ for name, value in self._save_context["__diag__"].items():
+ (__diag__.enable if value else __diag__.disable)(name)
+
+ ParserElement._packratEnabled = False
+ if self._save_context["packrat_enabled"]:
+ ParserElement.enable_packrat(self._save_context["packrat_cache_size"])
+ else:
+ ParserElement._parse = self._save_context["packrat_parse"]
+ ParserElement._left_recursion_enabled = self._save_context[
+ "recursion_enabled"
+ ]
+
+ __compat__.collect_all_And_tokens = self._save_context["__compat__"]
+
+ return self
+
+ def copy(self):
+ ret = type(self)()
+ ret._save_context.update(self._save_context)
+ return ret
+
+ def __enter__(self):
+ return self.save()
+
+ def __exit__(self, *args):
+ self.restore()
+
+ class TestParseResultsAsserts:
+ """
+ A mixin class to add parse results assertion methods to normal unittest.TestCase classes.
+ """
+
+ def assertParseResultsEquals(
+ self, result, expected_list=None, expected_dict=None, msg=None
+ ):
+ """
+ Unit test assertion to compare a :class:`ParseResults` object with an optional ``expected_list``,
+ and compare any defined results names with an optional ``expected_dict``.
+ """
+ if expected_list is not None:
+ self.assertEqual(expected_list, result.as_list(), msg=msg)
+ if expected_dict is not None:
+ self.assertEqual(expected_dict, result.as_dict(), msg=msg)
+
+ def assertParseAndCheckList(
+ self, expr, test_string, expected_list, msg=None, verbose=True
+ ):
+ """
+ Convenience wrapper assert to test a parser element and input string, and assert that
+ the resulting ``ParseResults.asList()`` is equal to the ``expected_list``.
+ """
+ result = expr.parse_string(test_string, parse_all=True)
+ if verbose:
+ print(result.dump())
+ else:
+ print(result.as_list())
+ self.assertParseResultsEquals(result, expected_list=expected_list, msg=msg)
+
+ def assertParseAndCheckDict(
+ self, expr, test_string, expected_dict, msg=None, verbose=True
+ ):
+ """
+ Convenience wrapper assert to test a parser element and input string, and assert that
+ the resulting ``ParseResults.asDict()`` is equal to the ``expected_dict``.
+ """
+ result = expr.parse_string(test_string, parseAll=True)
+ if verbose:
+ print(result.dump())
+ else:
+ print(result.as_list())
+ self.assertParseResultsEquals(result, expected_dict=expected_dict, msg=msg)
+
+ def assertRunTestResults(
+ self, run_tests_report, expected_parse_results=None, msg=None
+ ):
+ """
+ Unit test assertion to evaluate output of ``ParserElement.runTests()``. If a list of
+ list-dict tuples is given as the ``expected_parse_results`` argument, then these are zipped
+ with the report tuples returned by ``runTests`` and evaluated using ``assertParseResultsEquals``.
+ Finally, asserts that the overall ``runTests()`` success value is ``True``.
+
+ :param run_tests_report: tuple(bool, [tuple(str, ParseResults or Exception)]) returned from runTests
+ :param expected_parse_results (optional): [tuple(str, list, dict, Exception)]
+ """
+ run_test_success, run_test_results = run_tests_report
+
+ if expected_parse_results is not None:
+ merged = [
+ (*rpt, expected)
+ for rpt, expected in zip(run_test_results, expected_parse_results)
+ ]
+ for test_string, result, expected in merged:
+ # expected should be a tuple containing a list and/or a dict or an exception,
+ # and optional failure message string
+ # an empty tuple will skip any result validation
+ fail_msg = next(
+ (exp for exp in expected if isinstance(exp, str)), None
+ )
+ expected_exception = next(
+ (
+ exp
+ for exp in expected
+ if isinstance(exp, type) and issubclass(exp, Exception)
+ ),
+ None,
+ )
+ if expected_exception is not None:
+ with self.assertRaises(
+ expected_exception=expected_exception, msg=fail_msg or msg
+ ):
+ if isinstance(result, Exception):
+ raise result
+ else:
+ expected_list = next(
+ (exp for exp in expected if isinstance(exp, list)), None
+ )
+ expected_dict = next(
+ (exp for exp in expected if isinstance(exp, dict)), None
+ )
+ if (expected_list, expected_dict) != (None, None):
+ self.assertParseResultsEquals(
+ result,
+ expected_list=expected_list,
+ expected_dict=expected_dict,
+ msg=fail_msg or msg,
+ )
+ else:
+ # warning here maybe?
+ print("no validation for {!r}".format(test_string))
+
+ # do this last, in case some specific test results can be reported instead
+ self.assertTrue(
+ run_test_success, msg=msg if msg is not None else "failed runTests"
+ )
+
+ @contextmanager
+ def assertRaisesParseException(self, exc_type=ParseException, msg=None):
+ with self.assertRaises(exc_type, msg=msg):
+ yield
+
+ @staticmethod
+ def with_line_numbers(
+ s: str,
+ start_line: Optional[int] = None,
+ end_line: Optional[int] = None,
+ expand_tabs: bool = True,
+ eol_mark: str = "|",
+ mark_spaces: Optional[str] = None,
+ mark_control: Optional[str] = None,
+ ) -> str:
+ """
+ Helpful method for debugging a parser - prints a string with line and column numbers.
+ (Line and column numbers are 1-based.)
+
+ :param s: tuple(bool, str - string to be printed with line and column numbers
+ :param start_line: int - (optional) starting line number in s to print (default=1)
+ :param end_line: int - (optional) ending line number in s to print (default=len(s))
+ :param expand_tabs: bool - (optional) expand tabs to spaces, to match the pyparsing default
+ :param eol_mark: str - (optional) string to mark the end of lines, helps visualize trailing spaces (default="|")
+ :param mark_spaces: str - (optional) special character to display in place of spaces
+ :param mark_control: str - (optional) convert non-printing control characters to a placeholding
+ character; valid values:
+ - "unicode" - replaces control chars with Unicode symbols, such as "␍" and "␊"
+ - any single character string - replace control characters with given string
+ - None (default) - string is displayed as-is
+
+ :return: str - input string with leading line numbers and column number headers
+ """
+ if expand_tabs:
+ s = s.expandtabs()
+ if mark_control is not None:
+ if mark_control == "unicode":
+ tbl = str.maketrans(
+ {c: u for c, u in zip(range(0, 33), range(0x2400, 0x2433))}
+ | {127: 0x2421}
+ )
+ eol_mark = ""
+ else:
+ tbl = str.maketrans(
+ {c: mark_control for c in list(range(0, 32)) + [127]}
+ )
+ s = s.translate(tbl)
+ if mark_spaces is not None and mark_spaces != " ":
+ if mark_spaces == "unicode":
+ tbl = str.maketrans({9: 0x2409, 32: 0x2423})
+ s = s.translate(tbl)
+ else:
+ s = s.replace(" ", mark_spaces)
+ if start_line is None:
+ start_line = 1
+ if end_line is None:
+ end_line = len(s)
+ end_line = min(end_line, len(s))
+ start_line = min(max(1, start_line), end_line)
+
+ if mark_control != "unicode":
+ s_lines = s.splitlines()[start_line - 1 : end_line]
+ else:
+ s_lines = [line + "␊" for line in s.split("␊")[start_line - 1 : end_line]]
+ if not s_lines:
+ return ""
+
+ lineno_width = len(str(end_line))
+ max_line_len = max(len(line) for line in s_lines)
+ lead = " " * (lineno_width + 1)
+ if max_line_len >= 99:
+ header0 = (
+ lead
+ + "".join(
+ "{}{}".format(" " * 99, (i + 1) % 100)
+ for i in range(max(max_line_len // 100, 1))
+ )
+ + "\n"
+ )
+ else:
+ header0 = ""
+ header1 = (
+ header0
+ + lead
+ + "".join(
+ " {}".format((i + 1) % 10)
+ for i in range(-(-max_line_len // 10))
+ )
+ + "\n"
+ )
+ header2 = lead + "1234567890" * (-(-max_line_len // 10)) + "\n"
+ return (
+ header1
+ + header2
+ + "\n".join(
+ "{:{}d}:{}{}".format(i, lineno_width, line, eol_mark)
+ for i, line in enumerate(s_lines, start=start_line)
+ )
+ + "\n"
+ )
diff --git a/setuptools/_vendor/pyparsing/unicode.py b/setuptools/_vendor/pyparsing/unicode.py
new file mode 100644
index 00000000..92261487
--- /dev/null
+++ b/setuptools/_vendor/pyparsing/unicode.py
@@ -0,0 +1,332 @@
+# unicode.py
+
+import sys
+from itertools import filterfalse
+from typing import List, Tuple, Union
+
+
+class _lazyclassproperty:
+ def __init__(self, fn):
+ self.fn = fn
+ self.__doc__ = fn.__doc__
+ self.__name__ = fn.__name__
+
+ def __get__(self, obj, cls):
+ if cls is None:
+ cls = type(obj)
+ if not hasattr(cls, "_intern") or any(
+ cls._intern is getattr(superclass, "_intern", [])
+ for superclass in cls.__mro__[1:]
+ ):
+ cls._intern = {}
+ attrname = self.fn.__name__
+ if attrname not in cls._intern:
+ cls._intern[attrname] = self.fn(cls)
+ return cls._intern[attrname]
+
+
+UnicodeRangeList = List[Union[Tuple[int, int], Tuple[int]]]
+
+
+class unicode_set:
+ """
+ A set of Unicode characters, for language-specific strings for
+ ``alphas``, ``nums``, ``alphanums``, and ``printables``.
+ A unicode_set is defined by a list of ranges in the Unicode character
+ set, in a class attribute ``_ranges``. Ranges can be specified using
+ 2-tuples or a 1-tuple, such as::
+
+ _ranges = [
+ (0x0020, 0x007e),
+ (0x00a0, 0x00ff),
+ (0x0100,),
+ ]
+
+ Ranges are left- and right-inclusive. A 1-tuple of (x,) is treated as (x, x).
+
+ A unicode set can also be defined using multiple inheritance of other unicode sets::
+
+ class CJK(Chinese, Japanese, Korean):
+ pass
+ """
+
+ _ranges: UnicodeRangeList = []
+
+ @_lazyclassproperty
+ def _chars_for_ranges(cls):
+ ret = []
+ for cc in cls.__mro__:
+ if cc is unicode_set:
+ break
+ for rr in getattr(cc, "_ranges", ()):
+ ret.extend(range(rr[0], rr[-1] + 1))
+ return [chr(c) for c in sorted(set(ret))]
+
+ @_lazyclassproperty
+ def printables(cls):
+ "all non-whitespace characters in this range"
+ return "".join(filterfalse(str.isspace, cls._chars_for_ranges))
+
+ @_lazyclassproperty
+ def alphas(cls):
+ "all alphabetic characters in this range"
+ return "".join(filter(str.isalpha, cls._chars_for_ranges))
+
+ @_lazyclassproperty
+ def nums(cls):
+ "all numeric digit characters in this range"
+ return "".join(filter(str.isdigit, cls._chars_for_ranges))
+
+ @_lazyclassproperty
+ def alphanums(cls):
+ "all alphanumeric characters in this range"
+ return cls.alphas + cls.nums
+
+ @_lazyclassproperty
+ def identchars(cls):
+ "all characters in this range that are valid identifier characters, plus underscore '_'"
+ return "".join(
+ sorted(
+ set(
+ "".join(filter(str.isidentifier, cls._chars_for_ranges))
+ + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzªµº"
+ + "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ"
+ + "_"
+ )
+ )
+ )
+
+ @_lazyclassproperty
+ def identbodychars(cls):
+ """
+ all characters in this range that are valid identifier body characters,
+ plus the digits 0-9
+ """
+ return "".join(
+ sorted(
+ set(
+ cls.identchars
+ + "0123456789"
+ + "".join(
+ [c for c in cls._chars_for_ranges if ("_" + c).isidentifier()]
+ )
+ )
+ )
+ )
+
+
+class pyparsing_unicode(unicode_set):
+ """
+ A namespace class for defining common language unicode_sets.
+ """
+
+ _ranges: UnicodeRangeList = [(32, sys.maxunicode)]
+
+ class Latin1(unicode_set):
+ "Unicode set for Latin-1 Unicode Character Range"
+ _ranges: UnicodeRangeList = [
+ (0x0020, 0x007E),
+ (0x00A0, 0x00FF),
+ ]
+
+ class LatinA(unicode_set):
+ "Unicode set for Latin-A Unicode Character Range"
+ _ranges: UnicodeRangeList = [
+ (0x0100, 0x017F),
+ ]
+
+ class LatinB(unicode_set):
+ "Unicode set for Latin-B Unicode Character Range"
+ _ranges: UnicodeRangeList = [
+ (0x0180, 0x024F),
+ ]
+
+ class Greek(unicode_set):
+ "Unicode set for Greek Unicode Character Ranges"
+ _ranges: UnicodeRangeList = [
+ (0x0342, 0x0345),
+ (0x0370, 0x0377),
+ (0x037A, 0x037F),
+ (0x0384, 0x038A),
+ (0x038C,),
+ (0x038E, 0x03A1),
+ (0x03A3, 0x03E1),
+ (0x03F0, 0x03FF),
+ (0x1D26, 0x1D2A),
+ (0x1D5E,),
+ (0x1D60,),
+ (0x1D66, 0x1D6A),
+ (0x1F00, 0x1F15),
+ (0x1F18, 0x1F1D),
+ (0x1F20, 0x1F45),
+ (0x1F48, 0x1F4D),
+ (0x1F50, 0x1F57),
+ (0x1F59,),
+ (0x1F5B,),
+ (0x1F5D,),
+ (0x1F5F, 0x1F7D),
+ (0x1F80, 0x1FB4),
+ (0x1FB6, 0x1FC4),
+ (0x1FC6, 0x1FD3),
+ (0x1FD6, 0x1FDB),
+ (0x1FDD, 0x1FEF),
+ (0x1FF2, 0x1FF4),
+ (0x1FF6, 0x1FFE),
+ (0x2129,),
+ (0x2719, 0x271A),
+ (0xAB65,),
+ (0x10140, 0x1018D),
+ (0x101A0,),
+ (0x1D200, 0x1D245),
+ (0x1F7A1, 0x1F7A7),
+ ]
+
+ class Cyrillic(unicode_set):
+ "Unicode set for Cyrillic Unicode Character Range"
+ _ranges: UnicodeRangeList = [
+ (0x0400, 0x052F),
+ (0x1C80, 0x1C88),
+ (0x1D2B,),
+ (0x1D78,),
+ (0x2DE0, 0x2DFF),
+ (0xA640, 0xA672),
+ (0xA674, 0xA69F),
+ (0xFE2E, 0xFE2F),
+ ]
+
+ class Chinese(unicode_set):
+ "Unicode set for Chinese Unicode Character Range"
+ _ranges: UnicodeRangeList = [
+ (0x2E80, 0x2E99),
+ (0x2E9B, 0x2EF3),
+ (0x31C0, 0x31E3),
+ (0x3400, 0x4DB5),
+ (0x4E00, 0x9FEF),
+ (0xA700, 0xA707),
+ (0xF900, 0xFA6D),
+ (0xFA70, 0xFAD9),
+ (0x16FE2, 0x16FE3),
+ (0x1F210, 0x1F212),
+ (0x1F214, 0x1F23B),
+ (0x1F240, 0x1F248),
+ (0x20000, 0x2A6D6),
+ (0x2A700, 0x2B734),
+ (0x2B740, 0x2B81D),
+ (0x2B820, 0x2CEA1),
+ (0x2CEB0, 0x2EBE0),
+ (0x2F800, 0x2FA1D),
+ ]
+
+ class Japanese(unicode_set):
+ "Unicode set for Japanese Unicode Character Range, combining Kanji, Hiragana, and Katakana ranges"
+ _ranges: UnicodeRangeList = []
+
+ class Kanji(unicode_set):
+ "Unicode set for Kanji Unicode Character Range"
+ _ranges: UnicodeRangeList = [
+ (0x4E00, 0x9FBF),
+ (0x3000, 0x303F),
+ ]
+
+ class Hiragana(unicode_set):
+ "Unicode set for Hiragana Unicode Character Range"
+ _ranges: UnicodeRangeList = [
+ (0x3041, 0x3096),
+ (0x3099, 0x30A0),
+ (0x30FC,),
+ (0xFF70,),
+ (0x1B001,),
+ (0x1B150, 0x1B152),
+ (0x1F200,),
+ ]
+
+ class Katakana(unicode_set):
+ "Unicode set for Katakana Unicode Character Range"
+ _ranges: UnicodeRangeList = [
+ (0x3099, 0x309C),
+ (0x30A0, 0x30FF),
+ (0x31F0, 0x31FF),
+ (0x32D0, 0x32FE),
+ (0xFF65, 0xFF9F),
+ (0x1B000,),
+ (0x1B164, 0x1B167),
+ (0x1F201, 0x1F202),
+ (0x1F213,),
+ ]
+
+ class Hangul(unicode_set):
+ "Unicode set for Hangul (Korean) Unicode Character Range"
+ _ranges: UnicodeRangeList = [
+ (0x1100, 0x11FF),
+ (0x302E, 0x302F),
+ (0x3131, 0x318E),
+ (0x3200, 0x321C),
+ (0x3260, 0x327B),
+ (0x327E,),
+ (0xA960, 0xA97C),
+ (0xAC00, 0xD7A3),
+ (0xD7B0, 0xD7C6),
+ (0xD7CB, 0xD7FB),
+ (0xFFA0, 0xFFBE),
+ (0xFFC2, 0xFFC7),
+ (0xFFCA, 0xFFCF),
+ (0xFFD2, 0xFFD7),
+ (0xFFDA, 0xFFDC),
+ ]
+
+ Korean = Hangul
+
+ class CJK(Chinese, Japanese, Hangul):
+ "Unicode set for combined Chinese, Japanese, and Korean (CJK) Unicode Character Range"
+ pass
+
+ class Thai(unicode_set):
+ "Unicode set for Thai Unicode Character Range"
+ _ranges: UnicodeRangeList = [(0x0E01, 0x0E3A), (0x0E3F, 0x0E5B)]
+
+ class Arabic(unicode_set):
+ "Unicode set for Arabic Unicode Character Range"
+ _ranges: UnicodeRangeList = [
+ (0x0600, 0x061B),
+ (0x061E, 0x06FF),
+ (0x0700, 0x077F),
+ ]
+
+ class Hebrew(unicode_set):
+ "Unicode set for Hebrew Unicode Character Range"
+ _ranges: UnicodeRangeList = [
+ (0x0591, 0x05C7),
+ (0x05D0, 0x05EA),
+ (0x05EF, 0x05F4),
+ (0xFB1D, 0xFB36),
+ (0xFB38, 0xFB3C),
+ (0xFB3E,),
+ (0xFB40, 0xFB41),
+ (0xFB43, 0xFB44),
+ (0xFB46, 0xFB4F),
+ ]
+
+ class Devanagari(unicode_set):
+ "Unicode set for Devanagari Unicode Character Range"
+ _ranges: UnicodeRangeList = [(0x0900, 0x097F), (0xA8E0, 0xA8FF)]
+
+
+pyparsing_unicode.Japanese._ranges = (
+ pyparsing_unicode.Japanese.Kanji._ranges
+ + pyparsing_unicode.Japanese.Hiragana._ranges
+ + pyparsing_unicode.Japanese.Katakana._ranges
+)
+
+# define ranges in language character sets
+pyparsing_unicode.العربية = pyparsing_unicode.Arabic
+pyparsing_unicode.中文 = pyparsing_unicode.Chinese
+pyparsing_unicode.кириллица = pyparsing_unicode.Cyrillic
+pyparsing_unicode.Ελληνικά = pyparsing_unicode.Greek
+pyparsing_unicode.עִברִית = pyparsing_unicode.Hebrew
+pyparsing_unicode.日本語 = pyparsing_unicode.Japanese
+pyparsing_unicode.Japanese.漢字 = pyparsing_unicode.Japanese.Kanji
+pyparsing_unicode.Japanese.カタカナ = pyparsing_unicode.Japanese.Katakana
+pyparsing_unicode.Japanese.ひらがな = pyparsing_unicode.Japanese.Hiragana
+pyparsing_unicode.한국어 = pyparsing_unicode.Korean
+pyparsing_unicode.ไทย = pyparsing_unicode.Thai
+pyparsing_unicode.देवनागरी = pyparsing_unicode.Devanagari
diff --git a/setuptools/_vendor/pyparsing/util.py b/setuptools/_vendor/pyparsing/util.py
new file mode 100644
index 00000000..34ce092c
--- /dev/null
+++ b/setuptools/_vendor/pyparsing/util.py
@@ -0,0 +1,235 @@
+# util.py
+import warnings
+import types
+import collections
+import itertools
+from functools import lru_cache
+from typing import List, Union, Iterable
+
+_bslash = chr(92)
+
+
+class __config_flags:
+ """Internal class for defining compatibility and debugging flags"""
+
+ _all_names: List[str] = []
+ _fixed_names: List[str] = []
+ _type_desc = "configuration"
+
+ @classmethod
+ def _set(cls, dname, value):
+ if dname in cls._fixed_names:
+ warnings.warn(
+ "{}.{} {} is {} and cannot be overridden".format(
+ cls.__name__,
+ dname,
+ cls._type_desc,
+ str(getattr(cls, dname)).upper(),
+ )
+ )
+ return
+ if dname in cls._all_names:
+ setattr(cls, dname, value)
+ else:
+ raise ValueError("no such {} {!r}".format(cls._type_desc, dname))
+
+ enable = classmethod(lambda cls, name: cls._set(name, True))
+ disable = classmethod(lambda cls, name: cls._set(name, False))
+
+
+@lru_cache(maxsize=128)
+def col(loc: int, strg: str) -> int:
+ """
+ Returns current column within a string, counting newlines as line separators.
+ The first column is number 1.
+
+ Note: the default parsing behavior is to expand tabs in the input string
+ before starting the parsing process. See
+ :class:`ParserElement.parseString` for more
+ information on parsing strings containing ``<TAB>`` s, and suggested
+ methods to maintain a consistent view of the parsed string, the parse
+ location, and line and column positions within the parsed string.
+ """
+ s = strg
+ return 1 if 0 < loc < len(s) and s[loc - 1] == "\n" else loc - s.rfind("\n", 0, loc)
+
+
+@lru_cache(maxsize=128)
+def lineno(loc: int, strg: str) -> int:
+ """Returns current line number within a string, counting newlines as line separators.
+ The first line is number 1.
+
+ Note - the default parsing behavior is to expand tabs in the input string
+ before starting the parsing process. See :class:`ParserElement.parseString`
+ for more information on parsing strings containing ``<TAB>`` s, and
+ suggested methods to maintain a consistent view of the parsed string, the
+ parse location, and line and column positions within the parsed string.
+ """
+ return strg.count("\n", 0, loc) + 1
+
+
+@lru_cache(maxsize=128)
+def line(loc: int, strg: str) -> str:
+ """
+ Returns the line of text containing loc within a string, counting newlines as line separators.
+ """
+ last_cr = strg.rfind("\n", 0, loc)
+ next_cr = strg.find("\n", loc)
+ return strg[last_cr + 1 : next_cr] if next_cr >= 0 else strg[last_cr + 1 :]
+
+
+class _UnboundedCache:
+ def __init__(self):
+ cache = {}
+ cache_get = cache.get
+ self.not_in_cache = not_in_cache = object()
+
+ def get(_, key):
+ return cache_get(key, not_in_cache)
+
+ def set_(_, key, value):
+ cache[key] = value
+
+ def clear(_):
+ cache.clear()
+
+ self.size = None
+ self.get = types.MethodType(get, self)
+ self.set = types.MethodType(set_, self)
+ self.clear = types.MethodType(clear, self)
+
+
+class _FifoCache:
+ def __init__(self, size):
+ self.not_in_cache = not_in_cache = object()
+ cache = collections.OrderedDict()
+ cache_get = cache.get
+
+ def get(_, key):
+ return cache_get(key, not_in_cache)
+
+ def set_(_, key, value):
+ cache[key] = value
+ while len(cache) > size:
+ cache.popitem(last=False)
+
+ def clear(_):
+ cache.clear()
+
+ self.size = size
+ self.get = types.MethodType(get, self)
+ self.set = types.MethodType(set_, self)
+ self.clear = types.MethodType(clear, self)
+
+
+class LRUMemo:
+ """
+ A memoizing mapping that retains `capacity` deleted items
+
+ The memo tracks retained items by their access order; once `capacity` items
+ are retained, the least recently used item is discarded.
+ """
+
+ def __init__(self, capacity):
+ self._capacity = capacity
+ self._active = {}
+ self._memory = collections.OrderedDict()
+
+ def __getitem__(self, key):
+ try:
+ return self._active[key]
+ except KeyError:
+ self._memory.move_to_end(key)
+ return self._memory[key]
+
+ def __setitem__(self, key, value):
+ self._memory.pop(key, None)
+ self._active[key] = value
+
+ def __delitem__(self, key):
+ try:
+ value = self._active.pop(key)
+ except KeyError:
+ pass
+ else:
+ while len(self._memory) >= self._capacity:
+ self._memory.popitem(last=False)
+ self._memory[key] = value
+
+ def clear(self):
+ self._active.clear()
+ self._memory.clear()
+
+
+class UnboundedMemo(dict):
+ """
+ A memoizing mapping that retains all deleted items
+ """
+
+ def __delitem__(self, key):
+ pass
+
+
+def _escape_regex_range_chars(s: str) -> str:
+ # escape these chars: ^-[]
+ for c in r"\^-[]":
+ s = s.replace(c, _bslash + c)
+ s = s.replace("\n", r"\n")
+ s = s.replace("\t", r"\t")
+ return str(s)
+
+
+def _collapse_string_to_ranges(
+ s: Union[str, Iterable[str]], re_escape: bool = True
+) -> str:
+ def is_consecutive(c):
+ c_int = ord(c)
+ is_consecutive.prev, prev = c_int, is_consecutive.prev
+ if c_int - prev > 1:
+ is_consecutive.value = next(is_consecutive.counter)
+ return is_consecutive.value
+
+ is_consecutive.prev = 0
+ is_consecutive.counter = itertools.count()
+ is_consecutive.value = -1
+
+ def escape_re_range_char(c):
+ return "\\" + c if c in r"\^-][" else c
+
+ def no_escape_re_range_char(c):
+ return c
+
+ if not re_escape:
+ escape_re_range_char = no_escape_re_range_char
+
+ ret = []
+ s = "".join(sorted(set(s)))
+ if len(s) > 3:
+ for _, chars in itertools.groupby(s, key=is_consecutive):
+ first = last = next(chars)
+ last = collections.deque(
+ itertools.chain(iter([last]), chars), maxlen=1
+ ).pop()
+ if first == last:
+ ret.append(escape_re_range_char(first))
+ else:
+ sep = "" if ord(last) == ord(first) + 1 else "-"
+ ret.append(
+ "{}{}{}".format(
+ escape_re_range_char(first), sep, escape_re_range_char(last)
+ )
+ )
+ else:
+ ret = [escape_re_range_char(c) for c in s]
+
+ return "".join(ret)
+
+
+def _flatten(ll: list) -> list:
+ ret = []
+ for i in ll:
+ if isinstance(i, list):
+ ret.extend(_flatten(i))
+ else:
+ ret.append(i)
+ return ret
diff --git a/setuptools/_vendor/vendored.txt b/setuptools/_vendor/vendored.txt
index b08b0d6f..95de2dc5 100644
--- a/setuptools/_vendor/vendored.txt
+++ b/setuptools/_vendor/vendored.txt
@@ -1,5 +1,5 @@
packaging==21.3
-pyparsing==2.2.1
+pyparsing==3.0.8
ordered-set==3.1.1
more_itertools==8.8.0
jaraco.text==3.7.0
diff --git a/setuptools/command/build.py b/setuptools/command/build.py
new file mode 100644
index 00000000..12a43622
--- /dev/null
+++ b/setuptools/command/build.py
@@ -0,0 +1,24 @@
+from distutils.command.build import build as _build
+import warnings
+
+from setuptools import SetuptoolsDeprecationWarning
+
+
+_ORIGINAL_SUBCOMMANDS = {"build_py", "build_clib", "build_ext", "build_scripts"}
+
+
+class build(_build):
+ # copy to avoid sharing the object with parent class
+ sub_commands = _build.sub_commands[:]
+
+ def run(self):
+ subcommands = {cmd[0] for cmd in _build.sub_commands}
+ if subcommands - _ORIGINAL_SUBCOMMANDS:
+ msg = """
+ It seems that you are using `distutils.command.build` to add
+ new subcommands. Using `distutils` directly is considered deprecated,
+ please use `setuptools.command.build`.
+ """
+ warnings.warn(msg, SetuptoolsDeprecationWarning)
+ self.sub_commands = _build.sub_commands
+ super().run()
diff --git a/setuptools/command/build_py.py b/setuptools/command/build_py.py
index c3fdc092..2fced3d6 100644
--- a/setuptools/command/build_py.py
+++ b/setuptools/command/build_py.py
@@ -1,3 +1,4 @@
+from functools import partial
from glob import glob
from distutils.util import convert_path
import distutils.command.build_py as orig
@@ -8,6 +9,9 @@ import io
import distutils.errors
import itertools
import stat
+import warnings
+from pathlib import Path
+from setuptools._deprecation_warning import SetuptoolsDeprecationWarning
from setuptools.extern.more_itertools import unique_everseen
@@ -98,7 +102,7 @@ class build_py(orig.build_py):
package,
src_dir,
)
- globs_expanded = map(glob, patterns)
+ globs_expanded = map(partial(glob, recursive=True), patterns)
# flatten the expanded globs into an iterable of matches
globs_matches = itertools.chain.from_iterable(globs_expanded)
glob_files = filter(os.path.isfile, globs_matches)
@@ -129,6 +133,7 @@ class build_py(orig.build_py):
src_dirs[assert_relative(self.get_package_dir(package))] = package
self.run_command('egg_info')
+ check = _IncludePackageDataAbuse()
ei_cmd = self.get_finalized_command('egg_info')
for path in ei_cmd.filelist.files:
d, f = os.path.split(assert_relative(path))
@@ -139,8 +144,13 @@ class build_py(orig.build_py):
d, df = os.path.split(d)
f = os.path.join(df, f)
if d in src_dirs:
- if path.endswith('.py') and f == oldf:
- continue # it's a module, not data
+ if f == oldf:
+ if check.is_module(f):
+ continue # it's a module, not data
+ else:
+ importable = check.importable_subpackage(src_dirs[d], f)
+ if importable:
+ check.warn(importable)
mf.setdefault(src_dirs[d], []).append(path)
def get_data_files(self):
@@ -240,3 +250,49 @@ def assert_relative(path):
% path
)
raise DistutilsSetupError(msg)
+
+
+class _IncludePackageDataAbuse:
+ """Inform users that package or module is included as 'data file'"""
+
+ MESSAGE = """\
+ Installing {importable!r} as data is deprecated, please list it in `packages`.
+ !!\n\n
+ ############################
+ # Package would be ignored #
+ ############################
+ Python recognizes {importable!r} as an importable package,
+ but it is not listed in the `packages` configuration of setuptools.
+
+ {importable!r} has been automatically added to the distribution only
+ because it may contain data files, but this behavior is likely to change
+ in future versions of setuptools (and therefore is considered deprecated).
+
+ Please make sure that {importable!r} is included as a package by using
+ the `packages` configuration field or the proper discovery methods
+ (for example by using `find_namespace_packages(...)`/`find_namespace:`
+ instead of `find_packages(...)`/`find:`).
+
+ You can read more about "package discovery" and "data files" on setuptools
+ documentation page.
+ \n\n!!
+ """
+
+ def __init__(self):
+ self._already_warned = set()
+
+ def is_module(self, file):
+ return file.endswith(".py") and file[:-len(".py")].isidentifier()
+
+ def importable_subpackage(self, parent, file):
+ pkg = Path(file).parent
+ parts = list(itertools.takewhile(str.isidentifier, pkg.parts))
+ if parts:
+ return ".".join([parent, *parts])
+ return None
+
+ def warn(self, importable):
+ if importable not in self._already_warned:
+ msg = textwrap.dedent(self.MESSAGE).format(importable=importable)
+ warnings.warn(msg, SetuptoolsDeprecationWarning, stacklevel=2)
+ self._already_warned.add(importable)
diff --git a/setuptools/command/dist_info.py b/setuptools/command/dist_info.py
index 8b8509f3..ca540ad1 100644
--- a/setuptools/command/dist_info.py
+++ b/setuptools/command/dist_info.py
@@ -54,7 +54,8 @@ def _version(version: str) -> str:
try:
return str(packaging.version.Version(v)).replace("-", "_")
except packaging.version.InvalidVersion:
- msg = f"""!!\n\n
+ msg = f"""Invalid version: {version!r}.
+ !!\n\n
###################
# Invalid version #
###################
diff --git a/setuptools/config/_apply_pyprojecttoml.py b/setuptools/config/_apply_pyprojecttoml.py
index fce5c40e..c33c8cc7 100644
--- a/setuptools/config/_apply_pyprojecttoml.py
+++ b/setuptools/config/_apply_pyprojecttoml.py
@@ -16,6 +16,8 @@ from types import MappingProxyType
from typing import (TYPE_CHECKING, Any, Callable, Dict, List, Optional, Set, Tuple,
Type, Union)
+from setuptools._deprecation_warning import SetuptoolsDeprecationWarning
+
if TYPE_CHECKING:
from setuptools._importlib import metadata # noqa
from setuptools.dist import Distribution # noqa
@@ -75,6 +77,12 @@ def _apply_tool_table(dist: "Distribution", config: dict, filename: _Path):
for field, value in tool_table.items():
norm_key = json_compatible_key(field)
+
+ if norm_key in TOOL_TABLE_DEPRECATIONS:
+ suggestion = TOOL_TABLE_DEPRECATIONS[norm_key]
+ msg = f"The parameter `{norm_key}` is deprecated, {suggestion}"
+ warnings.warn(msg, SetuptoolsDeprecationWarning)
+
norm_key = TOOL_TABLE_RENAMES.get(norm_key, norm_key)
_set_config(dist, norm_key, value)
@@ -171,21 +179,7 @@ def _people(dist: "Distribution", val: List[dict], _root_dir: _Path, kind: str):
def _project_urls(dist: "Distribution", val: dict, _root_dir):
- special = {"downloadurl": "download_url", "homepage": "url"}
- for key, url in val.items():
- norm_key = json_compatible_key(key).replace("_", "")
- _set_config(dist, special.get(norm_key, key), url)
- # If `homepage` is missing, distutils will warn the following message:
- # "warning: check: missing required meta-data: url"
- # In the context of PEP 621, users might ask themselves: "which url?".
- # Let's add a warning before distutils check to help users understand the problem:
- if not dist.metadata.url:
- msg = (
- "Missing `Homepage` url.\nIt is advisable to link some kind of reference "
- "for your project (e.g. source code or documentation).\n"
- )
- _logger.warning(msg)
- _set_config(dist, "project_urls", val.copy())
+ _set_config(dist, "project_urls", val)
def _python_requires(dist: "Distribution", val: dict, _root_dir):
@@ -195,8 +189,10 @@ def _python_requires(dist: "Distribution", val: dict, _root_dir):
def _dependencies(dist: "Distribution", val: list, _root_dir):
- existing = getattr(dist, "install_requires", [])
- _set_config(dist, "install_requires", existing + val)
+ if getattr(dist, "install_requires", []):
+ msg = "`install_requires` overwritten in `pyproject.toml` (dependencies)"
+ warnings.warn(msg)
+ _set_config(dist, "install_requires", val)
def _optional_dependencies(dist: "Distribution", val: dict, _root_dir):
@@ -319,6 +315,9 @@ PYPROJECT_CORRESPONDENCE: Dict[str, _Correspondence] = {
}
TOOL_TABLE_RENAMES = {"script_files": "scripts"}
+TOOL_TABLE_DEPRECATIONS = {
+ "namespace_packages": "consider using implicit namespaces instead (PEP 420)."
+}
SETUPTOOLS_PATCHES = {"long_description_content_type", "project_urls",
"provides_extras", "license_file", "license_files"}
@@ -342,7 +341,10 @@ _PREVIOUSLY_DEFINED = {
class _WouldIgnoreField(UserWarning):
- """Inform users that ``pyproject.toml`` would overwrite previously defined metadata:
+ """Inform users that ``pyproject.toml`` would overwrite previous metadata."""
+
+ MESSAGE = """\
+ {field!r} defined outside of `pyproject.toml` would be ignored.
!!\n\n
##########################################################################
# configuration would be ignored/result in error due to `pyproject.toml` #
@@ -352,7 +354,7 @@ class _WouldIgnoreField(UserWarning):
`{field} = {value!r}`
- According to the spec (see the link bellow), however, setuptools CANNOT
+ According to the spec (see the link below), however, setuptools CANNOT
consider this value unless {field!r} is listed as `dynamic`.
https://packaging.python.org/en/latest/specifications/declaring-project-metadata/
@@ -370,5 +372,4 @@ class _WouldIgnoreField(UserWarning):
@classmethod
def message(cls, field, value):
from inspect import cleandoc
- msg = "\n".join(cls.__doc__.splitlines()[1:])
- return cleandoc(msg.format(field=field, value=value))
+ return cleandoc(cls.MESSAGE.format(field=field, value=value))
diff --git a/setuptools/config/pyprojecttoml.py b/setuptools/config/pyprojecttoml.py
index be812142..976eb063 100644
--- a/setuptools/config/pyprojecttoml.py
+++ b/setuptools/config/pyprojecttoml.py
@@ -418,7 +418,7 @@ class _ExperimentalProjectMetadata(UserWarning):
class _InvalidFile(UserWarning):
- """Inform users that the given `pyproject.toml` is experimental:
+ """The given `pyproject.toml` file is invalid and would be ignored.
!!\n\n
############################
# Invalid `pyproject.toml` #
@@ -436,5 +436,4 @@ class _InvalidFile(UserWarning):
@classmethod
def message(cls):
from inspect import cleandoc
- msg = "\n".join(cls.__doc__.splitlines()[1:])
- return cleandoc(msg)
+ return cleandoc(cls.__doc__)
diff --git a/setuptools/config/setupcfg.py b/setuptools/config/setupcfg.py
index d485a8bb..b2d5c346 100644
--- a/setuptools/config/setupcfg.py
+++ b/setuptools/config/setupcfg.py
@@ -12,6 +12,7 @@ from typing import (TYPE_CHECKING, Callable, Any, Dict, Generic, Iterable, List,
from distutils.errors import DistutilsOptionError, DistutilsFileError
from setuptools.extern.packaging.version import Version, InvalidVersion
from setuptools.extern.packaging.specifiers import SpecifierSet
+from setuptools._deprecation_warning import SetuptoolsDeprecationWarning
from . import expand
@@ -507,7 +508,7 @@ class ConfigMetadataHandler(ConfigHandler["DistributionMetadata"]):
parse_list,
"The requires parameter is deprecated, please use "
"install_requires for runtime dependencies.",
- DeprecationWarning,
+ SetuptoolsDeprecationWarning,
),
'obsoletes': parse_list,
'classifiers': self._get_parser_compound(parse_file, parse_list),
@@ -516,7 +517,7 @@ class ConfigMetadataHandler(ConfigHandler["DistributionMetadata"]):
exclude_files_parser('license_file'),
"The license_file parameter is deprecated, "
"use license_files instead.",
- DeprecationWarning,
+ SetuptoolsDeprecationWarning,
),
'license_files': parse_list,
'description': parse_file,
@@ -584,7 +585,12 @@ class ConfigOptionsHandler(ConfigHandler["Distribution"]):
'scripts': parse_list,
'eager_resources': parse_list,
'dependency_links': parse_list,
- 'namespace_packages': parse_list,
+ 'namespace_packages': self._deprecated_config_handler(
+ parse_list,
+ "The namespace_packages parameter is deprecated, "
+ "consider using implicit namespaces instead (PEP 420).",
+ SetuptoolsDeprecationWarning,
+ ),
'install_requires': parse_list_semicolon,
'setup_requires': parse_list_semicolon,
'tests_require': parse_list_semicolon,
diff --git a/setuptools/dist.py b/setuptools/dist.py
index 215c88e3..c1ad3008 100644
--- a/setuptools/dist.py
+++ b/setuptools/dist.py
@@ -102,7 +102,7 @@ def _read_list_from_msg(msg: "Message", field: str) -> Optional[List[str]]:
def _read_payload_from_msg(msg: "Message") -> Optional[str]:
value = msg.get_payload().strip()
- if value == 'UNKNOWN':
+ if value == 'UNKNOWN' or not value:
return None
return value
@@ -174,7 +174,10 @@ def write_pkg_file(self, file): # noqa: C901 # is too complex (14) # FIXME
write_field('Metadata-Version', str(version))
write_field('Name', self.get_name())
write_field('Version', self.get_version())
- write_field('Summary', single_line(self.get_description()))
+
+ summary = self.get_description()
+ if summary:
+ write_field('Summary', single_line(summary))
optional_fields = (
('Home-page', 'url'),
@@ -190,8 +193,10 @@ def write_pkg_file(self, file): # noqa: C901 # is too complex (14) # FIXME
if attr_val is not None:
write_field(field, attr_val)
- license = rfc822_escape(self.get_license())
- write_field('License', license)
+ license = self.get_license()
+ if license:
+ write_field('License', rfc822_escape(license))
+
for project_url in self.project_urls.items():
write_field('Project-URL', '%s, %s' % project_url)
@@ -199,7 +204,8 @@ def write_pkg_file(self, file): # noqa: C901 # is too complex (14) # FIXME
if keywords:
write_field('Keywords', keywords)
- for platform in self.get_platforms():
+ platforms = self.get_platforms() or []
+ for platform in platforms:
write_field('Platform', platform)
self._write_list(file, 'Classifier', self.get_classifiers())
@@ -222,7 +228,11 @@ def write_pkg_file(self, file): # noqa: C901 # is too complex (14) # FIXME
self._write_list(file, 'License-File', self.license_files or [])
- file.write("\n%s\n\n" % self.get_long_description())
+ long_description = self.get_long_description()
+ if long_description:
+ file.write("\n%s" % long_description)
+ if not long_description.endswith("\n"):
+ file.write("\n")
sequence = tuple, list
@@ -270,6 +280,11 @@ def check_nsp(dist, attr, value):
nsp,
parent,
)
+ msg = (
+ "The namespace_packages parameter is deprecated, "
+ "consider using implicit namespaces instead (PEP 420)."
+ )
+ warnings.warn(msg, SetuptoolsDeprecationWarning)
def check_extras(dist, attr, value):
diff --git a/setuptools/extension.py b/setuptools/extension.py
index f696c9c1..64baf114 100644
--- a/setuptools/extension.py
+++ b/setuptools/extension.py
@@ -28,7 +28,92 @@ _Extension = get_unpatched(distutils.core.Extension)
class Extension(_Extension):
- """Extension that uses '.c' files in place of '.pyx' files"""
+ """
+ Describes a single extension module.
+
+ This means that all source files will be compiled into a single binary file
+ ``<module path>.<suffix>`` (with ``<module path>`` derived from ``name`` and
+ ``<suffix>`` defined by one of the values in
+ ``importlib.machinery.EXTENSION_SUFFIXES``).
+
+ In the case ``.pyx`` files are passed as ``sources and`` ``Cython`` is **not**
+ installed in the build environment, ``setuptools`` may also try to look for the
+ equivalent ``.cpp`` or ``.c`` files.
+
+ :arg str name:
+ the full name of the extension, including any packages -- ie.
+ *not* a filename or pathname, but Python dotted name
+
+ :arg list[str] sources:
+ list of source filenames, relative to the distribution root
+ (where the setup script lives), in Unix form (slash-separated)
+ for portability. Source files may be C, C++, SWIG (.i),
+ platform-specific resource files, or whatever else is recognized
+ by the "build_ext" command as source for a Python extension.
+
+ :keyword list[str] include_dirs:
+ list of directories to search for C/C++ header files (in Unix
+ form for portability)
+
+ :keyword list[tuple[str, str|None]] define_macros:
+ list of macros to define; each macro is defined using a 2-tuple:
+ the first item corresponding to the name of the macro and the second
+ item either a string with its value or None to
+ define it without a particular value (equivalent of "#define
+ FOO" in source or -DFOO on Unix C compiler command line)
+
+ :keyword list[str] undef_macros:
+ list of macros to undefine explicitly
+
+ :keyword list[str] library_dirs:
+ list of directories to search for C/C++ libraries at link time
+
+ :keyword list[str] libraries:
+ list of library names (not filenames or paths) to link against
+
+ :keyword list[str] runtime_library_dirs:
+ list of directories to search for C/C++ libraries at run time
+ (for shared extensions, this is when the extension is loaded)
+
+ :keyword list[str] extra_objects:
+ list of extra files to link with (eg. object files not implied
+ by 'sources', static library that must be explicitly specified,
+ binary resource files, etc.)
+
+ :keyword list[str] extra_compile_args:
+ any extra platform- and compiler-specific information to use
+ when compiling the source files in 'sources'. For platforms and
+ compilers where "command line" makes sense, this is typically a
+ list of command-line arguments, but for other platforms it could
+ be anything.
+
+ :keyword list[str] extra_link_args:
+ any extra platform- and compiler-specific information to use
+ when linking object files together to create the extension (or
+ to create a new static Python interpreter). Similar
+ interpretation as for 'extra_compile_args'.
+
+ :keyword list[str] export_symbols:
+ list of symbols to be exported from a shared extension. Not
+ used on all platforms, and not generally necessary for Python
+ extensions, which typically export exactly one symbol: "init" +
+ extension_name.
+
+ :keyword list[str] swig_opts:
+ any extra options to pass to SWIG if a source file has the .i
+ extension.
+
+ :keyword list[str] depends:
+ list of files that the extension depends on
+
+ :keyword str language:
+ extension language (i.e. "c", "c++", "objc"). Will be detected
+ from the source extensions if not provided.
+
+ :keyword bool optional:
+ specifies that a build failure in the extension should not abort the
+ build process, but simply not install the failing extension.
+ """
def __init__(self, name, sources, *args, **kw):
# The *args is needed for compatibility as calls may use positional
diff --git a/setuptools/logging.py b/setuptools/logging.py
index 15b57613..5d41c988 100644
--- a/setuptools/logging.py
+++ b/setuptools/logging.py
@@ -12,7 +12,7 @@ def configure():
"""
Configure logging to emit warning and above to stderr
and everything else to stdout. This behavior is provided
- for compatibilty with distutils.log but may change in
+ for compatibility with distutils.log but may change in
the future.
"""
err_handler = logging.StreamHandler()
diff --git a/setuptools/tests/config/test_apply_pyprojecttoml.py b/setuptools/tests/config/test_apply_pyprojecttoml.py
index 045d7f40..2194197f 100644
--- a/setuptools/tests/config/test_apply_pyprojecttoml.py
+++ b/setuptools/tests/config/test_apply_pyprojecttoml.py
@@ -6,6 +6,7 @@ To run these tests offline, please have a look on ``./downloads/preload.py``
import io
import re
import tarfile
+from inspect import cleandoc
from pathlib import Path
from unittest.mock import Mock
from zipfile import ZipFile
@@ -14,6 +15,7 @@ import pytest
from ini2toml.api import Translator
import setuptools # noqa ensure monkey patch to metadata
+from setuptools._deprecation_warning import SetuptoolsDeprecationWarning
from setuptools.dist import Distribution
from setuptools.config import setupcfg, pyprojecttoml
from setuptools.config import expand
@@ -211,6 +213,21 @@ def test_license_and_license_files(tmp_path):
assert dist.metadata.license == "LicenseRef-Proprietary\n"
+class TestDeprecatedFields:
+ def test_namespace_packages(self, tmp_path):
+ pyproject = tmp_path / "pyproject.toml"
+ config = """
+ [project]
+ name = "myproj"
+ version = "42"
+ [tool.setuptools]
+ namespace-packages = ["myproj.pkg"]
+ """
+ pyproject.write_text(cleandoc(config), encoding="utf-8")
+ with pytest.warns(SetuptoolsDeprecationWarning, match="namespace_packages"):
+ pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+
+
class TestPresetField:
def pyproject(self, tmp_path, dynamic, extra_content=""):
content = f"[project]\nname = 'proj'\ndynamic = {dynamic!r}\n"
@@ -257,6 +274,15 @@ class TestPresetField:
dist_value = _some_attrgetter(f"metadata.{attr}", attr)(dist)
assert dist_value == value
+ def test_warning_overwritten_dependencies(self, tmp_path):
+ src = "[project]\nname='pkg'\nversion='0.1'\ndependencies=['click']\n"
+ pyproject = tmp_path / "pyproject.toml"
+ pyproject.write_text(src, encoding="utf-8")
+ dist = makedist(tmp_path, install_requires=["wheel"])
+ with pytest.warns(match="`install_requires` overwritten"):
+ dist = pyprojecttoml.apply_configuration(dist, pyproject)
+ assert "wheel" not in dist.install_requires
+
def test_optional_dependencies_dont_remove_env_markers(self, tmp_path):
"""
Internally setuptools converts dependencies with markers to "extras".
@@ -298,19 +324,26 @@ class TestMeta:
def core_metadata(dist) -> str:
with io.StringIO() as buffer:
dist.metadata.write_pkg_file(buffer)
- value = "\n".join(buffer.getvalue().strip().splitlines())
+ pkg_file_txt = buffer.getvalue()
+ skip_prefixes = ()
+ skip_lines = set()
# ---- DIFF NORMALISATION ----
# PEP 621 is very particular about author/maintainer metadata conversion, so skip
- value = re.sub(r"^(Author|Maintainer)(-email)?:.*$", "", value, flags=re.M)
+ skip_prefixes += ("Author:", "Author-email:", "Maintainer:", "Maintainer-email:")
# May be redundant with Home-page
- value = re.sub(r"^Project-URL: Homepage,.*$", "", value, flags=re.M)
+ skip_prefixes += ("Project-URL: Homepage,", "Home-page:")
# May be missing in original (relying on default) but backfilled in the TOML
- value = re.sub(r"^Description-Content-Type:.*$", "", value, flags=re.M)
+ skip_prefixes += ("Description-Content-Type:",)
# ini2toml can automatically convert `tests_require` to `testing` extra
- value = value.replace("Provides-Extra: testing\n", "")
+ skip_lines.add("Provides-Extra: testing")
# Remove empty lines
- value = re.sub(r"^\s*$", "", value, flags=re.M)
- value = re.sub(r"^\n", "", value, flags=re.M)
+ skip_lines.add("")
+
+ result = []
+ for line in pkg_file_txt.splitlines():
+ if line.startswith(skip_prefixes) or line in skip_lines:
+ continue
+ result.append(line + "\n")
- return value
+ return "".join(result)
diff --git a/setuptools/tests/config/test_setupcfg.py b/setuptools/tests/config/test_setupcfg.py
index 1f35f836..904b1ef8 100644
--- a/setuptools/tests/config/test_setupcfg.py
+++ b/setuptools/tests/config/test_setupcfg.py
@@ -7,6 +7,7 @@ from unittest.mock import Mock, patch
import pytest
from distutils.errors import DistutilsOptionError, DistutilsFileError
+from setuptools._deprecation_warning import SetuptoolsDeprecationWarning
from setuptools.dist import Distribution, _Distribution
from setuptools.config.setupcfg import ConfigHandler, read_configuration
from ..textwrap import DALS
@@ -409,7 +410,7 @@ class TestMetadata:
'requires = some, requirement\n',
)
- with pytest.deprecated_call():
+ with pytest.warns(SetuptoolsDeprecationWarning, match="requires"):
with get_dist(tmpdir) as dist:
metadata = dist.metadata
@@ -518,7 +519,8 @@ class TestOptions:
'python_requires = >=1.0, !=2.8\n'
'py_modules = module1, module2\n',
)
- with get_dist(tmpdir) as dist:
+ deprec = pytest.warns(SetuptoolsDeprecationWarning, match="namespace_packages")
+ with deprec, get_dist(tmpdir) as dist:
assert dist.zip_safe
assert dist.include_package_data
assert dist.package_dir == {'': 'src', 'b': 'c'}
@@ -572,7 +574,8 @@ class TestOptions:
' http://some.com/here/1\n'
' http://some.com/there/2\n',
)
- with get_dist(tmpdir) as dist:
+ deprec = pytest.warns(SetuptoolsDeprecationWarning, match="namespace_packages")
+ with deprec, get_dist(tmpdir) as dist:
assert dist.package_dir == {'': 'src', 'b': 'c'}
assert dist.packages == ['pack_a', 'pack_b.subpack']
assert dist.namespace_packages == ['pack1', 'pack2']
diff --git a/setuptools/tests/test_build.py b/setuptools/tests/test_build.py
new file mode 100644
index 00000000..cefb3d34
--- /dev/null
+++ b/setuptools/tests/test_build.py
@@ -0,0 +1,63 @@
+from contextlib import contextmanager
+from setuptools import Command, SetuptoolsDeprecationWarning
+from setuptools.dist import Distribution
+from setuptools.command.build import build
+from distutils.command.build import build as distutils_build
+
+import pytest
+
+
+def test_distribution_gives_setuptools_build_obj(tmpdir_cwd):
+ """
+ Check that the setuptools Distribution uses the
+ setuptools specific build object.
+ """
+
+ dist = Distribution(dict(
+ script_name='setup.py',
+ script_args=['build'],
+ packages=[],
+ package_data={'': ['path/*']},
+ ))
+ assert isinstance(dist.get_command_obj("build"), build)
+
+
+@contextmanager
+def _restore_sub_commands():
+ orig = distutils_build.sub_commands[:]
+ try:
+ yield
+ finally:
+ distutils_build.sub_commands = orig
+
+
+class Subcommand(Command):
+ """Dummy command to be used in tests"""
+
+ def initialize_options(self):
+ pass
+
+ def finalize_options(self):
+ pass
+
+ def run(self):
+ raise NotImplementedError("just to check if the command runs")
+
+
+@_restore_sub_commands()
+def test_subcommand_in_distutils(tmpdir_cwd):
+ """
+ Ensure that sub commands registered in ``distutils`` run,
+ after instructing the users to migrate to ``setuptools``.
+ """
+ dist = Distribution(dict(
+ packages=[],
+ cmdclass={'subcommand': Subcommand},
+ ))
+ distutils_build.sub_commands.append(('subcommand', None))
+
+ warning_msg = "please use .setuptools.command.build."
+ with pytest.warns(SetuptoolsDeprecationWarning, match=warning_msg):
+ # For backward compatibility, the subcommand should run anyway:
+ with pytest.raises(NotImplementedError, match="the command runs"):
+ dist.run_command("build")
diff --git a/setuptools/tests/test_build_py.py b/setuptools/tests/test_build_py.py
index 19c8b780..13fa64de 100644
--- a/setuptools/tests/test_build_py.py
+++ b/setuptools/tests/test_build_py.py
@@ -3,9 +3,14 @@ import stat
import shutil
import pytest
+import jaraco.path
+from path import Path
+from setuptools import SetuptoolsDeprecationWarning
from setuptools.dist import Distribution
+from .textwrap import DALS
+
def test_directories_in_package_data_glob(tmpdir_cwd):
"""
@@ -25,6 +30,29 @@ def test_directories_in_package_data_glob(tmpdir_cwd):
dist.run_commands()
+def test_recursive_in_package_data_glob(tmpdir_cwd):
+ """
+ Files matching recursive globs (**) in package_data should
+ be included in the package data.
+
+ #1806
+ """
+ dist = Distribution(dict(
+ script_name='setup.py',
+ script_args=['build_py'],
+ packages=[''],
+ package_data={'': ['path/**/data']},
+ ))
+ os.makedirs('path/subpath/subsubpath')
+ open('path/subpath/subsubpath/data', 'w').close()
+
+ dist.parse_command_line()
+ dist.run_commands()
+
+ assert stat.S_ISREG(os.stat('build/lib/path/subpath/subsubpath/data').st_mode), \
+ "File is not included"
+
+
def test_read_only(tmpdir_cwd):
"""
Ensure read-only flag is not preserved in copy
@@ -79,3 +107,69 @@ def test_executable_data(tmpdir_cwd):
assert os.stat('build/lib/pkg/run-me').st_mode & stat.S_IEXEC, \
"Script is not executable"
+
+
+def test_excluded_subpackages(tmp_path):
+ files = {
+ "setup.cfg": DALS("""
+ [metadata]
+ name = mypkg
+ version = 42
+
+ [options]
+ include_package_data = True
+ packages = find:
+
+ [options.packages.find]
+ exclude = *.tests*
+ """),
+ "mypkg": {
+ "__init__.py": "",
+ "resource_file.txt": "",
+ "tests": {
+ "__init__.py": "",
+ "test_mypkg.py": "",
+ "test_file.txt": "",
+ }
+ },
+ "MANIFEST.in": DALS("""
+ global-include *.py *.txt
+ global-exclude *.py[cod]
+ prune dist
+ prune build
+ prune *.egg-info
+ """)
+ }
+
+ with Path(tmp_path):
+ jaraco.path.build(files)
+ dist = Distribution({"script_name": "%PEP 517%"})
+ dist.parse_config_files()
+
+ build_py = dist.get_command_obj("build_py")
+ msg = r"Python recognizes 'mypkg\.tests' as an importable package"
+ with pytest.warns(SetuptoolsDeprecationWarning, match=msg):
+ # TODO: To fix #3260 we need some transition period to deprecate the
+ # existing behavior of `include_package_data`. After the transition, we
+ # should remove the warning and fix the behaviour.
+ build_py.finalize_options()
+ build_py.run()
+
+ build_dir = Path(dist.get_command_obj("build_py").build_lib)
+ assert (build_dir / "mypkg/__init__.py").exists()
+ assert (build_dir / "mypkg/resource_file.txt").exists()
+
+ # Setuptools is configured to ignore `mypkg.tests`, therefore the following
+ # files/dirs should not be included in the distribution.
+ for f in [
+ "mypkg/tests/__init__.py",
+ "mypkg/tests/test_mypkg.py",
+ "mypkg/tests/test_file.txt",
+ "mypkg/tests",
+ ]:
+ with pytest.raises(AssertionError):
+ # TODO: Enforce the following assertion once #3260 is fixed
+ # (remove context manager and the following xfail).
+ assert not (build_dir / f).exists()
+
+ pytest.xfail("#3260")
diff --git a/setuptools/tests/test_easy_install.py b/setuptools/tests/test_easy_install.py
index 726f9fda..246d634f 100644
--- a/setuptools/tests/test_easy_install.py
+++ b/setuptools/tests/test_easy_install.py
@@ -474,22 +474,27 @@ class TestInstallRequires:
'--install-purelib', str(install_root),
'--install-platlib', str(install_root),
]
- env = {"PYTHONPATH": str(install_root), "__EASYINSTALL_INDEX": mock_index.url}
- with pytest.raises(subprocess.CalledProcessError) as exc_info:
- subprocess.check_output(
- cmd, cwd=str(project_root), env=env, stderr=subprocess.STDOUT, text=True
- )
+ env = {**os.environ, "__EASYINSTALL_INDEX": mock_index.url}
+ cp = subprocess.run(
+ cmd,
+ cwd=str(project_root),
+ env=env,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ text=True,
+ )
+ assert cp.returncode != 0
try:
assert '/does-not-exist/' in {r.path for r in mock_index.requests}
assert next(
line
- for line in exc_info.value.output.splitlines()
+ for line in cp.stdout.splitlines()
if "not find suitable distribution for" in line
and "does-not-exist" in line
)
except Exception:
- if "failed to get random numbers" in exc_info.value.output:
- pytest.xfail(f"{sys.platform} failure - {exc_info.value.output}")
+ if "failed to get random numbers" in cp.stdout:
+ pytest.xfail(f"{sys.platform} failure - {cp.stdout}")
raise
def create_project(self, root):
@@ -1174,7 +1179,7 @@ def test_editable_user_and_build_isolation(setup_context, monkeypatch, tmp_path)
# == Arrange ==
# Pretend that build isolation was enabled
- # e.g pip sets the environment varible PYTHONNOUSERSITE=1
+ # e.g pip sets the environment variable PYTHONNOUSERSITE=1
monkeypatch.setattr('site.ENABLE_USER_SITE', False)
# Patching $HOME for 2 reasons: