This commit is contained in:
lz_db
2026-10-16 22:48:30 +08:00
parent 190de72571
commit 0b36fd3383
3161 changed files with 12787 additions and 77274 deletions
@@ -10,42 +10,49 @@ Create a wheel that, when installed, will make the source package 'editable'
*auxiliary build directory* or ``auxiliary_dir``.
"""
from __future__ import annotations
import io
import logging
import os
import re
import shutil
import sys
import traceback
from collections.abc import Iterable, Iterator, Mapping
import warnings
from contextlib import suppress
from enum import Enum
from inspect import cleandoc
from itertools import chain, starmap
from itertools import chain
from pathlib import Path
from tempfile import TemporaryDirectory
from types import TracebackType
from typing import TYPE_CHECKING, Protocol, TypeVar, cast
from typing import (
TYPE_CHECKING,
Dict,
Iterable,
Iterator,
List,
Mapping,
Optional,
Tuple,
TypeVar,
Union,
)
from .. import Command, _normalization, _path, _shutil, errors, namespaces
from .._path import StrPath
from ..compat import py312
from ..discovery import find_package_path
from ..dist import Distribution
from ..warnings import InformationOnly, SetuptoolsDeprecationWarning, SetuptoolsWarning
from .build import build as build_cls
from .build_py import build_py as build_py_cls
from .dist_info import dist_info as dist_info_cls
from .egg_info import egg_info as egg_info_cls
from .install import install as install_cls
from .install_scripts import install_scripts as install_scripts_cls
from setuptools import Command, SetuptoolsDeprecationWarning, errors, namespaces
from setuptools.command.build_py import build_py as build_py_cls
from setuptools.discovery import find_package_path
from setuptools.dist import Distribution
if TYPE_CHECKING:
from typing_extensions import Self
from wheel.wheelfile import WheelFile # noqa
from .._vendor.wheel.wheelfile import WheelFile
if sys.version_info >= (3, 8):
from typing import Protocol
elif TYPE_CHECKING:
from typing_extensions import Protocol
else:
from abc import ABC as Protocol
_P = TypeVar("_P", bound=StrPath)
_Path = Union[str, Path]
_P = TypeVar("_P", bound=_Path)
_logger = logging.getLogger(__name__)
@@ -62,7 +69,7 @@ class _EditableMode(Enum):
COMPAT = "compat" # TODO: Remove `compat` after Dec/2022.
@classmethod
def convert(cls, mode: str | None) -> _EditableMode:
def convert(cls, mode: Optional[str]) -> "_EditableMode":
if not mode:
return _EditableMode.LENIENT # default
@@ -71,21 +78,16 @@ class _EditableMode(Enum):
raise errors.OptionError(f"Invalid editable mode: {mode!r}. Try: 'strict'.")
if _mode == "COMPAT":
SetuptoolsDeprecationWarning.emit(
"Compat editable installs",
"""
The 'compat' editable mode is transitional and will be removed
in future versions of `setuptools`.
Please adapt your code accordingly to use either the 'strict' or the
'lenient' modes.
""",
see_docs="userguide/development_mode.html",
# TODO: define due_date
# There is a series of shortcomings with the available editable install
# methods, and they are very controversial. This is something that still
# needs work.
# Moreover, `pip` is still hiding this warning, so users are not aware.
)
msg = """
The 'compat' editable mode is transitional and will be removed
in future versions of `setuptools`.
Please adapt your code accordingly to use either the 'strict' or the
'lenient' modes.
For more information, please check:
https://setuptools.pypa.io/en/latest/userguide/development_mode.html
"""
warnings.warn(msg, SetuptoolsDeprecationWarning)
return _EditableMode[_mode]
@@ -102,11 +104,10 @@ Options like `package-data`, `include/exclude-package-data` or
class editable_wheel(Command):
"""Build 'editable' wheel for development.
This command is private and reserved for internal use of setuptools,
users should rely on ``setuptools.build_meta`` APIs.
(This command is reserved for internal use of setuptools).
"""
description = "DO NOT CALL DIRECTLY, INTERNAL ONLY: create PEP 660 editable wheel"
description = "create a PEP 660 'editable' wheel"
user_options = [
("dist-dir=", "d", "directory to put final built distributions in"),
@@ -120,13 +121,13 @@ class editable_wheel(Command):
self.project_dir = None
self.mode = None
def finalize_options(self) -> None:
def finalize_options(self):
dist = self.distribution
self.project_dir = dist.src_root or os.curdir
self.package_dir = dist.package_dir or {}
self.dist_dir = Path(self.dist_dir or os.path.join(self.project_dir, "dist"))
def run(self) -> None:
def run(self):
try:
self.dist_dir.mkdir(exist_ok=True)
self._ensure_dist_info()
@@ -137,15 +138,24 @@ class editable_wheel(Command):
bdist_wheel.write_wheelfile(self.dist_info_dir)
self._create_wheel_file(bdist_wheel)
except Exception:
except Exception as ex:
traceback.print_exc()
project = self.distribution.name or self.distribution.get_name()
_DebuggingTips.emit(project=project)
raise
msg = """
Support for editable installs via PEP 660 was recently introduced
in `setuptools`. If you are seeing this error, please report to:
https://github.com/pypa/setuptools/issues
Meanwhile you can try the legacy behavior by setting an
environment variable and trying to install again:
SETUPTOOLS_ENABLE_FEATURES="legacy-editable"
"""
raise errors.InternalError(cleandoc(msg)) from ex
def _ensure_dist_info(self):
if self.dist_info_dir is None:
dist_info = cast(dist_info_cls, self.reinitialize_command("dist_info"))
dist_info = self.reinitialize_command("dist_info")
dist_info.output_dir = self.dist_dir
dist_info.ensure_finalized()
dist_info.run()
@@ -164,13 +174,13 @@ class editable_wheel(Command):
installer = _NamespaceInstaller(dist, installation_dir, pth_prefix, src_root)
installer.install_namespaces()
def _find_egg_info_dir(self) -> str | None:
def _find_egg_info_dir(self) -> Optional[str]:
parent_dir = Path(self.dist_info_dir).parent if self.dist_info_dir else Path()
candidates = map(str, parent_dir.glob("*.egg-info"))
return next(candidates, None)
def _configure_build(
self, name: str, unpacked_wheel: StrPath, build_lib: StrPath, tmp_dir: StrPath
self, name: str, unpacked_wheel: _Path, build_lib: _Path, tmp_dir: _Path
):
"""Configure commands to behave in the following ways:
@@ -192,18 +202,12 @@ class editable_wheel(Command):
scripts = str(Path(unpacked_wheel, f"{name}.data", "scripts"))
# egg-info may be generated again to create a manifest (used for package data)
egg_info = cast(
egg_info_cls, dist.reinitialize_command("egg_info", reinit_subcommands=True)
)
egg_info = dist.reinitialize_command("egg_info", reinit_subcommands=True)
egg_info.egg_base = str(tmp_dir)
egg_info.ignore_egg_info_in_manifest = True
build = cast(
build_cls, dist.reinitialize_command("build", reinit_subcommands=True)
)
install = cast(
install_cls, dist.reinitialize_command("install", reinit_subcommands=True)
)
build = dist.reinitialize_command("build", reinit_subcommands=True)
install = dist.reinitialize_command("install", reinit_subcommands=True)
build.build_platlib = build.build_purelib = build.build_lib = build_lib
install.install_purelib = install.install_platlib = install.install_lib = wheel
@@ -211,14 +215,12 @@ class editable_wheel(Command):
install.install_headers = headers
install.install_data = data
install_scripts = cast(
install_scripts_cls, dist.get_command_obj("install_scripts")
)
install_scripts = dist.get_command_obj("install_scripts")
install_scripts.no_ep = True
build.build_temp = str(tmp_dir)
build_py = cast(build_py_cls, dist.get_command_obj("build_py"))
build_py = dist.get_command_obj("build_py")
build_py.compile = False
build_py.existing_egg_info_dir = self._find_egg_info_dir()
@@ -238,9 +240,9 @@ class editable_wheel(Command):
elif hasattr(cmd, "inplace"):
cmd.inplace = True # backward compatibility with distutils
def _collect_build_outputs(self) -> tuple[list[str], dict[str, str]]:
files: list[str] = []
mapping: dict[str, str] = {}
def _collect_build_outputs(self) -> Tuple[List[str], Dict[str, str]]:
files: List[str] = []
mapping: Dict[str, str] = {}
build = self.get_finalized_command("build")
for cmd_name in build.get_sub_commands():
@@ -253,12 +255,8 @@ class editable_wheel(Command):
return files, mapping
def _run_build_commands(
self,
dist_name: str,
unpacked_wheel: StrPath,
build_lib: StrPath,
tmp_dir: StrPath,
) -> tuple[list[str], dict[str, str]]:
self, dist_name: str, unpacked_wheel: _Path, build_lib: _Path, tmp_dir: _Path
) -> Tuple[List[str], Dict[str, str]]:
self._configure_build(dist_name, unpacked_wheel, build_lib, tmp_dir)
self._run_build_subcommands()
files, mapping = self._collect_build_outputs()
@@ -267,7 +265,7 @@ class editable_wheel(Command):
self._run_install("data")
return files, mapping
def _run_build_subcommands(self) -> None:
def _run_build_subcommands(self):
"""
Issue #3501 indicates that some plugins/customizations might rely on:
@@ -278,13 +276,13 @@ class editable_wheel(Command):
This method implements a temporary workaround to support the ecosystem
while the implementations catch up.
"""
# TODO: Once plugins/customizations had the chance to catch up, replace
# TODO: Once plugins/customisations had the chance to catch up, replace
# `self._run_build_subcommands()` with `self.run_command("build")`.
# Also remove _safely_run, TestCustomBuildPy. Suggested date: Aug/2023.
build = self.get_finalized_command("build")
build: Command = self.get_finalized_command("build")
for name in build.get_sub_commands():
cmd = self.get_finalized_command(name)
if name == "build_py" and type(cmd) is not build_py_cls:
if name == "build_py" and type(cmd) != build_py_cls:
self._safely_run(name)
else:
self.run_command(name)
@@ -293,29 +291,21 @@ class editable_wheel(Command):
try:
return self.run_command(cmd_name)
except Exception:
SetuptoolsDeprecationWarning.emit(
"Customization incompatible with editable install",
f"""
{traceback.format_exc()}
msg = f"""{traceback.format_exc()}\n
If you are seeing this warning it is very likely that a setuptools
plugin or customization overrides the `{cmd_name}` command, without
taking into consideration how editable installs run build steps
starting from v64.0.0.
If you are seeing this warning it is very likely that a setuptools
plugin or customization overrides the `{cmd_name}` command, without
taking into consideration how editable installs run build steps
starting from setuptools v64.0.0.
Plugin authors and developers relying on custom build steps are encouraged
to update their `{cmd_name}` implementation considering the information in
https://setuptools.pypa.io/en/latest/userguide/extension.html
about editable installs.
Plugin authors and developers relying on custom build steps are
encouraged to update their `{cmd_name}` implementation considering the
information about editable installs in
https://setuptools.pypa.io/en/latest/userguide/extension.html.
For the time being `setuptools` will silence this error and ignore
the faulty command, but this behavior will change in future versions.
""",
# TODO: define due_date
# There is a series of shortcomings with the available editable install
# methods, and they are very controversial. This is something that still
# needs work.
)
For the time being `setuptools` will silence this error and ignore
the faulty command, but this behaviour will change in future versions.\n
"""
warnings.warn(msg, SetuptoolsDeprecationWarning, stacklevel=2)
def _create_wheel_file(self, bdist_wheel):
from wheel.wheelfile import WheelFile
@@ -336,7 +326,7 @@ class editable_wheel(Command):
with unpacked_wheel as unpacked, build_lib as lib, build_tmp as tmp:
unpacked_dist_info = Path(unpacked, Path(self.dist_info_dir).name)
shutil.copytree(self.dist_info_dir, unpacked_dist_info)
self._install_namespaces(unpacked, dist_name)
self._install_namespaces(unpacked, dist_info.name)
files, mapping = self._run_build_commands(dist_name, unpacked, lib, tmp)
strategy = self._select_strategy(dist_name, tag, lib)
with strategy, WheelFile(wheel_path, "w") as wheel_obj:
@@ -355,8 +345,8 @@ class editable_wheel(Command):
self,
name: str,
tag: str,
build_lib: StrPath,
) -> EditableStrategy:
build_lib: _Path,
) -> "EditableStrategy":
"""Decides which strategy to use to implement an editable installation."""
build_name = f"__editable__.{name}-{tag}"
project_dir = Path(self.project_dir)
@@ -379,30 +369,28 @@ class editable_wheel(Command):
class EditableStrategy(Protocol):
def __call__(
self, wheel: WheelFile, files: list[str], mapping: Mapping[str, str]
) -> object: ...
def __enter__(self) -> Self: ...
def __exit__(
self,
_exc_type: type[BaseException] | None,
_exc_value: BaseException | None,
_traceback: TracebackType | None,
) -> object: ...
def __call__(self, wheel: "WheelFile", files: List[str], mapping: Dict[str, str]):
...
def __enter__(self):
...
def __exit__(self, _exc_type, _exc_value, _traceback):
...
class _StaticPth:
def __init__(self, dist: Distribution, name: str, path_entries: list[Path]) -> None:
def __init__(self, dist: Distribution, name: str, path_entries: List[Path]):
self.dist = dist
self.name = name
self.path_entries = path_entries
def __call__(self, wheel: WheelFile, files: list[str], mapping: Mapping[str, str]):
entries = "\n".join(str(p.resolve()) for p in self.path_entries)
contents = _encode_pth(f"{entries}\n")
def __call__(self, wheel: "WheelFile", files: List[str], mapping: Dict[str, str]):
entries = "\n".join((str(p.resolve()) for p in self.path_entries))
contents = bytes(f"{entries}\n", "utf-8")
wheel.writestr(f"__editable__.{self.name}.pth", contents)
def __enter__(self) -> Self:
def __enter__(self):
msg = f"""
Editable install will be performed using .pth file to extend `sys.path` with:
{list(map(os.fspath, self.path_entries))!r}
@@ -410,13 +398,8 @@ class _StaticPth:
_logger.warning(msg + _LENIENT_WARNING)
return self
def __exit__(
self,
_exc_type: object,
_exc_value: object,
_traceback: object,
) -> None:
pass
def __exit__(self, _exc_type, _exc_value, _traceback):
...
class _LinkTree(_StaticPth):
@@ -429,24 +412,22 @@ class _LinkTree(_StaticPth):
By collocating ``auxiliary_dir`` and the original source code, limitations
with hardlinks should be avoided.
"""
def __init__(
self,
dist: Distribution,
self, dist: Distribution,
name: str,
auxiliary_dir: StrPath,
build_lib: StrPath,
) -> None:
auxiliary_dir: _Path,
build_lib: _Path,
):
self.auxiliary_dir = Path(auxiliary_dir)
self.build_lib = Path(build_lib).resolve()
self._file = dist.get_command_obj("build_py").copy_file
super().__init__(dist, name, [self.auxiliary_dir])
def __call__(self, wheel: WheelFile, files: list[str], mapping: Mapping[str, str]):
def __call__(self, wheel: "WheelFile", files: List[str], mapping: Dict[str, str]):
self._create_links(files, mapping)
super().__call__(wheel, files, mapping)
def _normalize_output(self, file: str) -> str | None:
def _normalize_output(self, file: str) -> Optional[str]:
# Files relative to build_lib will be normalized to None
with suppress(ValueError):
path = Path(file).resolve().relative_to(self.build_lib)
@@ -459,12 +440,14 @@ class _LinkTree(_StaticPth):
dest.parent.mkdir(parents=True)
self._file(src_file, dest, link=link)
def _create_links(self, outputs, output_mapping: Mapping[str, str]):
def _create_links(self, outputs, output_mapping):
self.auxiliary_dir.mkdir(parents=True, exist_ok=True)
link_type = "sym" if _can_symlink_files(self.auxiliary_dir) else "hard"
normalised = ((self._normalize_output(k), v) for k, v in output_mapping.items())
# remove files that are not relative to build_lib
mappings = {k: v for k, v in normalised if k is not None}
mappings = {
self._normalize_output(k): v
for k, v in output_mapping.items()
}
mappings.pop(None, None) # remove files that are not relative to build_lib
for output in outputs:
relative = self._normalize_output(output)
@@ -474,17 +457,12 @@ class _LinkTree(_StaticPth):
for relative, src in mappings.items():
self._create_file(relative, src, link=link_type)
def __enter__(self) -> Self:
def __enter__(self):
msg = "Strict editable install will be performed using a link tree.\n"
_logger.warning(msg + _STRICT_WARNING)
return self
def __exit__(
self,
_exc_type: object,
_exc_value: object,
_traceback: object,
) -> None:
def __exit__(self, _exc_type, _exc_value, _traceback):
msg = f"""\n
Strict editable installation performed using the auxiliary directory:
{self.auxiliary_dir}
@@ -492,91 +470,44 @@ class _LinkTree(_StaticPth):
Please be careful to not remove this directory, otherwise you might not be able
to import/use your package.
"""
InformationOnly.emit("Editable installation.", msg)
warnings.warn(msg, InformationOnly)
class _TopLevelFinder:
def __init__(self, dist: Distribution, name: str) -> None:
def __init__(self, dist: Distribution, name: str):
self.dist = dist
self.name = name
def template_vars(self) -> tuple[str, str, dict[str, str], dict[str, list[str]]]:
def __call__(self, wheel: "WheelFile", files: List[str], mapping: Dict[str, str]):
src_root = self.dist.src_root or os.curdir
top_level = chain(_find_packages(self.dist), _find_top_level_modules(self.dist))
package_dir = self.dist.package_dir or {}
roots = _find_package_roots(top_level, package_dir, src_root)
namespaces_ = dict(
chain(
_find_namespaces(self.dist.packages or [], roots),
((ns, []) for ns in _find_virtual_namespaces(roots)),
)
)
legacy_namespaces = {
pkg: find_package_path(pkg, roots, self.dist.src_root or "")
for pkg in self.dist.namespace_packages or []
}
mapping = {**roots, **legacy_namespaces}
# ^-- We need to explicitly add the legacy_namespaces to the mapping to be
# able to import their modules even if another package sharing the same
# namespace is installed in a conventional (non-editable) way.
namespaces_: Dict[str, List[str]] = dict(chain(
_find_namespaces(self.dist.packages or [], roots),
((ns, []) for ns in _find_virtual_namespaces(roots)),
))
name = f"__editable__.{self.name}.finder"
finder = _normalization.safe_identifier(name)
return finder, name, mapping, namespaces_
finder = _make_identifier(name)
content = bytes(_finder_template(name, roots, namespaces_), "utf-8")
wheel.writestr(f"{finder}.py", content)
def get_implementation(self) -> Iterator[tuple[str, bytes]]:
finder, name, mapping, namespaces_ = self.template_vars()
content = bytes(f"import {finder}; {finder}.install()", "utf-8")
wheel.writestr(f"__editable__.{self.name}.pth", content)
content = bytes(_finder_template(name, mapping, namespaces_), "utf-8")
yield (f"{finder}.py", content)
content = _encode_pth(f"import {finder}; {finder}.install()")
yield (f"__editable__.{self.name}.pth", content)
def __call__(self, wheel: WheelFile, files: list[str], mapping: Mapping[str, str]):
for file, content in self.get_implementation():
wheel.writestr(file, content)
def __enter__(self) -> Self:
def __enter__(self):
msg = "Editable install will be performed using a meta path finder.\n"
_logger.warning(msg + _LENIENT_WARNING)
return self
def __exit__(
self,
_exc_type: object,
_exc_value: object,
_traceback: object,
) -> None:
def __exit__(self, _exc_type, _exc_value, _traceback):
msg = """\n
Please be careful with folders in your working directory with the same
name as your package as they may take precedence during imports.
"""
InformationOnly.emit("Editable installation.", msg)
def _encode_pth(content: str) -> bytes:
"""
Prior to Python 3.13 (see https://github.com/python/cpython/issues/77102),
.pth files are always read with 'locale' encoding, the recommendation
from the cpython core developers is to write them as ``open(path, "w")``
and ignore warnings (see python/cpython#77102, pypa/setuptools#3937).
This function tries to simulate this behavior without having to create an
actual file, in a way that supports a range of active Python versions.
(There seems to be some variety in the way different version of Python handle
``encoding=None``, not all of them use ``locale.getpreferredencoding(False)``
or ``locale.getencoding()``).
"""
with io.BytesIO() as buffer:
wrapper = io.TextIOWrapper(buffer, encoding=py312.PTH_ENCODING)
# TODO: Python 3.13 replace the whole function with `bytes(content, "utf-8")`
wrapper.write(content)
wrapper.flush()
buffer.seek(0)
return buffer.read()
warnings.warn(msg, InformationOnly)
def _can_symlink_files(base_dir: Path) -> bool:
@@ -600,7 +531,7 @@ def _can_symlink_files(base_dir: Path) -> bool:
def _simple_layout(
packages: Iterable[str], package_dir: dict[str, str], project_dir: StrPath
packages: Iterable[str], package_dir: Dict[str, str], project_dir: Path
) -> bool:
"""Return ``True`` if:
- all packages are contained by the same parent directory, **and**
@@ -630,12 +561,15 @@ def _simple_layout(
>>> _simple_layout([], {"a": "_a", "": "src"}, "/tmp/myproj")
False
"""
layout = {pkg: find_package_path(pkg, package_dir, project_dir) for pkg in packages}
layout = {
pkg: find_package_path(pkg, package_dir, project_dir)
for pkg in packages
}
if not layout:
return set(package_dir) in ({}, {""})
parent = os.path.commonpath(starmap(_parent_path, layout.items()))
parent = os.path.commonpath([_parent_path(k, v) for k, v in layout.items()])
return all(
_path.same_path(Path(parent, *key.split('.')), value)
_normalize_path(Path(parent, *key.split('.'))) == _normalize_path(value)
for key, value in layout.items()
)
@@ -650,7 +584,7 @@ def _parent_path(pkg, pkg_path):
>>> _parent_path("b", "src/c")
'src/c'
"""
parent = pkg_path[: -len(pkg)] if pkg_path.endswith(pkg) else pkg_path
parent = pkg_path[:-len(pkg)] if pkg_path.endswith(pkg) else pkg_path
return parent.rstrip("/" + os.sep)
@@ -682,9 +616,9 @@ def _find_top_level_modules(dist: Distribution) -> Iterator[str]:
def _find_package_roots(
packages: Iterable[str],
package_dir: Mapping[str, str],
src_root: StrPath,
) -> dict[str, str]:
pkg_roots: dict[str, str] = {
src_root: _Path,
) -> Dict[str, str]:
pkg_roots: Dict[str, str] = {
pkg: _absolute_root(find_package_path(pkg, package_dir, src_root))
for pkg in sorted(packages)
}
@@ -692,7 +626,7 @@ def _find_package_roots(
return _remove_nested(pkg_roots)
def _absolute_root(path: StrPath) -> str:
def _absolute_root(path: _Path) -> str:
"""Works for packages and top-level modules"""
path_ = Path(path)
parent = path_.parent
@@ -703,7 +637,7 @@ def _absolute_root(path: StrPath) -> str:
return str(parent.resolve() / path_.name)
def _find_virtual_namespaces(pkg_roots: dict[str, str]) -> Iterator[str]:
def _find_virtual_namespaces(pkg_roots: Dict[str, str]) -> Iterator[str]:
"""By carefully designing ``package_dir``, it is possible to implement the logical
structure of PEP 420 in a package without the corresponding directories.
@@ -728,15 +662,15 @@ def _find_virtual_namespaces(pkg_roots: dict[str, str]) -> Iterator[str]:
def _find_namespaces(
packages: list[str], pkg_roots: dict[str, str]
) -> Iterator[tuple[str, list[str]]]:
packages: List[str], pkg_roots: Dict[str, str]
) -> Iterator[Tuple[str, List[str]]]:
for pkg in packages:
path = find_package_path(pkg, pkg_roots, "")
if Path(path).exists() and not Path(path, "__init__.py").exists():
yield (pkg, [path])
def _remove_nested(pkg_roots: dict[str, str]) -> dict[str, str]:
def _remove_nested(pkg_roots: Dict[str, str]) -> Dict[str, str]:
output = dict(pkg_roots.copy())
for pkg, path in reversed(list(pkg_roots.items())):
@@ -764,32 +698,52 @@ def _is_nested(pkg: str, pkg_path: str, parent: str, parent_path: str) -> bool:
>>> _is_nested("b.a", "path/b/a", "a", "path/a")
False
"""
norm_pkg_path = _path.normpath(pkg_path)
norm_pkg_path = _normalize_path(pkg_path)
rest = pkg.replace(parent, "", 1).strip(".").split(".")
return pkg.startswith(parent) and norm_pkg_path == _path.normpath(
Path(parent_path, *rest)
return (
pkg.startswith(parent)
and norm_pkg_path == _normalize_path(Path(parent_path, *rest))
)
def _normalize_path(filename: _Path) -> str:
"""Normalize a file/dir name for comparison purposes"""
# See pkg_resources.normalize_path
file = os.path.abspath(filename) if sys.platform == 'cygwin' else filename
return os.path.normcase(os.path.realpath(os.path.normpath(file)))
def _empty_dir(dir_: _P) -> _P:
"""Create a directory ensured to be empty. Existing files may be removed."""
_shutil.rmtree(dir_, ignore_errors=True)
shutil.rmtree(dir_, ignore_errors=True)
os.makedirs(dir_)
return dir_
def _make_identifier(name: str) -> str:
"""Make a string safe to be used as Python identifier.
>>> _make_identifier("12abc")
'_12abc'
>>> _make_identifier("__editable__.myns.pkg-78.9.3_local")
'__editable___myns_pkg_78_9_3_local'
"""
safe = re.sub(r'\W|^(?=\d)', '_', name)
assert safe.isidentifier()
return safe
class _NamespaceInstaller(namespaces.Installer):
def __init__(self, distribution, installation_dir, editable_name, src_root) -> None:
def __init__(self, distribution, installation_dir, editable_name, src_root):
self.distribution = distribution
self.src_root = src_root
self.installation_dir = installation_dir
self.editable_name = editable_name
self.outputs: list[str] = []
self.outputs = []
self.dry_run = False
def _get_nspkg_file(self):
def _get_target(self):
"""Installation target."""
return os.path.join(self.installation_dir, self.editable_name + self.nspkg_ext)
return os.path.join(self.installation_dir, self.editable_name)
def _get_root(self):
"""Where the modules/packages should be loaded from."""
@@ -797,68 +751,51 @@ class _NamespaceInstaller(namespaces.Installer):
_FINDER_TEMPLATE = """\
from __future__ import annotations
import sys
from importlib.machinery import ModuleSpec, PathFinder
from importlib.machinery import ModuleSpec
from importlib.machinery import all_suffixes as module_suffixes
from importlib.util import spec_from_file_location
from itertools import chain
from pathlib import Path
MAPPING: dict[str, str] = {mapping!r}
NAMESPACES: dict[str, list[str]] = {namespaces!r}
MAPPING = {mapping!r}
NAMESPACES = {namespaces!r}
PATH_PLACEHOLDER = {name!r} + ".__path_hook__"
class _EditableFinder: # MetaPathFinder
@classmethod
def find_spec(cls, fullname: str, path=None, target=None) -> ModuleSpec | None: # type: ignore
# Top-level packages and modules (we know these exist in the FS)
if fullname in MAPPING:
pkg_path = MAPPING[fullname]
return cls._find_spec(fullname, Path(pkg_path))
def find_spec(cls, fullname, path=None, target=None):
for pkg, pkg_path in reversed(list(MAPPING.items())):
if fullname == pkg or fullname.startswith(f"{{pkg}}."):
rest = fullname.replace(pkg, "", 1).strip(".").split(".")
return cls._find_spec(fullname, Path(pkg_path, *rest))
# Handle immediate children modules (required for namespaces to work)
# To avoid problems with case sensitivity in the file system we delegate
# to the importlib.machinery implementation.
parent, _, child = fullname.rpartition(".")
if parent and parent in MAPPING:
return PathFinder.find_spec(fullname, path=[MAPPING[parent]])
# Other levels of nesting should be handled automatically by importlib
# using the parent path.
return None
@classmethod
def _find_spec(cls, fullname: str, candidate_path: Path) -> ModuleSpec | None:
def _find_spec(cls, fullname, candidate_path):
init = candidate_path / "__init__.py"
candidates = (candidate_path.with_suffix(x) for x in module_suffixes())
for candidate in chain([init], candidates):
if candidate.exists():
return spec_from_file_location(fullname, candidate)
return None
class _EditableNamespaceFinder: # PathEntryFinder
@classmethod
def _path_hook(cls, path) -> type[_EditableNamespaceFinder]:
def _path_hook(cls, path):
if path == PATH_PLACEHOLDER:
return cls
raise ImportError
@classmethod
def _paths(cls, fullname: str) -> list[str]:
paths = NAMESPACES[fullname]
if not paths and fullname in MAPPING:
paths = [MAPPING[fullname]]
# Always add placeholder, for 2 reasons:
# 1. __path__ cannot be empty for the spec to be considered namespace.
# 2. In the case of nested namespaces, we need to force
# import machinery to query _EditableNamespaceFinder again.
return [*paths, PATH_PLACEHOLDER]
def _paths(cls, fullname):
# Ensure __path__ is not empty for the spec to be considered a namespace.
return NAMESPACES[fullname] or MAPPING.get(fullname) or [PATH_PLACEHOLDER]
@classmethod
def find_spec(cls, fullname: str, target=None) -> ModuleSpec | None: # type: ignore
def find_spec(cls, fullname, target=None):
if fullname in NAMESPACES:
spec = ModuleSpec(fullname, None, is_package=True)
spec.submodule_search_locations = cls._paths(fullname)
@@ -866,7 +803,7 @@ class _EditableNamespaceFinder: # PathEntryFinder
return None
@classmethod
def find_module(cls, _fullname) -> None:
def find_module(cls, fullname):
return None
@@ -886,7 +823,7 @@ def install():
def _finder_template(
name: str, mapping: Mapping[str, str], namespaces: dict[str, list[str]]
name: str, mapping: Mapping[str, str], namespaces: Dict[str, List[str]]
) -> str:
"""Create a string containing the code for the``MetaPathFinder`` and
``PathEntryFinder``.
@@ -895,31 +832,13 @@ def _finder_template(
return _FINDER_TEMPLATE.format(name=name, mapping=mapping, namespaces=namespaces)
class InformationOnly(UserWarning):
"""Currently there is no clear way of displaying messages to the users
that use the setuptools backend directly via ``pip``.
The only thing that might work is a warning, although it is not the
most appropriate tool for the job...
"""
class LinksNotSupported(errors.FileError):
"""File system does not seem to support either symlinks or hard links."""
class _DebuggingTips(SetuptoolsWarning):
_SUMMARY = "Problem in editable installation."
_DETAILS = """
An error happened while installing `{project}` in editable mode.
The following steps are recommended to help debug this problem:
- Try to install the project normally, without using the editable mode.
Does the error still persist?
(If it does, try fixing the problem before attempting the editable mode).
- If you are using binary extensions, make sure you have all OS-level
dependencies installed (e.g. compilers, toolchains, binary libraries, ...).
- Try the latest version of setuptools (maybe the error was already fixed).
- If you (or your project dependencies) are using any setuptools extension
or customization, make sure they support the editable mode.
After following the steps above, if the problem still persists and
you think this is related to how setuptools handles editable installations,
please submit a reproducible example
(see https://stackoverflow.com/help/minimal-reproducible-example) to:
https://github.com/pypa/setuptools/issues
"""
_SEE_DOCS = "userguide/development_mode.html"