egg_info.py 26 KB

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