editable_wheel.py 30 KB

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