Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

egg_info.py 25KB

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