summaryrefslogtreecommitdiff
path: root/setuptools/dist.py
diff options
context:
space:
mode:
Diffstat (limited to 'setuptools/dist.py')
-rw-r--r--setuptools/dist.py393
1 files changed, 64 insertions, 329 deletions
diff --git a/setuptools/dist.py b/setuptools/dist.py
index ad54839b..2c088ef8 100644
--- a/setuptools/dist.py
+++ b/setuptools/dist.py
@@ -19,20 +19,16 @@ import itertools
from collections import defaultdict
from email import message_from_file
-from distutils.errors import (
- DistutilsOptionError, DistutilsPlatformError, DistutilsSetupError,
-)
+from distutils.errors import DistutilsOptionError, DistutilsSetupError
from distutils.util import rfc822_escape
from distutils.version import StrictVersion
-from setuptools.extern import six
from setuptools.extern import packaging
from setuptools.extern import ordered_set
-from setuptools.extern.six.moves import map, filter, filterfalse
from . import SetuptoolsDeprecationWarning
-from setuptools.depends import Require
+import setuptools
from setuptools import windows_support
from setuptools.monkey import get_unpatched
from setuptools.config import parse_configuration
@@ -128,12 +124,8 @@ def write_pkg_file(self, file):
"""
version = self.get_metadata_version()
- if six.PY2:
- def write_field(key, value):
- file.write("%s: %s\n" % (key, self._encode_field(value)))
- else:
- def write_field(key, value):
- file.write("%s: %s\n" % (key, value))
+ def write_field(key, value):
+ file.write("%s: %s\n" % (key, value))
write_field('Metadata-Version', str(version))
write_field('Name', self.get_name())
@@ -206,11 +198,11 @@ def check_importable(dist, attr, value):
try:
ep = pkg_resources.EntryPoint.parse('x=' + value)
assert not ep.extras
- except (TypeError, ValueError, AttributeError, AssertionError):
+ except (TypeError, ValueError, AttributeError, AssertionError) as e:
raise DistutilsSetupError(
"%r must be importable 'module:attrs' string (got %r)"
% (attr, value)
- )
+ ) from e
def assert_string_list(dist, attr, value):
@@ -221,10 +213,10 @@ def assert_string_list(dist, attr, value):
assert isinstance(value, (list, tuple))
# verify that elements of value are strings
assert ''.join(value) != value
- except (TypeError, ValueError, AttributeError, AssertionError):
+ except (TypeError, ValueError, AttributeError, AssertionError) as e:
raise DistutilsSetupError(
"%r must be a list of strings (got %r)" % (attr, value)
- )
+ ) from e
def check_nsp(dist, attr, value):
@@ -249,12 +241,12 @@ def check_extras(dist, attr, value):
"""Verify that extras_require mapping is valid"""
try:
list(itertools.starmap(_check_extra, value.items()))
- except (TypeError, ValueError, AttributeError):
+ except (TypeError, ValueError, AttributeError) as e:
raise DistutilsSetupError(
"'extras_require' must be a dictionary whose values are "
"strings or lists of strings containing valid project/version "
"requirement specifiers."
- )
+ ) from e
def _check_extra(extra, reqs):
@@ -282,7 +274,9 @@ def check_requirements(dist, attr, value):
"{attr!r} must be a string or list of strings "
"containing valid project/version requirement specifiers; {error}"
)
- raise DistutilsSetupError(tmpl.format(attr=attr, error=error))
+ raise DistutilsSetupError(
+ tmpl.format(attr=attr, error=error)
+ ) from error
def check_specifier(dist, attr, value):
@@ -294,7 +288,9 @@ def check_specifier(dist, attr, value):
"{attr!r} must be a string "
"containing valid version specifiers; {error}"
)
- raise DistutilsSetupError(tmpl.format(attr=attr, error=error))
+ raise DistutilsSetupError(
+ tmpl.format(attr=attr, error=error)
+ ) from error
def check_entry_points(dist, attr, value):
@@ -302,11 +298,11 @@ def check_entry_points(dist, attr, value):
try:
pkg_resources.EntryPoint.parse_map(value)
except ValueError as e:
- raise DistutilsSetupError(e)
+ raise DistutilsSetupError(e) from e
def check_test_suite(dist, attr, value):
- if not isinstance(value, six.string_types):
+ if not isinstance(value, str):
raise DistutilsSetupError("test_suite must be a string")
@@ -317,7 +313,7 @@ def check_package_data(dist, attr, value):
"{!r} must be a dictionary mapping package names to lists of "
"string wildcard patterns".format(attr))
for k, v in value.items():
- if not isinstance(k, six.string_types):
+ if not isinstance(k, str):
raise DistutilsSetupError(
"keys of {!r} dict must be strings (got {!r})"
.format(attr, k)
@@ -338,7 +334,7 @@ _Distribution = get_unpatched(distutils.core.Distribution)
class Distribution(_Distribution):
- """Distribution with support for features, tests, and package data
+ """Distribution with support for tests and package data
This is an enhanced version of 'distutils.dist.Distribution' that
effectively adds the following new optional keyword arguments to 'setup()':
@@ -365,21 +361,6 @@ class Distribution(_Distribution):
EasyInstall and requests one of your extras, the corresponding
additional requirements will be installed if needed.
- 'features' **deprecated** -- a dictionary mapping option names to
- 'setuptools.Feature'
- objects. Features are a portion of the distribution that can be
- included or excluded based on user options, inter-feature dependencies,
- and availability on the current system. Excluded features are omitted
- from all setup commands, including source and binary distributions, so
- you can create multiple distributions from the same source tree.
- Feature names should be valid Python identifiers, except that they may
- contain the '-' (minus) sign. Features can be included or excluded
- via the command line options '--with-X' and '--without-X', where 'X' is
- the name of the feature. Whether a feature is included by default, and
- whether you are allowed to control this from the command line, is
- determined by the Feature object. See the 'Feature' class for more
- information.
-
'test_suite' -- the name of a test suite to run for the 'test' command.
If the user runs 'python setup.py test', the package will be installed,
and the named test suite will be run. The format is the same as
@@ -401,8 +382,7 @@ class Distribution(_Distribution):
for manipulating the distribution's contents. For example, the 'include()'
and 'exclude()' methods can be thought of as in-place add and subtract
commands that add or remove packages, modules, extensions, and so on from
- the distribution. They are used by the feature subsystem to configure the
- distribution for the included and excluded features.
+ the distribution.
"""
_DISTUTILS_UNSUPPORTED_METADATA = {
@@ -432,10 +412,6 @@ class Distribution(_Distribution):
if not have_package_data:
self.package_data = {}
attrs = attrs or {}
- if 'features' in attrs or 'require_features' in attrs:
- Feature.warn_deprecated()
- self.require_features = []
- self.features = {}
self.dist_files = []
# Filter-out setuptools' specific options.
self.src_root = attrs.pop("src_root", None)
@@ -461,30 +437,40 @@ class Distribution(_Distribution):
value = default() if default else None
setattr(self.metadata, option, value)
- if isinstance(self.metadata.version, numbers.Number):
+ self.metadata.version = self._normalize_version(
+ self._validate_version(self.metadata.version))
+ self._finalize_requires()
+
+ @staticmethod
+ def _normalize_version(version):
+ if isinstance(version, setuptools.sic) or version is None:
+ return version
+
+ normalized = str(packaging.version.Version(version))
+ if version != normalized:
+ tmpl = "Normalizing '{version}' to '{normalized}'"
+ warnings.warn(tmpl.format(**locals()))
+ return normalized
+ return version
+
+ @staticmethod
+ def _validate_version(version):
+ if isinstance(version, numbers.Number):
# Some people apparently take "version number" too literally :)
- self.metadata.version = str(self.metadata.version)
+ version = str(version)
- if self.metadata.version is not None:
+ if version is not None:
try:
- ver = packaging.version.Version(self.metadata.version)
- normalized_version = str(ver)
- if self.metadata.version != normalized_version:
- warnings.warn(
- "Normalizing '%s' to '%s'" % (
- self.metadata.version,
- normalized_version,
- )
- )
- self.metadata.version = normalized_version
+ packaging.version.Version(version)
except (packaging.version.InvalidVersion, TypeError):
warnings.warn(
"The version specified (%r) is an invalid version, this "
"may not work as expected with newer versions of "
"setuptools, pip, and PyPI. Please see PEP 440 for more "
- "details." % self.metadata.version
+ "details." % version
)
- self._finalize_requires()
+ return setuptools.sic(version)
+ return version
def _finalize_requires(self):
"""
@@ -545,7 +531,7 @@ class Distribution(_Distribution):
spec_inst_reqs = getattr(self, 'install_requires', None) or ()
inst_reqs = list(pkg_resources.parse_requirements(spec_inst_reqs))
simple_reqs = filter(is_simple_req, inst_reqs)
- complex_reqs = filterfalse(is_simple_req, inst_reqs)
+ complex_reqs = itertools.filterfalse(is_simple_req, inst_reqs)
self.install_requires = list(map(str, simple_reqs))
for r in complex_reqs:
@@ -568,10 +554,10 @@ class Distribution(_Distribution):
this method provides the same functionality in subtly-improved
ways.
"""
- from setuptools.extern.six.moves.configparser import ConfigParser
+ from configparser import ConfigParser
# Ignore install directory options if we have a venv
- if not six.PY2 and sys.prefix != sys.base_prefix:
+ if sys.prefix != sys.base_prefix:
ignore_options = [
'install-base', 'install-platbase', 'install-lib',
'install-platlib', 'install-purelib', 'install-headers',
@@ -593,14 +579,14 @@ class Distribution(_Distribution):
with io.open(filename, encoding='utf-8') as reader:
if DEBUG:
self.announce(" reading {filename}".format(**locals()))
- (parser.readfp if six.PY2 else parser.read_file)(reader)
+ parser.read_file(reader)
for section in parser.sections():
options = parser.options(section)
opt_dict = self.get_option_dict(section)
for opt in options:
if opt != '__name__' and opt not in ignore_options:
- val = self._try_str(parser.get(section, opt))
+ val = parser.get(section, opt)
opt = opt.replace('-', '_')
opt_dict[opt] = (filename, val)
@@ -621,28 +607,8 @@ class Distribution(_Distribution):
setattr(self, opt, strtobool(val))
else:
setattr(self, opt, val)
- except ValueError as msg:
- raise DistutilsOptionError(msg)
-
- @staticmethod
- def _try_str(val):
- """
- On Python 2, much of distutils relies on string values being of
- type 'str' (bytes) and not unicode text. If the value can be safely
- encoded to bytes using the default encoding, prefer that.
-
- Why the default encoding? Because that value can be implicitly
- decoded back to text if needed.
-
- Ref #1653
- """
- if not six.PY2:
- return val
- try:
- return val.encode()
- except UnicodeEncodeError:
- pass
- return val
+ except ValueError as e:
+ raise DistutilsOptionError(e) from e
def _set_command_options(self, command_obj, option_dict=None):
"""
@@ -677,7 +643,7 @@ class Distribution(_Distribution):
neg_opt = {}
try:
- is_string = isinstance(value, six.string_types)
+ is_string = isinstance(value, str)
if option in neg_opt and is_string:
setattr(command_obj, neg_opt[option], not strtobool(value))
elif option in bool_opts and is_string:
@@ -688,8 +654,8 @@ class Distribution(_Distribution):
raise DistutilsOptionError(
"error in %s: command '%s' has no such option '%s'"
% (source, command_name, option))
- except ValueError as msg:
- raise DistutilsOptionError(msg)
+ except ValueError as e:
+ raise DistutilsOptionError(e) from e
def parse_config_files(self, filenames=None, ignore_option_errors=False):
"""Parses configuration files from various levels
@@ -702,17 +668,6 @@ class Distribution(_Distribution):
ignore_option_errors=ignore_option_errors)
self._finalize_requires()
- def parse_command_line(self):
- """Process features after parsing command line options"""
- result = _Distribution.parse_command_line(self)
- if self.features:
- self._finalize_features()
- return result
-
- def _feature_attrname(self, name):
- """Convert feature name to corresponding option attribute name"""
- return 'with_' + name.replace('-', '_')
-
def fetch_build_eggs(self, requires):
"""Resolve pre-setup requirements"""
resolved_dists = pkg_resources.working_set.resolve(
@@ -731,13 +686,13 @@ class Distribution(_Distribution):
to influence the order of execution. Smaller numbers
go first and the default is 0.
"""
- hook_key = 'setuptools.finalize_distribution_options'
+ group = 'setuptools.finalize_distribution_options'
def by_order(hook):
return getattr(hook, 'order', 0)
- eps = pkg_resources.iter_entry_points(hook_key)
+ eps = map(lambda e: e.load(), pkg_resources.iter_entry_points(group))
for ep in sorted(eps, key=by_order):
- ep.load()(self)
+ ep(self)
def _finalize_setup_keywords(self):
for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'):
@@ -776,53 +731,6 @@ class Distribution(_Distribution):
from setuptools.installer import fetch_build_egg
return fetch_build_egg(self, req)
- def _finalize_feature_opts(self):
- """Add --with-X/--without-X options based on optional features"""
-
- if not self.features:
- return
-
- go = []
- no = self.negative_opt.copy()
-
- for name, feature in self.features.items():
- self._set_feature(name, None)
- feature.validate(self)
-
- if feature.optional:
- descr = feature.description
- incdef = ' (default)'
- excdef = ''
- if not feature.include_by_default():
- excdef, incdef = incdef, excdef
-
- new = (
- ('with-' + name, None, 'include ' + descr + incdef),
- ('without-' + name, None, 'exclude ' + descr + excdef),
- )
- go.extend(new)
- no['without-' + name] = 'with-' + name
-
- self.global_options = self.feature_options = go + self.global_options
- self.negative_opt = self.feature_negopt = no
-
- def _finalize_features(self):
- """Add/remove features and resolve dependencies between them"""
-
- # First, flag all the enabled items (and thus their dependencies)
- for name, feature in self.features.items():
- enabled = self.feature_is_included(name)
- if enabled or (enabled is None and feature.include_by_default()):
- feature.include_in(self)
- self._set_feature(name, 1)
-
- # Then disable the rest, so that off-by-default features don't
- # get flagged as errors when they're required by an enabled feature
- for name, feature in self.features.items():
- if not self.feature_is_included(name):
- feature.exclude_from(self)
- self._set_feature(name, 0)
-
def get_command_class(self, command):
"""Pluggable version of get_command_class()"""
if command in self.cmdclass:
@@ -852,25 +760,6 @@ class Distribution(_Distribution):
self.cmdclass[ep.name] = cmdclass
return _Distribution.get_command_list(self)
- def _set_feature(self, name, status):
- """Set feature's inclusion status"""
- setattr(self, self._feature_attrname(name), status)
-
- def feature_is_included(self, name):
- """Return 1 if feature is included, 0 if excluded, 'None' if unknown"""
- return getattr(self, self._feature_attrname(name))
-
- def include_feature(self, name):
- """Request inclusion of feature named 'name'"""
-
- if self.feature_is_included(name) == 0:
- descr = self.features[name].description
- raise DistutilsOptionError(
- descr + " is required, but was excluded or is not available"
- )
- self.features[name].include_in(self)
- self._set_feature(name, 1)
-
def include(self, **attrs):
"""Add items to distribution that are named in keyword arguments
@@ -932,10 +821,10 @@ class Distribution(_Distribution):
)
try:
old = getattr(self, name)
- except AttributeError:
+ except AttributeError as e:
raise DistutilsSetupError(
"%s: No such distribution setting" % name
- )
+ ) from e
if old is not None and not isinstance(old, sequence):
raise DistutilsSetupError(
name + ": this setting cannot be changed via include/exclude"
@@ -952,10 +841,10 @@ class Distribution(_Distribution):
)
try:
old = getattr(self, name)
- except AttributeError:
+ except AttributeError as e:
raise DistutilsSetupError(
"%s: No such distribution setting" % name
- )
+ ) from e
if old is None:
setattr(self, name, value)
elif not isinstance(old, sequence):
@@ -1088,7 +977,7 @@ class Distribution(_Distribution):
"""
import sys
- if six.PY2 or self.help_commands:
+ if self.help_commands:
return _Distribution.handle_display_options(self, option_order)
# Stdout may be StringIO (e.g. in tests)
@@ -1115,160 +1004,6 @@ class Distribution(_Distribution):
sys.stdout.detach(), encoding, errors, newline, line_buffering)
-class Feature:
- """
- **deprecated** -- The `Feature` facility was never completely implemented
- or supported, `has reported issues
- <https://github.com/pypa/setuptools/issues/58>`_ and will be removed in
- a future version.
-
- A subset of the distribution that can be excluded if unneeded/wanted
-
- Features are created using these keyword arguments:
-
- 'description' -- a short, human readable description of the feature, to
- be used in error messages, and option help messages.
-
- 'standard' -- if true, the feature is included by default if it is
- available on the current system. Otherwise, the feature is only
- included if requested via a command line '--with-X' option, or if
- another included feature requires it. The default setting is 'False'.
-
- 'available' -- if true, the feature is available for installation on the
- current system. The default setting is 'True'.
-
- 'optional' -- if true, the feature's inclusion can be controlled from the
- command line, using the '--with-X' or '--without-X' options. If
- false, the feature's inclusion status is determined automatically,
- based on 'availabile', 'standard', and whether any other feature
- requires it. The default setting is 'True'.
-
- 'require_features' -- a string or sequence of strings naming features
- that should also be included if this feature is included. Defaults to
- empty list. May also contain 'Require' objects that should be
- added/removed from the distribution.
-
- 'remove' -- a string or list of strings naming packages to be removed
- from the distribution if this feature is *not* included. If the
- feature *is* included, this argument is ignored. This argument exists
- to support removing features that "crosscut" a distribution, such as
- defining a 'tests' feature that removes all the 'tests' subpackages
- provided by other features. The default for this argument is an empty
- list. (Note: the named package(s) or modules must exist in the base
- distribution when the 'setup()' function is initially called.)
-
- other keywords -- any other keyword arguments are saved, and passed to
- the distribution's 'include()' and 'exclude()' methods when the
- feature is included or excluded, respectively. So, for example, you
- could pass 'packages=["a","b"]' to cause packages 'a' and 'b' to be
- added or removed from the distribution as appropriate.
-
- A feature must include at least one 'requires', 'remove', or other
- keyword argument. Otherwise, it can't affect the distribution in any way.
- Note also that you can subclass 'Feature' to create your own specialized
- feature types that modify the distribution in other ways when included or
- excluded. See the docstrings for the various methods here for more detail.
- Aside from the methods, the only feature attributes that distributions look
- at are 'description' and 'optional'.
- """
-
- @staticmethod
- def warn_deprecated():
- msg = (
- "Features are deprecated and will be removed in a future "
- "version. See https://github.com/pypa/setuptools/issues/65."
- )
- warnings.warn(msg, DistDeprecationWarning, stacklevel=3)
-
- def __init__(
- self, description, standard=False, available=True,
- optional=True, require_features=(), remove=(), **extras):
- self.warn_deprecated()
-
- self.description = description
- self.standard = standard
- self.available = available
- self.optional = optional
- if isinstance(require_features, (str, Require)):
- require_features = require_features,
-
- self.require_features = [
- r for r in require_features if isinstance(r, str)
- ]
- er = [r for r in require_features if not isinstance(r, str)]
- if er:
- extras['require_features'] = er
-
- if isinstance(remove, str):
- remove = remove,
- self.remove = remove
- self.extras = extras
-
- if not remove and not require_features and not extras:
- raise DistutilsSetupError(
- "Feature %s: must define 'require_features', 'remove', or "
- "at least one of 'packages', 'py_modules', etc."
- )
-
- def include_by_default(self):
- """Should this feature be included by default?"""
- return self.available and self.standard
-
- def include_in(self, dist):
- """Ensure feature and its requirements are included in distribution
-
- You may override this in a subclass to perform additional operations on
- the distribution. Note that this method may be called more than once
- per feature, and so should be idempotent.
-
- """
-
- if not self.available:
- raise DistutilsPlatformError(
- self.description + " is required, "
- "but is not available on this platform"
- )
-
- dist.include(**self.extras)
-
- for f in self.require_features:
- dist.include_feature(f)
-
- def exclude_from(self, dist):
- """Ensure feature is excluded from distribution
-
- You may override this in a subclass to perform additional operations on
- the distribution. This method will be called at most once per
- feature, and only after all included features have been asked to
- include themselves.
- """
-
- dist.exclude(**self.extras)
-
- if self.remove:
- for item in self.remove:
- dist.exclude_package(item)
-
- def validate(self, dist):
- """Verify that feature makes sense in context of distribution
-
- This method is called by the distribution just before it parses its
- command line. It checks to ensure that the 'remove' attribute, if any,
- contains only valid package/module names that are present in the base
- distribution when 'setup()' is called. You may override it in a
- subclass to perform any other required validation of the feature
- against a target distribution.
- """
-
- for item in self.remove:
- if not dist.has_contents_for(item):
- raise DistutilsSetupError(
- "%s wants to be able to remove %s, but the distribution"
- " doesn't contain any packages or modules under %s"
- % (self.description, item, item)
- )
-
-
class DistDeprecationWarning(SetuptoolsDeprecationWarning):
"""Class for warning about deprecations in dist in
setuptools. Not ignored by default, unlike DeprecationWarning."""