egg_info.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  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 os
  10. import re
  11. import sys
  12. import io
  13. import warnings
  14. import time
  15. import collections
  16. from setuptools import Command
  17. from setuptools.command.sdist import sdist
  18. from setuptools.command.sdist import walk_revctrl
  19. from setuptools.command.setopt import edit_config
  20. from setuptools.command import bdist_egg
  21. from pkg_resources import (
  22. parse_requirements, safe_name, parse_version,
  23. safe_version, yield_lines, EntryPoint, iter_entry_points, to_filename)
  24. import setuptools.unicode_utils as unicode_utils
  25. from setuptools.glob import glob
  26. from setuptools.extern import packaging
  27. from setuptools import SetuptoolsDeprecationWarning
  28. def translate_pattern(glob):
  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 safe_name(self.distribution.get_name())
  103. def tagged_version(self):
  104. return safe_version(self._maybe_tag(self.distribution.get_version()))
  105. def _maybe_tag(self, version):
  106. """
  107. egg_info may be called more than once for a distribution,
  108. in which case the version string already contains all tags.
  109. """
  110. return (
  111. version if self.vtags and version.endswith(self.vtags)
  112. else version + self.vtags
  113. )
  114. def tags(self):
  115. version = ''
  116. if self.tag_build:
  117. version += self.tag_build
  118. if self.tag_date:
  119. version += time.strftime("-%Y%m%d")
  120. return version
  121. vtags = property(tags)
  122. class egg_info(InfoCommon, Command):
  123. description = "create a distribution's .egg-info directory"
  124. user_options = [
  125. ('egg-base=', 'e', "directory containing .egg-info directories"
  126. " (default: top of the source tree)"),
  127. ('tag-date', 'd', "Add date stamp (e.g. 20050528) to version number"),
  128. ('tag-build=', 'b', "Specify explicit tag to add to version number"),
  129. ('no-date', 'D', "Don't include date stamp [default]"),
  130. ]
  131. boolean_options = ['tag-date']
  132. negative_opt = {
  133. 'no-date': 'tag-date',
  134. }
  135. def initialize_options(self):
  136. self.egg_base = None
  137. self.egg_name = None
  138. self.egg_info = None
  139. self.egg_version = None
  140. self.broken_egg_info = False
  141. ####################################
  142. # allow the 'tag_svn_revision' to be detected and
  143. # set, supporting sdists built on older Setuptools.
  144. @property
  145. def tag_svn_revision(self):
  146. pass
  147. @tag_svn_revision.setter
  148. def tag_svn_revision(self, value):
  149. pass
  150. ####################################
  151. def save_version_info(self, filename):
  152. """
  153. Materialize the value of date into the
  154. build tag. Install build keys in a deterministic order
  155. to avoid arbitrary reordering on subsequent builds.
  156. """
  157. egg_info = collections.OrderedDict()
  158. # follow the order these keys would have been added
  159. # when PYTHONHASHSEED=0
  160. egg_info['tag_build'] = self.tags()
  161. egg_info['tag_date'] = 0
  162. edit_config(filename, dict(egg_info=egg_info))
  163. def finalize_options(self):
  164. # Note: we need to capture the current value returned
  165. # by `self.tagged_version()`, so we can later update
  166. # `self.distribution.metadata.version` without
  167. # repercussions.
  168. self.egg_name = self.name
  169. self.egg_version = self.tagged_version()
  170. parsed_version = parse_version(self.egg_version)
  171. try:
  172. is_version = isinstance(parsed_version, packaging.version.Version)
  173. spec = (
  174. "%s==%s" if is_version else "%s===%s"
  175. )
  176. list(
  177. parse_requirements(spec % (self.egg_name, self.egg_version))
  178. )
  179. except ValueError as e:
  180. raise distutils.errors.DistutilsOptionError(
  181. "Invalid distribution name or version syntax: %s-%s" %
  182. (self.egg_name, self.egg_version)
  183. ) from e
  184. if self.egg_base is None:
  185. dirs = self.distribution.package_dir
  186. self.egg_base = (dirs or {}).get('', os.curdir)
  187. self.ensure_dirname('egg_base')
  188. self.egg_info = to_filename(self.egg_name) + '.egg-info'
  189. if self.egg_base != os.curdir:
  190. self.egg_info = os.path.join(self.egg_base, self.egg_info)
  191. if '-' in self.egg_name:
  192. self.check_broken_egg_info()
  193. # Set package version for the benefit of dumber commands
  194. # (e.g. sdist, bdist_wininst, etc.)
  195. #
  196. self.distribution.metadata.version = self.egg_version
  197. # If we bootstrapped around the lack of a PKG-INFO, as might be the
  198. # case in a fresh checkout, make sure that any special tags get added
  199. # to the version info
  200. #
  201. pd = self.distribution._patched_dist
  202. if pd is not None and pd.key == self.egg_name.lower():
  203. pd._version = self.egg_version
  204. pd._parsed_version = parse_version(self.egg_version)
  205. self.distribution._patched_dist = None
  206. def write_or_delete_file(self, what, filename, data, force=False):
  207. """Write `data` to `filename` or delete if empty
  208. If `data` is non-empty, this routine is the same as ``write_file()``.
  209. If `data` is empty but not ``None``, this is the same as calling
  210. ``delete_file(filename)`. If `data` is ``None``, then this is a no-op
  211. unless `filename` exists, in which case a warning is issued about the
  212. orphaned file (if `force` is false), or deleted (if `force` is true).
  213. """
  214. if data:
  215. self.write_file(what, filename, data)
  216. elif os.path.exists(filename):
  217. if data is None and not force:
  218. log.warn(
  219. "%s not set in setup(), but %s exists", what, filename
  220. )
  221. return
  222. else:
  223. self.delete_file(filename)
  224. def write_file(self, what, filename, data):
  225. """Write `data` to `filename` (if not a dry run) after announcing it
  226. `what` is used in a log message to identify what is being written
  227. to the file.
  228. """
  229. log.info("writing %s to %s", what, filename)
  230. data = data.encode("utf-8")
  231. if not self.dry_run:
  232. f = open(filename, 'wb')
  233. f.write(data)
  234. f.close()
  235. def delete_file(self, filename):
  236. """Delete `filename` (if not a dry run) after announcing it"""
  237. log.info("deleting %s", filename)
  238. if not self.dry_run:
  239. os.unlink(filename)
  240. def run(self):
  241. self.mkpath(self.egg_info)
  242. os.utime(self.egg_info, None)
  243. installer = self.distribution.fetch_build_egg
  244. for ep in iter_entry_points('egg_info.writers'):
  245. ep.require(installer=installer)
  246. writer = ep.resolve()
  247. writer(self, ep.name, os.path.join(self.egg_info, ep.name))
  248. # Get rid of native_libs.txt if it was put there by older bdist_egg
  249. nl = os.path.join(self.egg_info, "native_libs.txt")
  250. if os.path.exists(nl):
  251. self.delete_file(nl)
  252. self.find_sources()
  253. def find_sources(self):
  254. """Generate SOURCES.txt manifest file"""
  255. manifest_filename = os.path.join(self.egg_info, "SOURCES.txt")
  256. mm = manifest_maker(self.distribution)
  257. mm.manifest = manifest_filename
  258. mm.run()
  259. self.filelist = mm.filelist
  260. def check_broken_egg_info(self):
  261. bei = self.egg_name + '.egg-info'
  262. if self.egg_base != os.curdir:
  263. bei = os.path.join(self.egg_base, bei)
  264. if os.path.exists(bei):
  265. log.warn(
  266. "-" * 78 + '\n'
  267. "Note: Your current .egg-info directory has a '-' in its name;"
  268. '\nthis will not work correctly with "setup.py develop".\n\n'
  269. 'Please rename %s to %s to correct this problem.\n' + '-' * 78,
  270. bei, self.egg_info
  271. )
  272. self.broken_egg_info = self.egg_info
  273. self.egg_info = bei # make it work for now
  274. class FileList(_FileList):
  275. # Implementations of the various MANIFEST.in commands
  276. def process_template_line(self, line):
  277. # Parse the line: split it up, make sure the right number of words
  278. # is there, and return the relevant words. 'action' is always
  279. # defined: it's the first word of the line. Which of the other
  280. # three are defined depends on the action; it'll be either
  281. # patterns, (dir and patterns), or (dir_pattern).
  282. (action, patterns, dir, dir_pattern) = self._parse_template_line(line)
  283. # OK, now we know that the action is valid and we have the
  284. # right number of words on the line for that action -- so we
  285. # can proceed with minimal error-checking.
  286. if action == 'include':
  287. self.debug_print("include " + ' '.join(patterns))
  288. for pattern in patterns:
  289. if not self.include(pattern):
  290. log.warn("warning: no files found matching '%s'", pattern)
  291. elif action == 'exclude':
  292. self.debug_print("exclude " + ' '.join(patterns))
  293. for pattern in patterns:
  294. if not self.exclude(pattern):
  295. log.warn(("warning: no previously-included files "
  296. "found matching '%s'"), pattern)
  297. elif action == 'global-include':
  298. self.debug_print("global-include " + ' '.join(patterns))
  299. for pattern in patterns:
  300. if not self.global_include(pattern):
  301. log.warn(("warning: no files found matching '%s' "
  302. "anywhere in distribution"), pattern)
  303. elif action == 'global-exclude':
  304. self.debug_print("global-exclude " + ' '.join(patterns))
  305. for pattern in patterns:
  306. if not self.global_exclude(pattern):
  307. log.warn(("warning: no previously-included files matching "
  308. "'%s' found anywhere in distribution"),
  309. pattern)
  310. elif action == 'recursive-include':
  311. self.debug_print("recursive-include %s %s" %
  312. (dir, ' '.join(patterns)))
  313. for pattern in patterns:
  314. if not self.recursive_include(dir, pattern):
  315. log.warn(("warning: no files found matching '%s' "
  316. "under directory '%s'"),
  317. pattern, dir)
  318. elif action == 'recursive-exclude':
  319. self.debug_print("recursive-exclude %s %s" %
  320. (dir, ' '.join(patterns)))
  321. for pattern in patterns:
  322. if not self.recursive_exclude(dir, pattern):
  323. log.warn(("warning: no previously-included files matching "
  324. "'%s' found under directory '%s'"),
  325. pattern, dir)
  326. elif action == 'graft':
  327. self.debug_print("graft " + dir_pattern)
  328. if not self.graft(dir_pattern):
  329. log.warn("warning: no directories found matching '%s'",
  330. dir_pattern)
  331. elif action == 'prune':
  332. self.debug_print("prune " + dir_pattern)
  333. if not self.prune(dir_pattern):
  334. log.warn(("no previously-included directories found "
  335. "matching '%s'"), dir_pattern)
  336. else:
  337. raise DistutilsInternalError(
  338. "this cannot happen: invalid action '%s'" % action)
  339. def _remove_files(self, predicate):
  340. """
  341. Remove all files from the file list that match the predicate.
  342. Return True if any matching files were removed
  343. """
  344. found = False
  345. for i in range(len(self.files) - 1, -1, -1):
  346. if predicate(self.files[i]):
  347. self.debug_print(" removing " + self.files[i])
  348. del self.files[i]
  349. found = True
  350. return found
  351. def include(self, pattern):
  352. """Include files that match 'pattern'."""
  353. found = [f for f in glob(pattern) if not os.path.isdir(f)]
  354. self.extend(found)
  355. return bool(found)
  356. def exclude(self, pattern):
  357. """Exclude files that match 'pattern'."""
  358. match = translate_pattern(pattern)
  359. return self._remove_files(match.match)
  360. def recursive_include(self, dir, pattern):
  361. """
  362. Include all files anywhere in 'dir/' that match the pattern.
  363. """
  364. full_pattern = os.path.join(dir, '**', pattern)
  365. found = [f for f in glob(full_pattern, recursive=True)
  366. if not os.path.isdir(f)]
  367. self.extend(found)
  368. return bool(found)
  369. def recursive_exclude(self, dir, pattern):
  370. """
  371. Exclude any file anywhere in 'dir/' that match the pattern.
  372. """
  373. match = translate_pattern(os.path.join(dir, '**', pattern))
  374. return self._remove_files(match.match)
  375. def graft(self, dir):
  376. """Include all files from 'dir/'."""
  377. found = [
  378. item
  379. for match_dir in glob(dir)
  380. for item in distutils.filelist.findall(match_dir)
  381. ]
  382. self.extend(found)
  383. return bool(found)
  384. def prune(self, dir):
  385. """Filter out files from 'dir/'."""
  386. match = translate_pattern(os.path.join(dir, '**'))
  387. return self._remove_files(match.match)
  388. def global_include(self, pattern):
  389. """
  390. Include all files anywhere in the current directory that match the
  391. pattern. This is very inefficient on large file trees.
  392. """
  393. if self.allfiles is None:
  394. self.findall()
  395. match = translate_pattern(os.path.join('**', pattern))
  396. found = [f for f in self.allfiles if match.match(f)]
  397. self.extend(found)
  398. return bool(found)
  399. def global_exclude(self, pattern):
  400. """
  401. Exclude all files anywhere that match the pattern.
  402. """
  403. match = translate_pattern(os.path.join('**', pattern))
  404. return self._remove_files(match.match)
  405. def append(self, item):
  406. if item.endswith('\r'): # Fix older sdists built on Windows
  407. item = item[:-1]
  408. path = convert_path(item)
  409. if self._safe_path(path):
  410. self.files.append(path)
  411. def extend(self, paths):
  412. self.files.extend(filter(self._safe_path, paths))
  413. def _repair(self):
  414. """
  415. Replace self.files with only safe paths
  416. Because some owners of FileList manipulate the underlying
  417. ``files`` attribute directly, this method must be called to
  418. repair those paths.
  419. """
  420. self.files = list(filter(self._safe_path, self.files))
  421. def _safe_path(self, path):
  422. enc_warn = "'%s' not %s encodable -- skipping"
  423. # To avoid accidental trans-codings errors, first to unicode
  424. u_path = unicode_utils.filesys_decode(path)
  425. if u_path is None:
  426. log.warn("'%s' in unexpected encoding -- skipping" % path)
  427. return False
  428. # Must ensure utf-8 encodability
  429. utf8_path = unicode_utils.try_encode(u_path, "utf-8")
  430. if utf8_path is None:
  431. log.warn(enc_warn, path, 'utf-8')
  432. return False
  433. try:
  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):
  443. self.use_defaults = 1
  444. self.prune = 1
  445. self.manifest_only = 1
  446. self.force_manifest = 1
  447. def finalize_options(self):
  448. pass
  449. def run(self):
  450. self.filelist = FileList()
  451. if not os.path.exists(self.manifest):
  452. self.write_manifest() # it must exist so it'll get in the list
  453. self.add_defaults()
  454. if os.path.exists(self.template):
  455. self.read_template()
  456. self.prune_file_list()
  457. self.filelist.sort()
  458. self.filelist.remove_duplicates()
  459. self.write_manifest()
  460. def _manifest_normalize(self, path):
  461. path = unicode_utils.filesys_decode(path)
  462. return path.replace(os.sep, '/')
  463. def write_manifest(self):
  464. """
  465. Write the file list in 'self.filelist' to the manifest file
  466. named by 'self.manifest'.
  467. """
  468. self.filelist._repair()
  469. # Now _repairs should encodability, but not unicode
  470. files = [self._manifest_normalize(f) for f in self.filelist.files]
  471. msg = "writing manifest file '%s'" % self.manifest
  472. self.execute(write_file, (self.manifest, files), msg)
  473. def warn(self, msg):
  474. if not self._should_suppress_warning(msg):
  475. sdist.warn(self, msg)
  476. @staticmethod
  477. def _should_suppress_warning(msg):
  478. """
  479. suppress missing-file warnings from sdist
  480. """
  481. return re.match(r"standard file .*not found", msg)
  482. def add_defaults(self):
  483. sdist.add_defaults(self)
  484. self.check_license()
  485. self.filelist.append(self.template)
  486. self.filelist.append(self.manifest)
  487. rcfiles = list(walk_revctrl())
  488. if rcfiles:
  489. self.filelist.extend(rcfiles)
  490. elif os.path.exists(self.manifest):
  491. self.read_manifest()
  492. if os.path.exists("setup.py"):
  493. # setup.py should be included by default, even if it's not
  494. # the script called to create the sdist
  495. self.filelist.append("setup.py")
  496. ei_cmd = self.get_finalized_command('egg_info')
  497. self.filelist.graft(ei_cmd.egg_info)
  498. def prune_file_list(self):
  499. build = self.get_finalized_command('build')
  500. base_dir = self.distribution.get_fullname()
  501. self.filelist.prune(build.build_base)
  502. self.filelist.prune(base_dir)
  503. sep = re.escape(os.sep)
  504. self.filelist.exclude_pattern(r'(^|' + sep + r')(RCS|CVS|\.svn)' + sep,
  505. is_regex=1)
  506. def write_file(filename, contents):
  507. """Create a file with the specified name and write 'contents' (a
  508. sequence of strings without line terminators) to it.
  509. """
  510. contents = "\n".join(contents)
  511. # assuming the contents has been vetted for utf-8 encoding
  512. contents = contents.encode("utf-8")
  513. with open(filename, "wb") as f: # always write POSIX-style manifest
  514. f.write(contents)
  515. def write_pkg_info(cmd, basename, filename):
  516. log.info("writing %s", filename)
  517. if not cmd.dry_run:
  518. metadata = cmd.distribution.metadata
  519. metadata.version, oldver = cmd.egg_version, metadata.version
  520. metadata.name, oldname = cmd.egg_name, metadata.name
  521. try:
  522. # write unescaped data to PKG-INFO, so older pkg_resources
  523. # can still parse it
  524. metadata.write_pkg_info(cmd.egg_info)
  525. finally:
  526. metadata.name, metadata.version = oldname, oldver
  527. safe = getattr(cmd.distribution, 'zip_safe', None)
  528. bdist_egg.write_safety_flag(cmd.egg_info, safe)
  529. def warn_depends_obsolete(cmd, basename, filename):
  530. if os.path.exists(filename):
  531. log.warn(
  532. "WARNING: 'depends.txt' is not used by setuptools 0.6!\n"
  533. "Use the install_requires/extras_require setup() args instead."
  534. )
  535. def _write_requirements(stream, reqs):
  536. lines = yield_lines(reqs or ())
  537. def append_cr(line):
  538. return line + '\n'
  539. lines = map(append_cr, lines)
  540. stream.writelines(lines)
  541. def write_requirements(cmd, basename, filename):
  542. dist = cmd.distribution
  543. data = io.StringIO()
  544. _write_requirements(data, dist.install_requires)
  545. extras_require = dist.extras_require or {}
  546. for extra in sorted(extras_require):
  547. data.write('\n[{extra}]\n'.format(**vars()))
  548. _write_requirements(data, extras_require[extra])
  549. cmd.write_or_delete_file("requirements", filename, data.getvalue())
  550. def write_setup_requirements(cmd, basename, filename):
  551. data = io.StringIO()
  552. _write_requirements(data, cmd.distribution.setup_requires)
  553. cmd.write_or_delete_file("setup-requirements", filename, data.getvalue())
  554. def write_toplevel_names(cmd, basename, filename):
  555. pkgs = dict.fromkeys(
  556. [
  557. k.split('.', 1)[0]
  558. for k in cmd.distribution.iter_distribution_names()
  559. ]
  560. )
  561. cmd.write_file("top-level names", filename, '\n'.join(sorted(pkgs)) + '\n')
  562. def overwrite_arg(cmd, basename, filename):
  563. write_arg(cmd, basename, filename, True)
  564. def write_arg(cmd, basename, filename, force=False):
  565. argname = os.path.splitext(basename)[0]
  566. value = getattr(cmd.distribution, argname, None)
  567. if value is not None:
  568. value = '\n'.join(value) + '\n'
  569. cmd.write_or_delete_file(argname, filename, value, force)
  570. def write_entries(cmd, basename, filename):
  571. ep = cmd.distribution.entry_points
  572. if isinstance(ep, str) or ep is None:
  573. data = ep
  574. elif ep is not None:
  575. data = []
  576. for section, contents in sorted(ep.items()):
  577. if not isinstance(contents, str):
  578. contents = EntryPoint.parse_group(section, contents)
  579. contents = '\n'.join(sorted(map(str, contents.values())))
  580. data.append('[%s]\n%s\n\n' % (section, contents))
  581. data = ''.join(data)
  582. cmd.write_or_delete_file('entry points', filename, data, True)
  583. def get_pkg_info_revision():
  584. """
  585. Get a -r### off of PKG-INFO Version in case this is an sdist of
  586. a subversion revision.
  587. """
  588. warnings.warn(
  589. "get_pkg_info_revision is deprecated.", EggInfoDeprecationWarning)
  590. if os.path.exists('PKG-INFO'):
  591. with io.open('PKG-INFO') as f:
  592. for line in f:
  593. match = re.match(r"Version:.*-r(\d+)\s*$", line)
  594. if match:
  595. return int(match.group(1))
  596. return 0
  597. class EggInfoDeprecationWarning(SetuptoolsDeprecationWarning):
  598. """Deprecated behavior warning for EggInfo, bypassing suppression."""