egg_info.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  1. """setuptools.command.egg_info
  2. Create a distribution's .egg-info directory and contents"""
  3. from __future__ import annotations
  4. import functools
  5. import os
  6. import re
  7. import sys
  8. import time
  9. from collections.abc import Callable
  10. import packaging
  11. import packaging.requirements
  12. import packaging.version
  13. import setuptools.unicode_utils as unicode_utils
  14. from setuptools import Command
  15. from setuptools.command import bdist_egg
  16. from setuptools.command.sdist import sdist, walk_revctrl
  17. from setuptools.command.setopt import edit_config
  18. from setuptools.glob import glob
  19. from .. import _entry_points, _normalization
  20. from .._importlib import metadata
  21. from ..warnings import SetuptoolsDeprecationWarning
  22. from . import _requirestxt
  23. import distutils.errors
  24. import distutils.filelist
  25. from distutils import log
  26. from distutils.errors import DistutilsInternalError
  27. from distutils.filelist import FileList as _FileList
  28. from distutils.util import convert_path
  29. PY_MAJOR = f'{sys.version_info.major}.{sys.version_info.minor}'
  30. def translate_pattern(glob): # noqa: C901 # is too complex (14) # FIXME
  31. """
  32. Translate a file path glob like '*.txt' in to a regular expression.
  33. This differs from fnmatch.translate which allows wildcards to match
  34. directory separators. It also knows about '**/' which matches any number of
  35. directories.
  36. """
  37. pat = ''
  38. # This will split on '/' within [character classes]. This is deliberate.
  39. chunks = glob.split(os.path.sep)
  40. sep = re.escape(os.sep)
  41. valid_char = f'[^{sep}]'
  42. for c, chunk in enumerate(chunks):
  43. last_chunk = c == len(chunks) - 1
  44. # Chunks that are a literal ** are globstars. They match anything.
  45. if chunk == '**':
  46. if last_chunk:
  47. # Match anything if this is the last component
  48. pat += '.*'
  49. else:
  50. # Match '(name/)*'
  51. pat += f'(?:{valid_char}+{sep})*'
  52. continue # Break here as the whole path component has been handled
  53. # Find any special characters in the remainder
  54. i = 0
  55. chunk_len = len(chunk)
  56. while i < chunk_len:
  57. char = chunk[i]
  58. if char == '*':
  59. # Match any number of name characters
  60. pat += valid_char + '*'
  61. elif char == '?':
  62. # Match a name character
  63. pat += valid_char
  64. elif char == '[':
  65. # Character class
  66. inner_i = i + 1
  67. # Skip initial !/] chars
  68. if inner_i < chunk_len and chunk[inner_i] == '!':
  69. inner_i = inner_i + 1
  70. if inner_i < chunk_len and chunk[inner_i] == ']':
  71. inner_i = inner_i + 1
  72. # Loop till the closing ] is found
  73. while inner_i < chunk_len and chunk[inner_i] != ']':
  74. inner_i = inner_i + 1
  75. if inner_i >= chunk_len:
  76. # Got to the end of the string without finding a closing ]
  77. # Do not treat this as a matching group, but as a literal [
  78. pat += re.escape(char)
  79. else:
  80. # Grab the insides of the [brackets]
  81. inner = chunk[i + 1 : inner_i]
  82. char_class = ''
  83. # Class negation
  84. if inner[0] == '!':
  85. char_class = '^'
  86. inner = inner[1:]
  87. char_class += re.escape(inner)
  88. pat += f'[{char_class}]'
  89. # Skip to the end ]
  90. i = inner_i
  91. else:
  92. pat += re.escape(char)
  93. i += 1
  94. # Join each chunk with the dir separator
  95. if not last_chunk:
  96. pat += sep
  97. pat += r'\Z'
  98. return re.compile(pat, flags=re.MULTILINE | re.DOTALL)
  99. class InfoCommon:
  100. tag_build = None
  101. tag_date = None
  102. @property
  103. def name(self):
  104. return _normalization.safe_name(self.distribution.get_name())
  105. def tagged_version(self):
  106. tagged = self._maybe_tag(self.distribution.get_version())
  107. return _normalization.safe_version(tagged)
  108. def _maybe_tag(self, version):
  109. """
  110. egg_info may be called more than once for a distribution,
  111. in which case the version string already contains all tags.
  112. """
  113. return (
  114. version
  115. if self.vtags and self._already_tagged(version)
  116. else version + self.vtags
  117. )
  118. def _already_tagged(self, version: str) -> bool:
  119. # Depending on their format, tags may change with version normalization.
  120. # So in addition the regular tags, we have to search for the normalized ones.
  121. return version.endswith((self.vtags, self._safe_tags()))
  122. def _safe_tags(self) -> str:
  123. # To implement this we can rely on `safe_version` pretending to be version 0
  124. # followed by tags. Then we simply discard the starting 0 (fake version number)
  125. try:
  126. return _normalization.safe_version(f"0{self.vtags}")[1:]
  127. except packaging.version.InvalidVersion:
  128. return _normalization.safe_name(self.vtags.replace(' ', '.'))
  129. def tags(self) -> str:
  130. version = ''
  131. if self.tag_build:
  132. version += self.tag_build
  133. if self.tag_date:
  134. version += time.strftime("%Y%m%d")
  135. return version
  136. vtags = property(tags)
  137. class egg_info(InfoCommon, Command):
  138. description = "create a distribution's .egg-info directory"
  139. user_options = [
  140. (
  141. 'egg-base=',
  142. 'e',
  143. "directory containing .egg-info directories"
  144. " [default: top of the source tree]",
  145. ),
  146. ('tag-date', 'd', "Add date stamp (e.g. 20050528) to version number"),
  147. ('tag-build=', 'b', "Specify explicit tag to add to version number"),
  148. ('no-date', 'D', "Don't include date stamp [default]"),
  149. ]
  150. boolean_options = ['tag-date']
  151. negative_opt = {
  152. 'no-date': 'tag-date',
  153. }
  154. def initialize_options(self):
  155. self.egg_base = None
  156. self.egg_name = None
  157. self.egg_info = None
  158. self.egg_version = None
  159. self.ignore_egg_info_in_manifest = False
  160. ####################################
  161. # allow the 'tag_svn_revision' to be detected and
  162. # set, supporting sdists built on older Setuptools.
  163. @property
  164. def tag_svn_revision(self) -> int | None:
  165. pass
  166. @tag_svn_revision.setter
  167. def tag_svn_revision(self, value) -> None:
  168. pass
  169. ####################################
  170. def save_version_info(self, filename) -> None:
  171. """
  172. Materialize the value of date into the
  173. build tag. Install build keys in a deterministic order
  174. to avoid arbitrary reordering on subsequent builds.
  175. """
  176. # follow the order these keys would have been added
  177. # when PYTHONHASHSEED=0
  178. egg_info = dict(tag_build=self.tags(), tag_date=0)
  179. edit_config(filename, dict(egg_info=egg_info))
  180. def finalize_options(self) -> None:
  181. # Note: we need to capture the current value returned
  182. # by `self.tagged_version()`, so we can later update
  183. # `self.distribution.metadata.version` without
  184. # repercussions.
  185. self.egg_name = self.name
  186. self.egg_version = self.tagged_version()
  187. parsed_version = packaging.version.Version(self.egg_version)
  188. try:
  189. is_version = isinstance(parsed_version, packaging.version.Version)
  190. spec = "%s==%s" if is_version else "%s===%s"
  191. packaging.requirements.Requirement(spec % (self.egg_name, self.egg_version))
  192. except ValueError as e:
  193. raise distutils.errors.DistutilsOptionError(
  194. f"Invalid distribution name or version syntax: {self.egg_name}-{self.egg_version}"
  195. ) from e
  196. if self.egg_base is None:
  197. dirs = self.distribution.package_dir
  198. self.egg_base = (dirs or {}).get('', os.curdir)
  199. self.ensure_dirname('egg_base')
  200. self.egg_info = _normalization.filename_component(self.egg_name) + '.egg-info'
  201. if self.egg_base != os.curdir:
  202. self.egg_info = os.path.join(self.egg_base, self.egg_info)
  203. # Set package version for the benefit of dumber commands
  204. # (e.g. sdist, bdist_wininst, etc.)
  205. #
  206. self.distribution.metadata.version = self.egg_version
  207. def _get_egg_basename(self, py_version=PY_MAJOR, platform=None):
  208. """Compute filename of the output egg. Private API."""
  209. return _egg_basename(self.egg_name, self.egg_version, py_version, platform)
  210. def write_or_delete_file(self, what, filename, data, force: bool = False) -> None:
  211. """Write `data` to `filename` or delete if empty
  212. If `data` is non-empty, this routine is the same as ``write_file()``.
  213. If `data` is empty but not ``None``, this is the same as calling
  214. ``delete_file(filename)`. If `data` is ``None``, then this is a no-op
  215. unless `filename` exists, in which case a warning is issued about the
  216. orphaned file (if `force` is false), or deleted (if `force` is true).
  217. """
  218. if data:
  219. self.write_file(what, filename, data)
  220. elif os.path.exists(filename):
  221. if data is None and not force:
  222. log.warn("%s not set in setup(), but %s exists", what, filename)
  223. return
  224. else:
  225. self.delete_file(filename)
  226. def write_file(self, what, filename, data) -> None:
  227. """Write `data` to `filename` (if not a dry run) after announcing it
  228. `what` is used in a log message to identify what is being written
  229. to the file.
  230. """
  231. log.info("writing %s to %s", what, filename)
  232. data = data.encode("utf-8")
  233. f = open(filename, 'wb')
  234. f.write(data)
  235. f.close()
  236. def delete_file(self, filename) -> None:
  237. """Delete `filename` (if not a dry run) after announcing it"""
  238. log.info("deleting %s", filename)
  239. os.unlink(filename)
  240. def run(self) -> None:
  241. # Pre-load to avoid iterating over entry-points while an empty .egg-info
  242. # exists in sys.path. See pypa/pyproject-hooks#206
  243. writers = list(metadata.entry_points(group='egg_info.writers'))
  244. self.mkpath(self.egg_info)
  245. try:
  246. os.utime(self.egg_info, None)
  247. except OSError as e:
  248. msg = f"Cannot update time stamp of directory '{self.egg_info}'"
  249. raise distutils.errors.DistutilsFileError(msg) from e
  250. for ep in writers:
  251. writer = ep.load()
  252. writer(self, ep.name, os.path.join(self.egg_info, ep.name))
  253. # Get rid of native_libs.txt if it was put there by older bdist_egg
  254. nl = os.path.join(self.egg_info, "native_libs.txt")
  255. if os.path.exists(nl):
  256. self.delete_file(nl)
  257. self.find_sources()
  258. def find_sources(self) -> None:
  259. """Generate SOURCES.txt manifest file"""
  260. manifest_filename = os.path.join(self.egg_info, "SOURCES.txt")
  261. mm = manifest_maker(self.distribution)
  262. mm.ignore_egg_info_dir = self.ignore_egg_info_in_manifest
  263. mm.manifest = manifest_filename
  264. mm.run()
  265. self.filelist = mm.filelist
  266. class FileList(_FileList):
  267. # Implementations of the various MANIFEST.in commands
  268. def __init__(
  269. self, warn=None, debug_print=None, ignore_egg_info_dir: bool = False
  270. ) -> None:
  271. super().__init__(warn, debug_print)
  272. self.ignore_egg_info_dir = ignore_egg_info_dir
  273. def process_template_line(self, line) -> None:
  274. # Parse the line: split it up, make sure the right number of words
  275. # is there, and return the relevant words. 'action' is always
  276. # defined: it's the first word of the line. Which of the other
  277. # three are defined depends on the action; it'll be either
  278. # patterns, (dir and patterns), or (dir_pattern).
  279. (action, patterns, dir, dir_pattern) = self._parse_template_line(line)
  280. action_map: dict[str, Callable] = {
  281. 'include': self.include,
  282. 'exclude': self.exclude,
  283. 'global-include': self.global_include,
  284. 'global-exclude': self.global_exclude,
  285. 'recursive-include': functools.partial(
  286. self.recursive_include,
  287. dir,
  288. ),
  289. 'recursive-exclude': functools.partial(
  290. self.recursive_exclude,
  291. dir,
  292. ),
  293. 'graft': self.graft,
  294. 'prune': self.prune,
  295. }
  296. log_map = {
  297. 'include': "warning: no files found matching '%s'",
  298. 'exclude': ("warning: no previously-included files found matching '%s'"),
  299. 'global-include': (
  300. "warning: no files found matching '%s' anywhere in distribution"
  301. ),
  302. 'global-exclude': (
  303. "warning: no previously-included files matching "
  304. "'%s' found anywhere in distribution"
  305. ),
  306. 'recursive-include': (
  307. "warning: no files found matching '%s' under directory '%s'"
  308. ),
  309. 'recursive-exclude': (
  310. "warning: no previously-included files matching "
  311. "'%s' found under directory '%s'"
  312. ),
  313. 'graft': "warning: no directories found matching '%s'",
  314. 'prune': "no previously-included directories found matching '%s'",
  315. }
  316. try:
  317. process_action = action_map[action]
  318. except KeyError:
  319. msg = f"Invalid MANIFEST.in: unknown action {action!r} in {line!r}"
  320. raise DistutilsInternalError(msg) from None
  321. # OK, now we know that the action is valid and we have the
  322. # right number of words on the line for that action -- so we
  323. # can proceed with minimal error-checking.
  324. action_is_recursive = action.startswith('recursive-')
  325. if action in {'graft', 'prune'}:
  326. patterns = [dir_pattern]
  327. extra_log_args = (dir,) if action_is_recursive else ()
  328. log_tmpl = log_map[action]
  329. self.debug_print(
  330. ' '.join(
  331. [action] + ([dir] if action_is_recursive else []) + patterns,
  332. )
  333. )
  334. for pattern in patterns:
  335. if not process_action(pattern):
  336. log.warn(log_tmpl, pattern, *extra_log_args)
  337. def _remove_files(self, predicate):
  338. """
  339. Remove all files from the file list that match the predicate.
  340. Return True if any matching files were removed
  341. """
  342. found = False
  343. for i in range(len(self.files) - 1, -1, -1):
  344. if predicate(self.files[i]):
  345. self.debug_print(" removing " + self.files[i])
  346. del self.files[i]
  347. found = True
  348. return found
  349. def include(self, pattern):
  350. """Include files that match 'pattern'."""
  351. found = [f for f in glob(pattern) if not os.path.isdir(f)]
  352. self.extend(found)
  353. return bool(found)
  354. def exclude(self, pattern):
  355. """Exclude files that match 'pattern'."""
  356. match = translate_pattern(pattern)
  357. return self._remove_files(match.match)
  358. def recursive_include(self, dir, pattern):
  359. """
  360. Include all files anywhere in 'dir/' that match the pattern.
  361. """
  362. full_pattern = os.path.join(dir, '**', pattern)
  363. found = [f for f in glob(full_pattern, recursive=True) if not os.path.isdir(f)]
  364. self.extend(found)
  365. return bool(found)
  366. def recursive_exclude(self, dir, pattern):
  367. """
  368. Exclude any file anywhere in 'dir/' that match the pattern.
  369. """
  370. match = translate_pattern(os.path.join(dir, '**', pattern))
  371. return self._remove_files(match.match)
  372. def graft(self, dir):
  373. """Include all files from 'dir/'."""
  374. found = [
  375. item
  376. for match_dir in glob(dir)
  377. for item in distutils.filelist.findall(match_dir)
  378. ]
  379. self.extend(found)
  380. return bool(found)
  381. def prune(self, dir):
  382. """Filter out files from 'dir/'."""
  383. match = translate_pattern(os.path.join(dir, '**'))
  384. return self._remove_files(match.match)
  385. def global_include(self, pattern):
  386. """
  387. Include all files anywhere in the current directory that match the
  388. pattern. This is very inefficient on large file trees.
  389. """
  390. if self.allfiles is None:
  391. self.findall()
  392. match = translate_pattern(os.path.join('**', pattern))
  393. found = [f for f in self.allfiles if match.match(f)]
  394. self.extend(found)
  395. return bool(found)
  396. def global_exclude(self, pattern):
  397. """
  398. Exclude all files anywhere that match the pattern.
  399. """
  400. match = translate_pattern(os.path.join('**', pattern))
  401. return self._remove_files(match.match)
  402. def append(self, item) -> None:
  403. item = item.removesuffix('\r') # Fix older sdists built on Windows
  404. path = convert_path(item)
  405. if self._safe_path(path):
  406. self.files.append(path)
  407. def extend(self, paths) -> None:
  408. self.files.extend(filter(self._safe_path, paths))
  409. def _repair(self):
  410. """
  411. Replace self.files with only safe paths
  412. Because some owners of FileList manipulate the underlying
  413. ``files`` attribute directly, this method must be called to
  414. repair those paths.
  415. """
  416. self.files = list(filter(self._safe_path, self.files))
  417. def _safe_path(self, path):
  418. enc_warn = "'%s' not %s encodable -- skipping"
  419. # To avoid accidental trans-codings errors, first to unicode
  420. u_path = unicode_utils.filesys_decode(path)
  421. if u_path is None:
  422. log.warn(f"'{path}' in unexpected encoding -- skipping")
  423. return False
  424. # Must ensure utf-8 encodability
  425. utf8_path = unicode_utils.try_encode(u_path, "utf-8")
  426. if utf8_path is None:
  427. log.warn(enc_warn, path, 'utf-8')
  428. return False
  429. try:
  430. # ignore egg-info paths
  431. is_egg_info = ".egg-info" in u_path or b".egg-info" in utf8_path
  432. if self.ignore_egg_info_dir and is_egg_info:
  433. return False
  434. # accept is either way checks out
  435. if os.path.exists(u_path) or os.path.exists(utf8_path):
  436. return True
  437. # this will catch any encode errors decoding u_path
  438. except UnicodeEncodeError:
  439. log.warn(enc_warn, path, sys.getfilesystemencoding())
  440. class manifest_maker(sdist):
  441. template = "MANIFEST.in"
  442. def initialize_options(self) -> None:
  443. self.use_defaults = True
  444. self.prune = True
  445. self.manifest_only = True
  446. self.force_manifest = True
  447. self.ignore_egg_info_dir = False
  448. def finalize_options(self) -> None:
  449. pass
  450. def run(self) -> None:
  451. self.filelist = FileList(ignore_egg_info_dir=self.ignore_egg_info_dir)
  452. if not os.path.exists(self.manifest):
  453. self.write_manifest() # it must exist so it'll get in the list
  454. self.add_defaults()
  455. if os.path.exists(self.template):
  456. self.read_template()
  457. self.add_license_files()
  458. self._add_referenced_files()
  459. self.prune_file_list()
  460. self.filelist.sort()
  461. self.filelist.remove_duplicates()
  462. self.write_manifest()
  463. def _manifest_normalize(self, path):
  464. path = unicode_utils.filesys_decode(path)
  465. return path.replace(os.sep, '/')
  466. def write_manifest(self) -> None:
  467. """
  468. Write the file list in 'self.filelist' to the manifest file
  469. named by 'self.manifest'.
  470. """
  471. self.filelist._repair()
  472. # Now _repairs should encodability, but not unicode
  473. files = [self._manifest_normalize(f) for f in self.filelist.files]
  474. msg = f"writing manifest file '{self.manifest}'"
  475. self.execute(write_file, (self.manifest, files), msg)
  476. def warn(self, msg) -> None:
  477. if not self._should_suppress_warning(msg):
  478. sdist.warn(self, msg)
  479. @staticmethod
  480. def _should_suppress_warning(msg):
  481. """
  482. suppress missing-file warnings from sdist
  483. """
  484. return re.match(r"standard file .*not found", msg)
  485. def add_defaults(self) -> None:
  486. sdist.add_defaults(self)
  487. self.filelist.append(self.template)
  488. self.filelist.append(self.manifest)
  489. rcfiles = list(walk_revctrl())
  490. if rcfiles:
  491. self.filelist.extend(rcfiles)
  492. elif os.path.exists(self.manifest):
  493. self.read_manifest()
  494. if os.path.exists("setup.py"):
  495. # setup.py should be included by default, even if it's not
  496. # the script called to create the sdist
  497. self.filelist.append("setup.py")
  498. ei_cmd = self.get_finalized_command('egg_info')
  499. self.filelist.graft(ei_cmd.egg_info)
  500. def add_license_files(self) -> None:
  501. license_files = self.distribution.metadata.license_files or []
  502. for lf in license_files:
  503. log.info("adding license file '%s'", lf)
  504. self.filelist.extend(license_files)
  505. def _add_referenced_files(self):
  506. """Add files referenced by the config (e.g. `file:` directive) to filelist"""
  507. referenced = getattr(self.distribution, '_referenced_files', [])
  508. # ^-- fallback if dist comes from distutils or is a custom class
  509. for rf in referenced:
  510. log.debug("adding file referenced by config '%s'", rf)
  511. self.filelist.extend(referenced)
  512. def _safe_data_files(self, build_py):
  513. """
  514. The parent class implementation of this method
  515. (``sdist``) will try to include data files, which
  516. might cause recursion problems when
  517. ``include_package_data=True``.
  518. Therefore, avoid triggering any attempt of
  519. analyzing/building the manifest again.
  520. """
  521. if hasattr(build_py, 'get_data_files_without_manifest'):
  522. return build_py.get_data_files_without_manifest()
  523. SetuptoolsDeprecationWarning.emit(
  524. "`build_py` command does not inherit from setuptools' `build_py`.",
  525. """
  526. Custom 'build_py' does not implement 'get_data_files_without_manifest'.
  527. Please extend command classes from setuptools instead of distutils.
  528. """,
  529. see_url="https://peps.python.org/pep-0632/",
  530. # due_date not defined yet, old projects might still do it?
  531. )
  532. return build_py.get_data_files()
  533. def write_file(filename, contents) -> None:
  534. """Create a file with the specified name and write 'contents' (a
  535. sequence of strings without line terminators) to it.
  536. """
  537. contents = "\n".join(contents)
  538. # assuming the contents has been vetted for utf-8 encoding
  539. contents = contents.encode("utf-8")
  540. with open(filename, "wb") as f: # always write POSIX-style manifest
  541. f.write(contents)
  542. def write_pkg_info(cmd, basename, filename) -> None:
  543. log.info("writing %s", filename)
  544. metadata = cmd.distribution.metadata
  545. metadata.version, oldver = cmd.egg_version, metadata.version
  546. metadata.name, oldname = cmd.egg_name, metadata.name
  547. try:
  548. metadata.write_pkg_info(cmd.egg_info)
  549. finally:
  550. metadata.name, metadata.version = oldname, oldver
  551. safe = getattr(cmd.distribution, 'zip_safe', None)
  552. bdist_egg.write_safety_flag(cmd.egg_info, safe)
  553. def warn_depends_obsolete(cmd, basename, filename) -> None:
  554. """
  555. Unused: left to avoid errors when updating (from source) from <= 67.8.
  556. Old installations have a .dist-info directory with the entry-point
  557. ``depends.txt = setuptools.command.egg_info:warn_depends_obsolete``.
  558. This may trigger errors when running the first egg_info in build_meta.
  559. TODO: Remove this function in a version sufficiently > 68.
  560. """
  561. # Export API used in entry_points
  562. write_requirements = _requirestxt.write_requirements
  563. write_setup_requirements = _requirestxt.write_setup_requirements
  564. def write_toplevel_names(cmd, basename, filename) -> None:
  565. pkgs = dict.fromkeys([
  566. k.split('.', 1)[0] for k in cmd.distribution.iter_distribution_names()
  567. ])
  568. cmd.write_file("top-level names", filename, '\n'.join(sorted(pkgs)) + '\n')
  569. def overwrite_arg(cmd, basename, filename) -> None:
  570. write_arg(cmd, basename, filename, True)
  571. def write_arg(cmd, basename, filename, force: bool = False) -> None:
  572. argname = os.path.splitext(basename)[0]
  573. value = getattr(cmd.distribution, argname, None)
  574. if value is not None:
  575. value = '\n'.join(value) + '\n'
  576. cmd.write_or_delete_file(argname, filename, value, force)
  577. def write_entries(cmd, basename, filename) -> None:
  578. eps = _entry_points.load(cmd.distribution.entry_points)
  579. defn = _entry_points.render(eps)
  580. cmd.write_or_delete_file('entry points', filename, defn, True)
  581. def _egg_basename(egg_name, egg_version, py_version=None, platform=None):
  582. """Compute filename of the output egg. Private API."""
  583. name = _normalization.filename_component(egg_name)
  584. version = _normalization.filename_component(egg_version)
  585. egg = f"{name}-{version}-py{py_version or PY_MAJOR}"
  586. if platform:
  587. egg += f"-{platform}"
  588. return egg
  589. class EggInfoDeprecationWarning(SetuptoolsDeprecationWarning):
  590. """Deprecated behavior warning for EggInfo, bypassing suppression."""