editable_wheel.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  1. """
  2. Create a wheel that, when installed, will make the source package 'editable'
  3. (add it to the interpreter's path, including metadata) per PEP 660. Replaces
  4. 'setup.py develop'.
  5. .. note::
  6. One of the mechanisms briefly mentioned in PEP 660 to implement editable installs is
  7. to create a separated directory inside ``build`` and use a .pth file to point to that
  8. directory. In the context of this file such directory is referred as
  9. *auxiliary build directory* or ``auxiliary_dir``.
  10. """
  11. import logging
  12. import io
  13. import os
  14. import shutil
  15. import sys
  16. import traceback
  17. from contextlib import suppress
  18. from enum import Enum
  19. from inspect import cleandoc
  20. from itertools import chain
  21. from pathlib import Path
  22. from tempfile import TemporaryDirectory
  23. from typing import (
  24. TYPE_CHECKING,
  25. Dict,
  26. Iterable,
  27. Iterator,
  28. List,
  29. Mapping,
  30. Optional,
  31. Tuple,
  32. TypeVar,
  33. Union,
  34. )
  35. from .. import (
  36. Command,
  37. _normalization,
  38. _path,
  39. errors,
  40. namespaces,
  41. )
  42. from ..discovery import find_package_path
  43. from ..dist import Distribution
  44. from ..warnings import (
  45. InformationOnly,
  46. SetuptoolsDeprecationWarning,
  47. SetuptoolsWarning,
  48. )
  49. from .build_py import build_py as build_py_cls
  50. if TYPE_CHECKING:
  51. from wheel.wheelfile import WheelFile # noqa
  52. if sys.version_info >= (3, 8):
  53. from typing import Protocol
  54. elif TYPE_CHECKING:
  55. from typing_extensions import Protocol
  56. else:
  57. from abc import ABC as Protocol
  58. _Path = Union[str, Path]
  59. _P = TypeVar("_P", bound=_Path)
  60. _logger = logging.getLogger(__name__)
  61. class _EditableMode(Enum):
  62. """
  63. Possible editable installation modes:
  64. `lenient` (new files automatically added to the package - DEFAULT);
  65. `strict` (requires a new installation when files are added/removed); or
  66. `compat` (attempts to emulate `python setup.py develop` - DEPRECATED).
  67. """
  68. STRICT = "strict"
  69. LENIENT = "lenient"
  70. COMPAT = "compat" # TODO: Remove `compat` after Dec/2022.
  71. @classmethod
  72. def convert(cls, mode: Optional[str]) -> "_EditableMode":
  73. if not mode:
  74. return _EditableMode.LENIENT # default
  75. _mode = mode.upper()
  76. if _mode not in _EditableMode.__members__:
  77. raise errors.OptionError(f"Invalid editable mode: {mode!r}. Try: 'strict'.")
  78. if _mode == "COMPAT":
  79. SetuptoolsDeprecationWarning.emit(
  80. "Compat editable installs",
  81. """
  82. The 'compat' editable mode is transitional and will be removed
  83. in future versions of `setuptools`.
  84. Please adapt your code accordingly to use either the 'strict' or the
  85. 'lenient' modes.
  86. """,
  87. see_docs="userguide/development_mode.html",
  88. # TODO: define due_date
  89. # There is a series of shortcomings with the available editable install
  90. # methods, and they are very controversial. This is something that still
  91. # needs work.
  92. # Moreover, `pip` is still hiding this warning, so users are not aware.
  93. )
  94. return _EditableMode[_mode]
  95. _STRICT_WARNING = """
  96. New or renamed files may not be automatically picked up without a new installation.
  97. """
  98. _LENIENT_WARNING = """
  99. Options like `package-data`, `include/exclude-package-data` or
  100. `packages.find.exclude/include` may have no effect.
  101. """
  102. class editable_wheel(Command):
  103. """Build 'editable' wheel for development.
  104. This command is private and reserved for internal use of setuptools,
  105. users should rely on ``setuptools.build_meta`` APIs.
  106. """
  107. description = "DO NOT CALL DIRECTLY, INTERNAL ONLY: create PEP 660 editable wheel"
  108. user_options = [
  109. ("dist-dir=", "d", "directory to put final built distributions in"),
  110. ("dist-info-dir=", "I", "path to a pre-build .dist-info directory"),
  111. ("mode=", None, cleandoc(_EditableMode.__doc__ or "")),
  112. ]
  113. def initialize_options(self):
  114. self.dist_dir = None
  115. self.dist_info_dir = None
  116. self.project_dir = None
  117. self.mode = None
  118. def finalize_options(self):
  119. dist = self.distribution
  120. self.project_dir = dist.src_root or os.curdir
  121. self.package_dir = dist.package_dir or {}
  122. self.dist_dir = Path(self.dist_dir or os.path.join(self.project_dir, "dist"))
  123. def run(self):
  124. try:
  125. self.dist_dir.mkdir(exist_ok=True)
  126. self._ensure_dist_info()
  127. # Add missing dist_info files
  128. self.reinitialize_command("bdist_wheel")
  129. bdist_wheel = self.get_finalized_command("bdist_wheel")
  130. bdist_wheel.write_wheelfile(self.dist_info_dir)
  131. self._create_wheel_file(bdist_wheel)
  132. except Exception:
  133. traceback.print_exc()
  134. project = self.distribution.name or self.distribution.get_name()
  135. _DebuggingTips.emit(project=project)
  136. raise
  137. def _ensure_dist_info(self):
  138. if self.dist_info_dir is None:
  139. dist_info = self.reinitialize_command("dist_info")
  140. dist_info.output_dir = self.dist_dir
  141. dist_info.ensure_finalized()
  142. dist_info.run()
  143. self.dist_info_dir = dist_info.dist_info_dir
  144. else:
  145. assert str(self.dist_info_dir).endswith(".dist-info")
  146. assert Path(self.dist_info_dir, "METADATA").exists()
  147. def _install_namespaces(self, installation_dir, pth_prefix):
  148. # XXX: Only required to support the deprecated namespace practice
  149. dist = self.distribution
  150. if not dist.namespace_packages:
  151. return
  152. src_root = Path(self.project_dir, self.package_dir.get("", ".")).resolve()
  153. installer = _NamespaceInstaller(dist, installation_dir, pth_prefix, src_root)
  154. installer.install_namespaces()
  155. def _find_egg_info_dir(self) -> Optional[str]:
  156. parent_dir = Path(self.dist_info_dir).parent if self.dist_info_dir else Path()
  157. candidates = map(str, parent_dir.glob("*.egg-info"))
  158. return next(candidates, None)
  159. def _configure_build(
  160. self, name: str, unpacked_wheel: _Path, build_lib: _Path, tmp_dir: _Path
  161. ):
  162. """Configure commands to behave in the following ways:
  163. - Build commands can write to ``build_lib`` if they really want to...
  164. (but this folder is expected to be ignored and modules are expected to live
  165. in the project directory...)
  166. - Binary extensions should be built in-place (editable_mode = True)
  167. - Data/header/script files are not part of the "editable" specification
  168. so they are written directly to the unpacked_wheel directory.
  169. """
  170. # Non-editable files (data, headers, scripts) are written directly to the
  171. # unpacked_wheel
  172. dist = self.distribution
  173. wheel = str(unpacked_wheel)
  174. build_lib = str(build_lib)
  175. data = str(Path(unpacked_wheel, f"{name}.data", "data"))
  176. headers = str(Path(unpacked_wheel, f"{name}.data", "headers"))
  177. scripts = str(Path(unpacked_wheel, f"{name}.data", "scripts"))
  178. # egg-info may be generated again to create a manifest (used for package data)
  179. egg_info = dist.reinitialize_command("egg_info", reinit_subcommands=True)
  180. egg_info.egg_base = str(tmp_dir)
  181. egg_info.ignore_egg_info_in_manifest = True
  182. build = dist.reinitialize_command("build", reinit_subcommands=True)
  183. install = dist.reinitialize_command("install", reinit_subcommands=True)
  184. build.build_platlib = build.build_purelib = build.build_lib = build_lib
  185. install.install_purelib = install.install_platlib = install.install_lib = wheel
  186. install.install_scripts = build.build_scripts = scripts
  187. install.install_headers = headers
  188. install.install_data = data
  189. install_scripts = dist.get_command_obj("install_scripts")
  190. install_scripts.no_ep = True
  191. build.build_temp = str(tmp_dir)
  192. build_py = dist.get_command_obj("build_py")
  193. build_py.compile = False
  194. build_py.existing_egg_info_dir = self._find_egg_info_dir()
  195. self._set_editable_mode()
  196. build.ensure_finalized()
  197. install.ensure_finalized()
  198. def _set_editable_mode(self):
  199. """Set the ``editable_mode`` flag in the build sub-commands"""
  200. dist = self.distribution
  201. build = dist.get_command_obj("build")
  202. for cmd_name in build.get_sub_commands():
  203. cmd = dist.get_command_obj(cmd_name)
  204. if hasattr(cmd, "editable_mode"):
  205. cmd.editable_mode = True
  206. elif hasattr(cmd, "inplace"):
  207. cmd.inplace = True # backward compatibility with distutils
  208. def _collect_build_outputs(self) -> Tuple[List[str], Dict[str, str]]:
  209. files: List[str] = []
  210. mapping: Dict[str, str] = {}
  211. build = self.get_finalized_command("build")
  212. for cmd_name in build.get_sub_commands():
  213. cmd = self.get_finalized_command(cmd_name)
  214. if hasattr(cmd, "get_outputs"):
  215. files.extend(cmd.get_outputs() or [])
  216. if hasattr(cmd, "get_output_mapping"):
  217. mapping.update(cmd.get_output_mapping() or {})
  218. return files, mapping
  219. def _run_build_commands(
  220. self, dist_name: str, unpacked_wheel: _Path, build_lib: _Path, tmp_dir: _Path
  221. ) -> Tuple[List[str], Dict[str, str]]:
  222. self._configure_build(dist_name, unpacked_wheel, build_lib, tmp_dir)
  223. self._run_build_subcommands()
  224. files, mapping = self._collect_build_outputs()
  225. self._run_install("headers")
  226. self._run_install("scripts")
  227. self._run_install("data")
  228. return files, mapping
  229. def _run_build_subcommands(self):
  230. """
  231. Issue #3501 indicates that some plugins/customizations might rely on:
  232. 1. ``build_py`` not running
  233. 2. ``build_py`` always copying files to ``build_lib``
  234. However both these assumptions may be false in editable_wheel.
  235. This method implements a temporary workaround to support the ecosystem
  236. while the implementations catch up.
  237. """
  238. # TODO: Once plugins/customisations had the chance to catch up, replace
  239. # `self._run_build_subcommands()` with `self.run_command("build")`.
  240. # Also remove _safely_run, TestCustomBuildPy. Suggested date: Aug/2023.
  241. build: Command = self.get_finalized_command("build")
  242. for name in build.get_sub_commands():
  243. cmd = self.get_finalized_command(name)
  244. if name == "build_py" and type(cmd) != build_py_cls:
  245. self._safely_run(name)
  246. else:
  247. self.run_command(name)
  248. def _safely_run(self, cmd_name: str):
  249. try:
  250. return self.run_command(cmd_name)
  251. except Exception:
  252. SetuptoolsDeprecationWarning.emit(
  253. "Customization incompatible with editable install",
  254. f"""
  255. {traceback.format_exc()}
  256. If you are seeing this warning it is very likely that a setuptools
  257. plugin or customization overrides the `{cmd_name}` command, without
  258. taking into consideration how editable installs run build steps
  259. starting from setuptools v64.0.0.
  260. Plugin authors and developers relying on custom build steps are
  261. encouraged to update their `{cmd_name}` implementation considering the
  262. information about editable installs in
  263. https://setuptools.pypa.io/en/latest/userguide/extension.html.
  264. For the time being `setuptools` will silence this error and ignore
  265. the faulty command, but this behaviour will change in future versions.
  266. """,
  267. # TODO: define due_date
  268. # There is a series of shortcomings with the available editable install
  269. # methods, and they are very controversial. This is something that still
  270. # needs work.
  271. )
  272. def _create_wheel_file(self, bdist_wheel):
  273. from wheel.wheelfile import WheelFile
  274. dist_info = self.get_finalized_command("dist_info")
  275. dist_name = dist_info.name
  276. tag = "-".join(bdist_wheel.get_tag())
  277. build_tag = "0.editable" # According to PEP 427 needs to start with digit
  278. archive_name = f"{dist_name}-{build_tag}-{tag}.whl"
  279. wheel_path = Path(self.dist_dir, archive_name)
  280. if wheel_path.exists():
  281. wheel_path.unlink()
  282. unpacked_wheel = TemporaryDirectory(suffix=archive_name)
  283. build_lib = TemporaryDirectory(suffix=".build-lib")
  284. build_tmp = TemporaryDirectory(suffix=".build-temp")
  285. with unpacked_wheel as unpacked, build_lib as lib, build_tmp as tmp:
  286. unpacked_dist_info = Path(unpacked, Path(self.dist_info_dir).name)
  287. shutil.copytree(self.dist_info_dir, unpacked_dist_info)
  288. self._install_namespaces(unpacked, dist_name)
  289. files, mapping = self._run_build_commands(dist_name, unpacked, lib, tmp)
  290. strategy = self._select_strategy(dist_name, tag, lib)
  291. with strategy, WheelFile(wheel_path, "w") as wheel_obj:
  292. strategy(wheel_obj, files, mapping)
  293. wheel_obj.write_files(unpacked)
  294. return wheel_path
  295. def _run_install(self, category: str):
  296. has_category = getattr(self.distribution, f"has_{category}", None)
  297. if has_category and has_category():
  298. _logger.info(f"Installing {category} as non editable")
  299. self.run_command(f"install_{category}")
  300. def _select_strategy(
  301. self,
  302. name: str,
  303. tag: str,
  304. build_lib: _Path,
  305. ) -> "EditableStrategy":
  306. """Decides which strategy to use to implement an editable installation."""
  307. build_name = f"__editable__.{name}-{tag}"
  308. project_dir = Path(self.project_dir)
  309. mode = _EditableMode.convert(self.mode)
  310. if mode is _EditableMode.STRICT:
  311. auxiliary_dir = _empty_dir(Path(self.project_dir, "build", build_name))
  312. return _LinkTree(self.distribution, name, auxiliary_dir, build_lib)
  313. packages = _find_packages(self.distribution)
  314. has_simple_layout = _simple_layout(packages, self.package_dir, project_dir)
  315. is_compat_mode = mode is _EditableMode.COMPAT
  316. if set(self.package_dir) == {""} and has_simple_layout or is_compat_mode:
  317. # src-layout(ish) is relatively safe for a simple pth file
  318. src_dir = self.package_dir.get("", ".")
  319. return _StaticPth(self.distribution, name, [Path(project_dir, src_dir)])
  320. # Use a MetaPathFinder to avoid adding accidental top-level packages/modules
  321. return _TopLevelFinder(self.distribution, name)
  322. class EditableStrategy(Protocol):
  323. def __call__(self, wheel: "WheelFile", files: List[str], mapping: Dict[str, str]):
  324. ...
  325. def __enter__(self):
  326. ...
  327. def __exit__(self, _exc_type, _exc_value, _traceback):
  328. ...
  329. class _StaticPth:
  330. def __init__(self, dist: Distribution, name: str, path_entries: List[Path]):
  331. self.dist = dist
  332. self.name = name
  333. self.path_entries = path_entries
  334. def __call__(self, wheel: "WheelFile", files: List[str], mapping: Dict[str, str]):
  335. entries = "\n".join((str(p.resolve()) for p in self.path_entries))
  336. contents = _encode_pth(f"{entries}\n")
  337. wheel.writestr(f"__editable__.{self.name}.pth", contents)
  338. def __enter__(self):
  339. msg = f"""
  340. Editable install will be performed using .pth file to extend `sys.path` with:
  341. {list(map(os.fspath, self.path_entries))!r}
  342. """
  343. _logger.warning(msg + _LENIENT_WARNING)
  344. return self
  345. def __exit__(self, _exc_type, _exc_value, _traceback):
  346. ...
  347. class _LinkTree(_StaticPth):
  348. """
  349. Creates a ``.pth`` file that points to a link tree in the ``auxiliary_dir``.
  350. This strategy will only link files (not dirs), so it can be implemented in
  351. any OS, even if that means using hardlinks instead of symlinks.
  352. By collocating ``auxiliary_dir`` and the original source code, limitations
  353. with hardlinks should be avoided.
  354. """
  355. def __init__(
  356. self,
  357. dist: Distribution,
  358. name: str,
  359. auxiliary_dir: _Path,
  360. build_lib: _Path,
  361. ):
  362. self.auxiliary_dir = Path(auxiliary_dir)
  363. self.build_lib = Path(build_lib).resolve()
  364. self._file = dist.get_command_obj("build_py").copy_file
  365. super().__init__(dist, name, [self.auxiliary_dir])
  366. def __call__(self, wheel: "WheelFile", files: List[str], mapping: Dict[str, str]):
  367. self._create_links(files, mapping)
  368. super().__call__(wheel, files, mapping)
  369. def _normalize_output(self, file: str) -> Optional[str]:
  370. # Files relative to build_lib will be normalized to None
  371. with suppress(ValueError):
  372. path = Path(file).resolve().relative_to(self.build_lib)
  373. return str(path).replace(os.sep, '/')
  374. return None
  375. def _create_file(self, relative_output: str, src_file: str, link=None):
  376. dest = self.auxiliary_dir / relative_output
  377. if not dest.parent.is_dir():
  378. dest.parent.mkdir(parents=True)
  379. self._file(src_file, dest, link=link)
  380. def _create_links(self, outputs, output_mapping):
  381. self.auxiliary_dir.mkdir(parents=True, exist_ok=True)
  382. link_type = "sym" if _can_symlink_files(self.auxiliary_dir) else "hard"
  383. mappings = {self._normalize_output(k): v for k, v in output_mapping.items()}
  384. mappings.pop(None, None) # remove files that are not relative to build_lib
  385. for output in outputs:
  386. relative = self._normalize_output(output)
  387. if relative and relative not in mappings:
  388. self._create_file(relative, output)
  389. for relative, src in mappings.items():
  390. self._create_file(relative, src, link=link_type)
  391. def __enter__(self):
  392. msg = "Strict editable install will be performed using a link tree.\n"
  393. _logger.warning(msg + _STRICT_WARNING)
  394. return self
  395. def __exit__(self, _exc_type, _exc_value, _traceback):
  396. msg = f"""\n
  397. Strict editable installation performed using the auxiliary directory:
  398. {self.auxiliary_dir}
  399. Please be careful to not remove this directory, otherwise you might not be able
  400. to import/use your package.
  401. """
  402. InformationOnly.emit("Editable installation.", msg)
  403. class _TopLevelFinder:
  404. def __init__(self, dist: Distribution, name: str):
  405. self.dist = dist
  406. self.name = name
  407. def __call__(self, wheel: "WheelFile", files: List[str], mapping: Dict[str, str]):
  408. src_root = self.dist.src_root or os.curdir
  409. top_level = chain(_find_packages(self.dist), _find_top_level_modules(self.dist))
  410. package_dir = self.dist.package_dir or {}
  411. roots = _find_package_roots(top_level, package_dir, src_root)
  412. namespaces_: Dict[str, List[str]] = dict(
  413. chain(
  414. _find_namespaces(self.dist.packages or [], roots),
  415. ((ns, []) for ns in _find_virtual_namespaces(roots)),
  416. )
  417. )
  418. legacy_namespaces = {
  419. pkg: find_package_path(pkg, roots, self.dist.src_root or "")
  420. for pkg in self.dist.namespace_packages or []
  421. }
  422. mapping = {**roots, **legacy_namespaces}
  423. # ^-- We need to explicitly add the legacy_namespaces to the mapping to be
  424. # able to import their modules even if another package sharing the same
  425. # namespace is installed in a conventional (non-editable) way.
  426. name = f"__editable__.{self.name}.finder"
  427. finder = _normalization.safe_identifier(name)
  428. content = bytes(_finder_template(name, mapping, namespaces_), "utf-8")
  429. wheel.writestr(f"{finder}.py", content)
  430. content = _encode_pth(f"import {finder}; {finder}.install()")
  431. wheel.writestr(f"__editable__.{self.name}.pth", content)
  432. def __enter__(self):
  433. msg = "Editable install will be performed using a meta path finder.\n"
  434. _logger.warning(msg + _LENIENT_WARNING)
  435. return self
  436. def __exit__(self, _exc_type, _exc_value, _traceback):
  437. msg = """\n
  438. Please be careful with folders in your working directory with the same
  439. name as your package as they may take precedence during imports.
  440. """
  441. InformationOnly.emit("Editable installation.", msg)
  442. def _encode_pth(content: str) -> bytes:
  443. """.pth files are always read with 'locale' encoding, the recommendation
  444. from the cpython core developers is to write them as ``open(path, "w")``
  445. and ignore warnings (see python/cpython#77102, pypa/setuptools#3937).
  446. This function tries to simulate this behaviour without having to create an
  447. actual file, in a way that supports a range of active Python versions.
  448. (There seems to be some variety in the way different version of Python handle
  449. ``encoding=None``, not all of them use ``locale.getpreferredencoding(False)``).
  450. """
  451. encoding = "locale" if sys.version_info >= (3, 10) else None
  452. with io.BytesIO() as buffer:
  453. wrapper = io.TextIOWrapper(buffer, encoding)
  454. wrapper.write(content)
  455. wrapper.flush()
  456. buffer.seek(0)
  457. return buffer.read()
  458. def _can_symlink_files(base_dir: Path) -> bool:
  459. with TemporaryDirectory(dir=str(base_dir.resolve())) as tmp:
  460. path1, path2 = Path(tmp, "file1.txt"), Path(tmp, "file2.txt")
  461. path1.write_text("file1", encoding="utf-8")
  462. with suppress(AttributeError, NotImplementedError, OSError):
  463. os.symlink(path1, path2)
  464. if path2.is_symlink() and path2.read_text(encoding="utf-8") == "file1":
  465. return True
  466. try:
  467. os.link(path1, path2) # Ensure hard links can be created
  468. except Exception as ex:
  469. msg = (
  470. "File system does not seem to support either symlinks or hard links. "
  471. "Strict editable installs require one of them to be supported."
  472. )
  473. raise LinksNotSupported(msg) from ex
  474. return False
  475. def _simple_layout(
  476. packages: Iterable[str], package_dir: Dict[str, str], project_dir: Path
  477. ) -> bool:
  478. """Return ``True`` if:
  479. - all packages are contained by the same parent directory, **and**
  480. - all packages become importable if the parent directory is added to ``sys.path``.
  481. >>> _simple_layout(['a'], {"": "src"}, "/tmp/myproj")
  482. True
  483. >>> _simple_layout(['a', 'a.b'], {"": "src"}, "/tmp/myproj")
  484. True
  485. >>> _simple_layout(['a', 'a.b'], {}, "/tmp/myproj")
  486. True
  487. >>> _simple_layout(['a', 'a.a1', 'a.a1.a2', 'b'], {"": "src"}, "/tmp/myproj")
  488. True
  489. >>> _simple_layout(['a', 'a.a1', 'a.a1.a2', 'b'], {"a": "a", "b": "b"}, ".")
  490. True
  491. >>> _simple_layout(['a', 'a.a1', 'a.a1.a2', 'b'], {"a": "_a", "b": "_b"}, ".")
  492. False
  493. >>> _simple_layout(['a', 'a.a1', 'a.a1.a2', 'b'], {"a": "_a"}, "/tmp/myproj")
  494. False
  495. >>> _simple_layout(['a', 'a.a1', 'a.a1.a2', 'b'], {"a.a1.a2": "_a2"}, ".")
  496. False
  497. >>> _simple_layout(['a', 'a.b'], {"": "src", "a.b": "_ab"}, "/tmp/myproj")
  498. False
  499. >>> # Special cases, no packages yet:
  500. >>> _simple_layout([], {"": "src"}, "/tmp/myproj")
  501. True
  502. >>> _simple_layout([], {"a": "_a", "": "src"}, "/tmp/myproj")
  503. False
  504. """
  505. layout = {pkg: find_package_path(pkg, package_dir, project_dir) for pkg in packages}
  506. if not layout:
  507. return set(package_dir) in ({}, {""})
  508. parent = os.path.commonpath([_parent_path(k, v) for k, v in layout.items()])
  509. return all(
  510. _path.same_path(Path(parent, *key.split('.')), value)
  511. for key, value in layout.items()
  512. )
  513. def _parent_path(pkg, pkg_path):
  514. """Infer the parent path containing a package, that if added to ``sys.path`` would
  515. allow importing that package.
  516. When ``pkg`` is directly mapped into a directory with a different name, return its
  517. own path.
  518. >>> _parent_path("a", "src/a")
  519. 'src'
  520. >>> _parent_path("b", "src/c")
  521. 'src/c'
  522. """
  523. parent = pkg_path[: -len(pkg)] if pkg_path.endswith(pkg) else pkg_path
  524. return parent.rstrip("/" + os.sep)
  525. def _find_packages(dist: Distribution) -> Iterator[str]:
  526. yield from iter(dist.packages or [])
  527. py_modules = dist.py_modules or []
  528. nested_modules = [mod for mod in py_modules if "." in mod]
  529. if dist.ext_package:
  530. yield dist.ext_package
  531. else:
  532. ext_modules = dist.ext_modules or []
  533. nested_modules += [x.name for x in ext_modules if "." in x.name]
  534. for module in nested_modules:
  535. package, _, _ = module.rpartition(".")
  536. yield package
  537. def _find_top_level_modules(dist: Distribution) -> Iterator[str]:
  538. py_modules = dist.py_modules or []
  539. yield from (mod for mod in py_modules if "." not in mod)
  540. if not dist.ext_package:
  541. ext_modules = dist.ext_modules or []
  542. yield from (x.name for x in ext_modules if "." not in x.name)
  543. def _find_package_roots(
  544. packages: Iterable[str],
  545. package_dir: Mapping[str, str],
  546. src_root: _Path,
  547. ) -> Dict[str, str]:
  548. pkg_roots: Dict[str, str] = {
  549. pkg: _absolute_root(find_package_path(pkg, package_dir, src_root))
  550. for pkg in sorted(packages)
  551. }
  552. return _remove_nested(pkg_roots)
  553. def _absolute_root(path: _Path) -> str:
  554. """Works for packages and top-level modules"""
  555. path_ = Path(path)
  556. parent = path_.parent
  557. if path_.exists():
  558. return str(path_.resolve())
  559. else:
  560. return str(parent.resolve() / path_.name)
  561. def _find_virtual_namespaces(pkg_roots: Dict[str, str]) -> Iterator[str]:
  562. """By carefully designing ``package_dir``, it is possible to implement the logical
  563. structure of PEP 420 in a package without the corresponding directories.
  564. Moreover a parent package can be purposefully/accidentally skipped in the discovery
  565. phase (e.g. ``find_packages(include=["mypkg.*"])``, when ``mypkg.foo`` is included
  566. by ``mypkg`` itself is not).
  567. We consider this case to also be a virtual namespace (ignoring the original
  568. directory) to emulate a non-editable installation.
  569. This function will try to find these kinds of namespaces.
  570. """
  571. for pkg in pkg_roots:
  572. if "." not in pkg:
  573. continue
  574. parts = pkg.split(".")
  575. for i in range(len(parts) - 1, 0, -1):
  576. partial_name = ".".join(parts[:i])
  577. path = Path(find_package_path(partial_name, pkg_roots, ""))
  578. if not path.exists() or partial_name not in pkg_roots:
  579. # partial_name not in pkg_roots ==> purposefully/accidentally skipped
  580. yield partial_name
  581. def _find_namespaces(
  582. packages: List[str], pkg_roots: Dict[str, str]
  583. ) -> Iterator[Tuple[str, List[str]]]:
  584. for pkg in packages:
  585. path = find_package_path(pkg, pkg_roots, "")
  586. if Path(path).exists() and not Path(path, "__init__.py").exists():
  587. yield (pkg, [path])
  588. def _remove_nested(pkg_roots: Dict[str, str]) -> Dict[str, str]:
  589. output = dict(pkg_roots.copy())
  590. for pkg, path in reversed(list(pkg_roots.items())):
  591. if any(
  592. pkg != other and _is_nested(pkg, path, other, other_path)
  593. for other, other_path in pkg_roots.items()
  594. ):
  595. output.pop(pkg)
  596. return output
  597. def _is_nested(pkg: str, pkg_path: str, parent: str, parent_path: str) -> bool:
  598. """
  599. Return ``True`` if ``pkg`` is nested inside ``parent`` both logically and in the
  600. file system.
  601. >>> _is_nested("a.b", "path/a/b", "a", "path/a")
  602. True
  603. >>> _is_nested("a.b", "path/a/b", "a", "otherpath/a")
  604. False
  605. >>> _is_nested("a.b", "path/a/b", "c", "path/c")
  606. False
  607. >>> _is_nested("a.a", "path/a/a", "a", "path/a")
  608. True
  609. >>> _is_nested("b.a", "path/b/a", "a", "path/a")
  610. False
  611. """
  612. norm_pkg_path = _path.normpath(pkg_path)
  613. rest = pkg.replace(parent, "", 1).strip(".").split(".")
  614. return pkg.startswith(parent) and norm_pkg_path == _path.normpath(
  615. Path(parent_path, *rest)
  616. )
  617. def _empty_dir(dir_: _P) -> _P:
  618. """Create a directory ensured to be empty. Existing files may be removed."""
  619. shutil.rmtree(dir_, ignore_errors=True)
  620. os.makedirs(dir_)
  621. return dir_
  622. class _NamespaceInstaller(namespaces.Installer):
  623. def __init__(self, distribution, installation_dir, editable_name, src_root):
  624. self.distribution = distribution
  625. self.src_root = src_root
  626. self.installation_dir = installation_dir
  627. self.editable_name = editable_name
  628. self.outputs = []
  629. self.dry_run = False
  630. def _get_nspkg_file(self):
  631. """Installation target."""
  632. return os.path.join(self.installation_dir, self.editable_name + self.nspkg_ext)
  633. def _get_root(self):
  634. """Where the modules/packages should be loaded from."""
  635. return repr(str(self.src_root))
  636. _FINDER_TEMPLATE = """\
  637. import sys
  638. from importlib.machinery import ModuleSpec, PathFinder
  639. from importlib.machinery import all_suffixes as module_suffixes
  640. from importlib.util import spec_from_file_location
  641. from itertools import chain
  642. from pathlib import Path
  643. MAPPING = {mapping!r}
  644. NAMESPACES = {namespaces!r}
  645. PATH_PLACEHOLDER = {name!r} + ".__path_hook__"
  646. class _EditableFinder: # MetaPathFinder
  647. @classmethod
  648. def find_spec(cls, fullname, path=None, target=None):
  649. extra_path = []
  650. # Top-level packages and modules (we know these exist in the FS)
  651. if fullname in MAPPING:
  652. pkg_path = MAPPING[fullname]
  653. return cls._find_spec(fullname, Path(pkg_path))
  654. # Handle immediate children modules (required for namespaces to work)
  655. # To avoid problems with case sensitivity in the file system we delegate
  656. # to the importlib.machinery implementation.
  657. parent, _, child = fullname.rpartition(".")
  658. if parent and parent in MAPPING:
  659. return PathFinder.find_spec(fullname, path=[MAPPING[parent], *extra_path])
  660. # Other levels of nesting should be handled automatically by importlib
  661. # using the parent path.
  662. return None
  663. @classmethod
  664. def _find_spec(cls, fullname, candidate_path):
  665. init = candidate_path / "__init__.py"
  666. candidates = (candidate_path.with_suffix(x) for x in module_suffixes())
  667. for candidate in chain([init], candidates):
  668. if candidate.exists():
  669. return spec_from_file_location(fullname, candidate)
  670. class _EditableNamespaceFinder: # PathEntryFinder
  671. @classmethod
  672. def _path_hook(cls, path):
  673. if path == PATH_PLACEHOLDER:
  674. return cls
  675. raise ImportError
  676. @classmethod
  677. def _paths(cls, fullname):
  678. # Ensure __path__ is not empty for the spec to be considered a namespace.
  679. return NAMESPACES[fullname] or MAPPING.get(fullname) or [PATH_PLACEHOLDER]
  680. @classmethod
  681. def find_spec(cls, fullname, target=None):
  682. if fullname in NAMESPACES:
  683. spec = ModuleSpec(fullname, None, is_package=True)
  684. spec.submodule_search_locations = cls._paths(fullname)
  685. return spec
  686. return None
  687. @classmethod
  688. def find_module(cls, fullname):
  689. return None
  690. def install():
  691. if not any(finder == _EditableFinder for finder in sys.meta_path):
  692. sys.meta_path.append(_EditableFinder)
  693. if not NAMESPACES:
  694. return
  695. if not any(hook == _EditableNamespaceFinder._path_hook for hook in sys.path_hooks):
  696. # PathEntryFinder is needed to create NamespaceSpec without private APIS
  697. sys.path_hooks.append(_EditableNamespaceFinder._path_hook)
  698. if PATH_PLACEHOLDER not in sys.path:
  699. sys.path.append(PATH_PLACEHOLDER) # Used just to trigger the path hook
  700. """
  701. def _finder_template(
  702. name: str, mapping: Mapping[str, str], namespaces: Dict[str, List[str]]
  703. ) -> str:
  704. """Create a string containing the code for the``MetaPathFinder`` and
  705. ``PathEntryFinder``.
  706. """
  707. mapping = dict(sorted(mapping.items(), key=lambda p: p[0]))
  708. return _FINDER_TEMPLATE.format(name=name, mapping=mapping, namespaces=namespaces)
  709. class LinksNotSupported(errors.FileError):
  710. """File system does not seem to support either symlinks or hard links."""
  711. class _DebuggingTips(SetuptoolsWarning):
  712. _SUMMARY = "Problem in editable installation."
  713. _DETAILS = """
  714. An error happened while installing `{project}` in editable mode.
  715. The following steps are recommended to help debug this problem:
  716. - Try to install the project normally, without using the editable mode.
  717. Does the error still persist?
  718. (If it does, try fixing the problem before attempting the editable mode).
  719. - If you are using binary extensions, make sure you have all OS-level
  720. dependencies installed (e.g. compilers, toolchains, binary libraries, ...).
  721. - Try the latest version of setuptools (maybe the error was already fixed).
  722. - If you (or your project dependencies) are using any setuptools extension
  723. or customization, make sure they support the editable mode.
  724. After following the steps above, if the problem still persists and
  725. you think this is related to how setuptools handles editable installations,
  726. please submit a reproducible example
  727. (see https://stackoverflow.com/help/minimal-reproducible-example) to:
  728. https://github.com/pypa/setuptools/issues
  729. """
  730. _SEE_DOCS = "userguide/development_mode.html"