dist.py 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286
  1. """distutils.dist
  2. Provides the Distribution class, which represents the module distribution
  3. being built/installed/distributed.
  4. """
  5. import sys
  6. import os
  7. import re
  8. import pathlib
  9. import contextlib
  10. from email import message_from_file
  11. try:
  12. import warnings
  13. except ImportError:
  14. warnings = None
  15. from distutils.errors import (
  16. DistutilsOptionError,
  17. DistutilsModuleError,
  18. DistutilsArgError,
  19. DistutilsClassError,
  20. )
  21. from distutils.fancy_getopt import FancyGetopt, translate_longopt
  22. from distutils.util import check_environ, strtobool, rfc822_escape
  23. from distutils import log
  24. from distutils.debug import DEBUG
  25. # Regex to define acceptable Distutils command names. This is not *quite*
  26. # the same as a Python NAME -- I don't allow leading underscores. The fact
  27. # that they're very similar is no coincidence; the default naming scheme is
  28. # to look for a Python module named after the command.
  29. command_re = re.compile(r'^[a-zA-Z]([a-zA-Z0-9_]*)$')
  30. def _ensure_list(value, fieldname):
  31. if isinstance(value, str):
  32. # a string containing comma separated values is okay. It will
  33. # be converted to a list by Distribution.finalize_options().
  34. pass
  35. elif not isinstance(value, list):
  36. # passing a tuple or an iterator perhaps, warn and convert
  37. typename = type(value).__name__
  38. msg = "Warning: '{fieldname}' should be a list, got type '{typename}'"
  39. msg = msg.format(**locals())
  40. log.log(log.WARN, msg)
  41. value = list(value)
  42. return value
  43. class Distribution:
  44. """The core of the Distutils. Most of the work hiding behind 'setup'
  45. is really done within a Distribution instance, which farms the work out
  46. to the Distutils commands specified on the command line.
  47. Setup scripts will almost never instantiate Distribution directly,
  48. unless the 'setup()' function is totally inadequate to their needs.
  49. However, it is conceivable that a setup script might wish to subclass
  50. Distribution for some specialized purpose, and then pass the subclass
  51. to 'setup()' as the 'distclass' keyword argument. If so, it is
  52. necessary to respect the expectations that 'setup' has of Distribution.
  53. See the code for 'setup()', in core.py, for details.
  54. """
  55. # 'global_options' describes the command-line options that may be
  56. # supplied to the setup script prior to any actual commands.
  57. # Eg. "./setup.py -n" or "./setup.py --quiet" both take advantage of
  58. # these global options. This list should be kept to a bare minimum,
  59. # since every global option is also valid as a command option -- and we
  60. # don't want to pollute the commands with too many options that they
  61. # have minimal control over.
  62. # The fourth entry for verbose means that it can be repeated.
  63. global_options = [
  64. ('verbose', 'v', "run verbosely (default)", 1),
  65. ('quiet', 'q', "run quietly (turns verbosity off)"),
  66. ('dry-run', 'n', "don't actually do anything"),
  67. ('help', 'h', "show detailed help message"),
  68. ('no-user-cfg', None, 'ignore pydistutils.cfg in your home directory'),
  69. ]
  70. # 'common_usage' is a short (2-3 line) string describing the common
  71. # usage of the setup script.
  72. common_usage = """\
  73. Common commands: (see '--help-commands' for more)
  74. setup.py build will build the package underneath 'build/'
  75. setup.py install will install the package
  76. """
  77. # options that are not propagated to the commands
  78. display_options = [
  79. ('help-commands', None, "list all available commands"),
  80. ('name', None, "print package name"),
  81. ('version', 'V', "print package version"),
  82. ('fullname', None, "print <package name>-<version>"),
  83. ('author', None, "print the author's name"),
  84. ('author-email', None, "print the author's email address"),
  85. ('maintainer', None, "print the maintainer's name"),
  86. ('maintainer-email', None, "print the maintainer's email address"),
  87. ('contact', None, "print the maintainer's name if known, else the author's"),
  88. (
  89. 'contact-email',
  90. None,
  91. "print the maintainer's email address if known, else the author's",
  92. ),
  93. ('url', None, "print the URL for this package"),
  94. ('license', None, "print the license of the package"),
  95. ('licence', None, "alias for --license"),
  96. ('description', None, "print the package description"),
  97. ('long-description', None, "print the long package description"),
  98. ('platforms', None, "print the list of platforms"),
  99. ('classifiers', None, "print the list of classifiers"),
  100. ('keywords', None, "print the list of keywords"),
  101. ('provides', None, "print the list of packages/modules provided"),
  102. ('requires', None, "print the list of packages/modules required"),
  103. ('obsoletes', None, "print the list of packages/modules made obsolete"),
  104. ]
  105. display_option_names = [translate_longopt(x[0]) for x in display_options]
  106. # negative options are options that exclude other options
  107. negative_opt = {'quiet': 'verbose'}
  108. # -- Creation/initialization methods -------------------------------
  109. def __init__(self, attrs=None): # noqa: C901
  110. """Construct a new Distribution instance: initialize all the
  111. attributes of a Distribution, and then use 'attrs' (a dictionary
  112. mapping attribute names to values) to assign some of those
  113. attributes their "real" values. (Any attributes not mentioned in
  114. 'attrs' will be assigned to some null value: 0, None, an empty list
  115. or dictionary, etc.) Most importantly, initialize the
  116. 'command_obj' attribute to the empty dictionary; this will be
  117. filled in with real command objects by 'parse_command_line()'.
  118. """
  119. # Default values for our command-line options
  120. self.verbose = 1
  121. self.dry_run = 0
  122. self.help = 0
  123. for attr in self.display_option_names:
  124. setattr(self, attr, 0)
  125. # Store the distribution meta-data (name, version, author, and so
  126. # forth) in a separate object -- we're getting to have enough
  127. # information here (and enough command-line options) that it's
  128. # worth it. Also delegate 'get_XXX()' methods to the 'metadata'
  129. # object in a sneaky and underhanded (but efficient!) way.
  130. self.metadata = DistributionMetadata()
  131. for basename in self.metadata._METHOD_BASENAMES:
  132. method_name = "get_" + basename
  133. setattr(self, method_name, getattr(self.metadata, method_name))
  134. # 'cmdclass' maps command names to class objects, so we
  135. # can 1) quickly figure out which class to instantiate when
  136. # we need to create a new command object, and 2) have a way
  137. # for the setup script to override command classes
  138. self.cmdclass = {}
  139. # 'command_packages' is a list of packages in which commands
  140. # are searched for. The factory for command 'foo' is expected
  141. # to be named 'foo' in the module 'foo' in one of the packages
  142. # named here. This list is searched from the left; an error
  143. # is raised if no named package provides the command being
  144. # searched for. (Always access using get_command_packages().)
  145. self.command_packages = None
  146. # 'script_name' and 'script_args' are usually set to sys.argv[0]
  147. # and sys.argv[1:], but they can be overridden when the caller is
  148. # not necessarily a setup script run from the command-line.
  149. self.script_name = None
  150. self.script_args = None
  151. # 'command_options' is where we store command options between
  152. # parsing them (from config files, the command-line, etc.) and when
  153. # they are actually needed -- ie. when the command in question is
  154. # instantiated. It is a dictionary of dictionaries of 2-tuples:
  155. # command_options = { command_name : { option : (source, value) } }
  156. self.command_options = {}
  157. # 'dist_files' is the list of (command, pyversion, file) that
  158. # have been created by any dist commands run so far. This is
  159. # filled regardless of whether the run is dry or not. pyversion
  160. # gives sysconfig.get_python_version() if the dist file is
  161. # specific to a Python version, 'any' if it is good for all
  162. # Python versions on the target platform, and '' for a source
  163. # file. pyversion should not be used to specify minimum or
  164. # maximum required Python versions; use the metainfo for that
  165. # instead.
  166. self.dist_files = []
  167. # These options are really the business of various commands, rather
  168. # than of the Distribution itself. We provide aliases for them in
  169. # Distribution as a convenience to the developer.
  170. self.packages = None
  171. self.package_data = {}
  172. self.package_dir = None
  173. self.py_modules = None
  174. self.libraries = None
  175. self.headers = None
  176. self.ext_modules = None
  177. self.ext_package = None
  178. self.include_dirs = None
  179. self.extra_path = None
  180. self.scripts = None
  181. self.data_files = None
  182. self.password = ''
  183. # And now initialize bookkeeping stuff that can't be supplied by
  184. # the caller at all. 'command_obj' maps command names to
  185. # Command instances -- that's how we enforce that every command
  186. # class is a singleton.
  187. self.command_obj = {}
  188. # 'have_run' maps command names to boolean values; it keeps track
  189. # of whether we have actually run a particular command, to make it
  190. # cheap to "run" a command whenever we think we might need to -- if
  191. # it's already been done, no need for expensive filesystem
  192. # operations, we just check the 'have_run' dictionary and carry on.
  193. # It's only safe to query 'have_run' for a command class that has
  194. # been instantiated -- a false value will be inserted when the
  195. # command object is created, and replaced with a true value when
  196. # the command is successfully run. Thus it's probably best to use
  197. # '.get()' rather than a straight lookup.
  198. self.have_run = {}
  199. # Now we'll use the attrs dictionary (ultimately, keyword args from
  200. # the setup script) to possibly override any or all of these
  201. # distribution options.
  202. if attrs:
  203. # Pull out the set of command options and work on them
  204. # specifically. Note that this order guarantees that aliased
  205. # command options will override any supplied redundantly
  206. # through the general options dictionary.
  207. options = attrs.get('options')
  208. if options is not None:
  209. del attrs['options']
  210. for (command, cmd_options) in options.items():
  211. opt_dict = self.get_option_dict(command)
  212. for (opt, val) in cmd_options.items():
  213. opt_dict[opt] = ("setup script", val)
  214. if 'licence' in attrs:
  215. attrs['license'] = attrs['licence']
  216. del attrs['licence']
  217. msg = "'licence' distribution option is deprecated; use 'license'"
  218. if warnings is not None:
  219. warnings.warn(msg)
  220. else:
  221. sys.stderr.write(msg + "\n")
  222. # Now work on the rest of the attributes. Any attribute that's
  223. # not already defined is invalid!
  224. for (key, val) in attrs.items():
  225. if hasattr(self.metadata, "set_" + key):
  226. getattr(self.metadata, "set_" + key)(val)
  227. elif hasattr(self.metadata, key):
  228. setattr(self.metadata, key, val)
  229. elif hasattr(self, key):
  230. setattr(self, key, val)
  231. else:
  232. msg = "Unknown distribution option: %s" % repr(key)
  233. warnings.warn(msg)
  234. # no-user-cfg is handled before other command line args
  235. # because other args override the config files, and this
  236. # one is needed before we can load the config files.
  237. # If attrs['script_args'] wasn't passed, assume false.
  238. #
  239. # This also make sure we just look at the global options
  240. self.want_user_cfg = True
  241. if self.script_args is not None:
  242. for arg in self.script_args:
  243. if not arg.startswith('-'):
  244. break
  245. if arg == '--no-user-cfg':
  246. self.want_user_cfg = False
  247. break
  248. self.finalize_options()
  249. def get_option_dict(self, command):
  250. """Get the option dictionary for a given command. If that
  251. command's option dictionary hasn't been created yet, then create it
  252. and return the new dictionary; otherwise, return the existing
  253. option dictionary.
  254. """
  255. dict = self.command_options.get(command)
  256. if dict is None:
  257. dict = self.command_options[command] = {}
  258. return dict
  259. def dump_option_dicts(self, header=None, commands=None, indent=""):
  260. from pprint import pformat
  261. if commands is None: # dump all command option dicts
  262. commands = sorted(self.command_options.keys())
  263. if header is not None:
  264. self.announce(indent + header)
  265. indent = indent + " "
  266. if not commands:
  267. self.announce(indent + "no commands known yet")
  268. return
  269. for cmd_name in commands:
  270. opt_dict = self.command_options.get(cmd_name)
  271. if opt_dict is None:
  272. self.announce(indent + "no option dict for '%s' command" % cmd_name)
  273. else:
  274. self.announce(indent + "option dict for '%s' command:" % cmd_name)
  275. out = pformat(opt_dict)
  276. for line in out.split('\n'):
  277. self.announce(indent + " " + line)
  278. # -- Config file finding/parsing methods ---------------------------
  279. def find_config_files(self):
  280. """Find as many configuration files as should be processed for this
  281. platform, and return a list of filenames in the order in which they
  282. should be parsed. The filenames returned are guaranteed to exist
  283. (modulo nasty race conditions).
  284. There are multiple possible config files:
  285. - distutils.cfg in the Distutils installation directory (i.e.
  286. where the top-level Distutils __inst__.py file lives)
  287. - a file in the user's home directory named .pydistutils.cfg
  288. on Unix and pydistutils.cfg on Windows/Mac; may be disabled
  289. with the ``--no-user-cfg`` option
  290. - setup.cfg in the current directory
  291. - a file named by an environment variable
  292. """
  293. check_environ()
  294. files = [str(path) for path in self._gen_paths() if os.path.isfile(path)]
  295. if DEBUG:
  296. self.announce("using config files: %s" % ', '.join(files))
  297. return files
  298. def _gen_paths(self):
  299. # The system-wide Distutils config file
  300. sys_dir = pathlib.Path(sys.modules['distutils'].__file__).parent
  301. yield sys_dir / "distutils.cfg"
  302. # The per-user config file
  303. prefix = '.' * (os.name == 'posix')
  304. filename = prefix + 'pydistutils.cfg'
  305. if self.want_user_cfg:
  306. yield pathlib.Path('~').expanduser() / filename
  307. # All platforms support local setup.cfg
  308. yield pathlib.Path('setup.cfg')
  309. # Additional config indicated in the environment
  310. with contextlib.suppress(TypeError):
  311. yield pathlib.Path(os.getenv("DIST_EXTRA_CONFIG"))
  312. def parse_config_files(self, filenames=None): # noqa: C901
  313. from configparser import ConfigParser
  314. # Ignore install directory options if we have a venv
  315. if sys.prefix != sys.base_prefix:
  316. ignore_options = [
  317. 'install-base',
  318. 'install-platbase',
  319. 'install-lib',
  320. 'install-platlib',
  321. 'install-purelib',
  322. 'install-headers',
  323. 'install-scripts',
  324. 'install-data',
  325. 'prefix',
  326. 'exec-prefix',
  327. 'home',
  328. 'user',
  329. 'root',
  330. ]
  331. else:
  332. ignore_options = []
  333. ignore_options = frozenset(ignore_options)
  334. if filenames is None:
  335. filenames = self.find_config_files()
  336. if DEBUG:
  337. self.announce("Distribution.parse_config_files():")
  338. parser = ConfigParser()
  339. for filename in filenames:
  340. if DEBUG:
  341. self.announce(" reading %s" % filename)
  342. parser.read(filename)
  343. for section in parser.sections():
  344. options = parser.options(section)
  345. opt_dict = self.get_option_dict(section)
  346. for opt in options:
  347. if opt != '__name__' and opt not in ignore_options:
  348. val = parser.get(section, opt)
  349. opt = opt.replace('-', '_')
  350. opt_dict[opt] = (filename, val)
  351. # Make the ConfigParser forget everything (so we retain
  352. # the original filenames that options come from)
  353. parser.__init__()
  354. # If there was a "global" section in the config file, use it
  355. # to set Distribution options.
  356. if 'global' in self.command_options:
  357. for (opt, (src, val)) in self.command_options['global'].items():
  358. alias = self.negative_opt.get(opt)
  359. try:
  360. if alias:
  361. setattr(self, alias, not strtobool(val))
  362. elif opt in ('verbose', 'dry_run'): # ugh!
  363. setattr(self, opt, strtobool(val))
  364. else:
  365. setattr(self, opt, val)
  366. except ValueError as msg:
  367. raise DistutilsOptionError(msg)
  368. # -- Command-line parsing methods ----------------------------------
  369. def parse_command_line(self):
  370. """Parse the setup script's command line, taken from the
  371. 'script_args' instance attribute (which defaults to 'sys.argv[1:]'
  372. -- see 'setup()' in core.py). This list is first processed for
  373. "global options" -- options that set attributes of the Distribution
  374. instance. Then, it is alternately scanned for Distutils commands
  375. and options for that command. Each new command terminates the
  376. options for the previous command. The allowed options for a
  377. command are determined by the 'user_options' attribute of the
  378. command class -- thus, we have to be able to load command classes
  379. in order to parse the command line. Any error in that 'options'
  380. attribute raises DistutilsGetoptError; any error on the
  381. command-line raises DistutilsArgError. If no Distutils commands
  382. were found on the command line, raises DistutilsArgError. Return
  383. true if command-line was successfully parsed and we should carry
  384. on with executing commands; false if no errors but we shouldn't
  385. execute commands (currently, this only happens if user asks for
  386. help).
  387. """
  388. #
  389. # We now have enough information to show the Macintosh dialog
  390. # that allows the user to interactively specify the "command line".
  391. #
  392. toplevel_options = self._get_toplevel_options()
  393. # We have to parse the command line a bit at a time -- global
  394. # options, then the first command, then its options, and so on --
  395. # because each command will be handled by a different class, and
  396. # the options that are valid for a particular class aren't known
  397. # until we have loaded the command class, which doesn't happen
  398. # until we know what the command is.
  399. self.commands = []
  400. parser = FancyGetopt(toplevel_options + self.display_options)
  401. parser.set_negative_aliases(self.negative_opt)
  402. parser.set_aliases({'licence': 'license'})
  403. args = parser.getopt(args=self.script_args, object=self)
  404. option_order = parser.get_option_order()
  405. log.set_verbosity(self.verbose)
  406. # for display options we return immediately
  407. if self.handle_display_options(option_order):
  408. return
  409. while args:
  410. args = self._parse_command_opts(parser, args)
  411. if args is None: # user asked for help (and got it)
  412. return
  413. # Handle the cases of --help as a "global" option, ie.
  414. # "setup.py --help" and "setup.py --help command ...". For the
  415. # former, we show global options (--verbose, --dry-run, etc.)
  416. # and display-only options (--name, --version, etc.); for the
  417. # latter, we omit the display-only options and show help for
  418. # each command listed on the command line.
  419. if self.help:
  420. self._show_help(
  421. parser, display_options=len(self.commands) == 0, commands=self.commands
  422. )
  423. return
  424. # Oops, no commands found -- an end-user error
  425. if not self.commands:
  426. raise DistutilsArgError("no commands supplied")
  427. # All is well: return true
  428. return True
  429. def _get_toplevel_options(self):
  430. """Return the non-display options recognized at the top level.
  431. This includes options that are recognized *only* at the top
  432. level as well as options recognized for commands.
  433. """
  434. return self.global_options + [
  435. (
  436. "command-packages=",
  437. None,
  438. "list of packages that provide distutils commands",
  439. ),
  440. ]
  441. def _parse_command_opts(self, parser, args): # noqa: C901
  442. """Parse the command-line options for a single command.
  443. 'parser' must be a FancyGetopt instance; 'args' must be the list
  444. of arguments, starting with the current command (whose options
  445. we are about to parse). Returns a new version of 'args' with
  446. the next command at the front of the list; will be the empty
  447. list if there are no more commands on the command line. Returns
  448. None if the user asked for help on this command.
  449. """
  450. # late import because of mutual dependence between these modules
  451. from distutils.cmd import Command
  452. # Pull the current command from the head of the command line
  453. command = args[0]
  454. if not command_re.match(command):
  455. raise SystemExit("invalid command name '%s'" % command)
  456. self.commands.append(command)
  457. # Dig up the command class that implements this command, so we
  458. # 1) know that it's a valid command, and 2) know which options
  459. # it takes.
  460. try:
  461. cmd_class = self.get_command_class(command)
  462. except DistutilsModuleError as msg:
  463. raise DistutilsArgError(msg)
  464. # Require that the command class be derived from Command -- want
  465. # to be sure that the basic "command" interface is implemented.
  466. if not issubclass(cmd_class, Command):
  467. raise DistutilsClassError(
  468. "command class %s must subclass Command" % cmd_class
  469. )
  470. # Also make sure that the command object provides a list of its
  471. # known options.
  472. if not (
  473. hasattr(cmd_class, 'user_options')
  474. and isinstance(cmd_class.user_options, list)
  475. ):
  476. msg = (
  477. "command class %s must provide "
  478. "'user_options' attribute (a list of tuples)"
  479. )
  480. raise DistutilsClassError(msg % cmd_class)
  481. # If the command class has a list of negative alias options,
  482. # merge it in with the global negative aliases.
  483. negative_opt = self.negative_opt
  484. if hasattr(cmd_class, 'negative_opt'):
  485. negative_opt = negative_opt.copy()
  486. negative_opt.update(cmd_class.negative_opt)
  487. # Check for help_options in command class. They have a different
  488. # format (tuple of four) so we need to preprocess them here.
  489. if hasattr(cmd_class, 'help_options') and isinstance(
  490. cmd_class.help_options, list
  491. ):
  492. help_options = fix_help_options(cmd_class.help_options)
  493. else:
  494. help_options = []
  495. # All commands support the global options too, just by adding
  496. # in 'global_options'.
  497. parser.set_option_table(
  498. self.global_options + cmd_class.user_options + help_options
  499. )
  500. parser.set_negative_aliases(negative_opt)
  501. (args, opts) = parser.getopt(args[1:])
  502. if hasattr(opts, 'help') and opts.help:
  503. self._show_help(parser, display_options=0, commands=[cmd_class])
  504. return
  505. if hasattr(cmd_class, 'help_options') and isinstance(
  506. cmd_class.help_options, list
  507. ):
  508. help_option_found = 0
  509. for (help_option, short, desc, func) in cmd_class.help_options:
  510. if hasattr(opts, parser.get_attr_name(help_option)):
  511. help_option_found = 1
  512. if callable(func):
  513. func()
  514. else:
  515. raise DistutilsClassError(
  516. "invalid help function %r for help option '%s': "
  517. "must be a callable object (function, etc.)"
  518. % (func, help_option)
  519. )
  520. if help_option_found:
  521. return
  522. # Put the options from the command-line into their official
  523. # holding pen, the 'command_options' dictionary.
  524. opt_dict = self.get_option_dict(command)
  525. for (name, value) in vars(opts).items():
  526. opt_dict[name] = ("command line", value)
  527. return args
  528. def finalize_options(self):
  529. """Set final values for all the options on the Distribution
  530. instance, analogous to the .finalize_options() method of Command
  531. objects.
  532. """
  533. for attr in ('keywords', 'platforms'):
  534. value = getattr(self.metadata, attr)
  535. if value is None:
  536. continue
  537. if isinstance(value, str):
  538. value = [elm.strip() for elm in value.split(',')]
  539. setattr(self.metadata, attr, value)
  540. def _show_help(self, parser, global_options=1, display_options=1, commands=[]):
  541. """Show help for the setup script command-line in the form of
  542. several lists of command-line options. 'parser' should be a
  543. FancyGetopt instance; do not expect it to be returned in the
  544. same state, as its option table will be reset to make it
  545. generate the correct help text.
  546. If 'global_options' is true, lists the global options:
  547. --verbose, --dry-run, etc. If 'display_options' is true, lists
  548. the "display-only" options: --name, --version, etc. Finally,
  549. lists per-command help for every command name or command class
  550. in 'commands'.
  551. """
  552. # late import because of mutual dependence between these modules
  553. from distutils.core import gen_usage
  554. from distutils.cmd import Command
  555. if global_options:
  556. if display_options:
  557. options = self._get_toplevel_options()
  558. else:
  559. options = self.global_options
  560. parser.set_option_table(options)
  561. parser.print_help(self.common_usage + "\nGlobal options:")
  562. print('')
  563. if display_options:
  564. parser.set_option_table(self.display_options)
  565. parser.print_help(
  566. "Information display options (just display "
  567. + "information, ignore any commands)"
  568. )
  569. print('')
  570. for command in self.commands:
  571. if isinstance(command, type) and issubclass(command, Command):
  572. klass = command
  573. else:
  574. klass = self.get_command_class(command)
  575. if hasattr(klass, 'help_options') and isinstance(klass.help_options, list):
  576. parser.set_option_table(
  577. klass.user_options + fix_help_options(klass.help_options)
  578. )
  579. else:
  580. parser.set_option_table(klass.user_options)
  581. parser.print_help("Options for '%s' command:" % klass.__name__)
  582. print('')
  583. print(gen_usage(self.script_name))
  584. def handle_display_options(self, option_order):
  585. """If there were any non-global "display-only" options
  586. (--help-commands or the metadata display options) on the command
  587. line, display the requested info and return true; else return
  588. false.
  589. """
  590. from distutils.core import gen_usage
  591. # User just wants a list of commands -- we'll print it out and stop
  592. # processing now (ie. if they ran "setup --help-commands foo bar",
  593. # we ignore "foo bar").
  594. if self.help_commands:
  595. self.print_commands()
  596. print('')
  597. print(gen_usage(self.script_name))
  598. return 1
  599. # If user supplied any of the "display metadata" options, then
  600. # display that metadata in the order in which the user supplied the
  601. # metadata options.
  602. any_display_options = 0
  603. is_display_option = {}
  604. for option in self.display_options:
  605. is_display_option[option[0]] = 1
  606. for (opt, val) in option_order:
  607. if val and is_display_option.get(opt):
  608. opt = translate_longopt(opt)
  609. value = getattr(self.metadata, "get_" + opt)()
  610. if opt in ['keywords', 'platforms']:
  611. print(','.join(value))
  612. elif opt in ('classifiers', 'provides', 'requires', 'obsoletes'):
  613. print('\n'.join(value))
  614. else:
  615. print(value)
  616. any_display_options = 1
  617. return any_display_options
  618. def print_command_list(self, commands, header, max_length):
  619. """Print a subset of the list of all commands -- used by
  620. 'print_commands()'.
  621. """
  622. print(header + ":")
  623. for cmd in commands:
  624. klass = self.cmdclass.get(cmd)
  625. if not klass:
  626. klass = self.get_command_class(cmd)
  627. try:
  628. description = klass.description
  629. except AttributeError:
  630. description = "(no description available)"
  631. print(" %-*s %s" % (max_length, cmd, description))
  632. def print_commands(self):
  633. """Print out a help message listing all available commands with a
  634. description of each. The list is divided into "standard commands"
  635. (listed in distutils.command.__all__) and "extra commands"
  636. (mentioned in self.cmdclass, but not a standard command). The
  637. descriptions come from the command class attribute
  638. 'description'.
  639. """
  640. import distutils.command
  641. std_commands = distutils.command.__all__
  642. is_std = {}
  643. for cmd in std_commands:
  644. is_std[cmd] = 1
  645. extra_commands = []
  646. for cmd in self.cmdclass.keys():
  647. if not is_std.get(cmd):
  648. extra_commands.append(cmd)
  649. max_length = 0
  650. for cmd in std_commands + extra_commands:
  651. if len(cmd) > max_length:
  652. max_length = len(cmd)
  653. self.print_command_list(std_commands, "Standard commands", max_length)
  654. if extra_commands:
  655. print()
  656. self.print_command_list(extra_commands, "Extra commands", max_length)
  657. def get_command_list(self):
  658. """Get a list of (command, description) tuples.
  659. The list is divided into "standard commands" (listed in
  660. distutils.command.__all__) and "extra commands" (mentioned in
  661. self.cmdclass, but not a standard command). The descriptions come
  662. from the command class attribute 'description'.
  663. """
  664. # Currently this is only used on Mac OS, for the Mac-only GUI
  665. # Distutils interface (by Jack Jansen)
  666. import distutils.command
  667. std_commands = distutils.command.__all__
  668. is_std = {}
  669. for cmd in std_commands:
  670. is_std[cmd] = 1
  671. extra_commands = []
  672. for cmd in self.cmdclass.keys():
  673. if not is_std.get(cmd):
  674. extra_commands.append(cmd)
  675. rv = []
  676. for cmd in std_commands + extra_commands:
  677. klass = self.cmdclass.get(cmd)
  678. if not klass:
  679. klass = self.get_command_class(cmd)
  680. try:
  681. description = klass.description
  682. except AttributeError:
  683. description = "(no description available)"
  684. rv.append((cmd, description))
  685. return rv
  686. # -- Command class/object methods ----------------------------------
  687. def get_command_packages(self):
  688. """Return a list of packages from which commands are loaded."""
  689. pkgs = self.command_packages
  690. if not isinstance(pkgs, list):
  691. if pkgs is None:
  692. pkgs = ''
  693. pkgs = [pkg.strip() for pkg in pkgs.split(',') if pkg != '']
  694. if "distutils.command" not in pkgs:
  695. pkgs.insert(0, "distutils.command")
  696. self.command_packages = pkgs
  697. return pkgs
  698. def get_command_class(self, command):
  699. """Return the class that implements the Distutils command named by
  700. 'command'. First we check the 'cmdclass' dictionary; if the
  701. command is mentioned there, we fetch the class object from the
  702. dictionary and return it. Otherwise we load the command module
  703. ("distutils.command." + command) and fetch the command class from
  704. the module. The loaded class is also stored in 'cmdclass'
  705. to speed future calls to 'get_command_class()'.
  706. Raises DistutilsModuleError if the expected module could not be
  707. found, or if that module does not define the expected class.
  708. """
  709. klass = self.cmdclass.get(command)
  710. if klass:
  711. return klass
  712. for pkgname in self.get_command_packages():
  713. module_name = "{}.{}".format(pkgname, command)
  714. klass_name = command
  715. try:
  716. __import__(module_name)
  717. module = sys.modules[module_name]
  718. except ImportError:
  719. continue
  720. try:
  721. klass = getattr(module, klass_name)
  722. except AttributeError:
  723. raise DistutilsModuleError(
  724. "invalid command '%s' (no class '%s' in module '%s')"
  725. % (command, klass_name, module_name)
  726. )
  727. self.cmdclass[command] = klass
  728. return klass
  729. raise DistutilsModuleError("invalid command '%s'" % command)
  730. def get_command_obj(self, command, create=1):
  731. """Return the command object for 'command'. Normally this object
  732. is cached on a previous call to 'get_command_obj()'; if no command
  733. object for 'command' is in the cache, then we either create and
  734. return it (if 'create' is true) or return None.
  735. """
  736. cmd_obj = self.command_obj.get(command)
  737. if not cmd_obj and create:
  738. if DEBUG:
  739. self.announce(
  740. "Distribution.get_command_obj(): "
  741. "creating '%s' command object" % command
  742. )
  743. klass = self.get_command_class(command)
  744. cmd_obj = self.command_obj[command] = klass(self)
  745. self.have_run[command] = 0
  746. # Set any options that were supplied in config files
  747. # or on the command line. (NB. support for error
  748. # reporting is lame here: any errors aren't reported
  749. # until 'finalize_options()' is called, which means
  750. # we won't report the source of the error.)
  751. options = self.command_options.get(command)
  752. if options:
  753. self._set_command_options(cmd_obj, options)
  754. return cmd_obj
  755. def _set_command_options(self, command_obj, option_dict=None): # noqa: C901
  756. """Set the options for 'command_obj' from 'option_dict'. Basically
  757. this means copying elements of a dictionary ('option_dict') to
  758. attributes of an instance ('command').
  759. 'command_obj' must be a Command instance. If 'option_dict' is not
  760. supplied, uses the standard option dictionary for this command
  761. (from 'self.command_options').
  762. """
  763. command_name = command_obj.get_command_name()
  764. if option_dict is None:
  765. option_dict = self.get_option_dict(command_name)
  766. if DEBUG:
  767. self.announce(" setting options for '%s' command:" % command_name)
  768. for (option, (source, value)) in option_dict.items():
  769. if DEBUG:
  770. self.announce(" {} = {} (from {})".format(option, value, source))
  771. try:
  772. bool_opts = [translate_longopt(o) for o in command_obj.boolean_options]
  773. except AttributeError:
  774. bool_opts = []
  775. try:
  776. neg_opt = command_obj.negative_opt
  777. except AttributeError:
  778. neg_opt = {}
  779. try:
  780. is_string = isinstance(value, str)
  781. if option in neg_opt and is_string:
  782. setattr(command_obj, neg_opt[option], not strtobool(value))
  783. elif option in bool_opts and is_string:
  784. setattr(command_obj, option, strtobool(value))
  785. elif hasattr(command_obj, option):
  786. setattr(command_obj, option, value)
  787. else:
  788. raise DistutilsOptionError(
  789. "error in %s: command '%s' has no such option '%s'"
  790. % (source, command_name, option)
  791. )
  792. except ValueError as msg:
  793. raise DistutilsOptionError(msg)
  794. def reinitialize_command(self, command, reinit_subcommands=0):
  795. """Reinitializes a command to the state it was in when first
  796. returned by 'get_command_obj()': ie., initialized but not yet
  797. finalized. This provides the opportunity to sneak option
  798. values in programmatically, overriding or supplementing
  799. user-supplied values from the config files and command line.
  800. You'll have to re-finalize the command object (by calling
  801. 'finalize_options()' or 'ensure_finalized()') before using it for
  802. real.
  803. 'command' should be a command name (string) or command object. If
  804. 'reinit_subcommands' is true, also reinitializes the command's
  805. sub-commands, as declared by the 'sub_commands' class attribute (if
  806. it has one). See the "install" command for an example. Only
  807. reinitializes the sub-commands that actually matter, ie. those
  808. whose test predicates return true.
  809. Returns the reinitialized command object.
  810. """
  811. from distutils.cmd import Command
  812. if not isinstance(command, Command):
  813. command_name = command
  814. command = self.get_command_obj(command_name)
  815. else:
  816. command_name = command.get_command_name()
  817. if not command.finalized:
  818. return command
  819. command.initialize_options()
  820. command.finalized = 0
  821. self.have_run[command_name] = 0
  822. self._set_command_options(command)
  823. if reinit_subcommands:
  824. for sub in command.get_sub_commands():
  825. self.reinitialize_command(sub, reinit_subcommands)
  826. return command
  827. # -- Methods that operate on the Distribution ----------------------
  828. def announce(self, msg, level=log.INFO):
  829. log.log(level, msg)
  830. def run_commands(self):
  831. """Run each command that was seen on the setup script command line.
  832. Uses the list of commands found and cache of command objects
  833. created by 'get_command_obj()'.
  834. """
  835. for cmd in self.commands:
  836. self.run_command(cmd)
  837. # -- Methods that operate on its Commands --------------------------
  838. def run_command(self, command):
  839. """Do whatever it takes to run a command (including nothing at all,
  840. if the command has already been run). Specifically: if we have
  841. already created and run the command named by 'command', return
  842. silently without doing anything. If the command named by 'command'
  843. doesn't even have a command object yet, create one. Then invoke
  844. 'run()' on that command object (or an existing one).
  845. """
  846. # Already been here, done that? then return silently.
  847. if self.have_run.get(command):
  848. return
  849. log.info("running %s", command)
  850. cmd_obj = self.get_command_obj(command)
  851. cmd_obj.ensure_finalized()
  852. cmd_obj.run()
  853. self.have_run[command] = 1
  854. # -- Distribution query methods ------------------------------------
  855. def has_pure_modules(self):
  856. return len(self.packages or self.py_modules or []) > 0
  857. def has_ext_modules(self):
  858. return self.ext_modules and len(self.ext_modules) > 0
  859. def has_c_libraries(self):
  860. return self.libraries and len(self.libraries) > 0
  861. def has_modules(self):
  862. return self.has_pure_modules() or self.has_ext_modules()
  863. def has_headers(self):
  864. return self.headers and len(self.headers) > 0
  865. def has_scripts(self):
  866. return self.scripts and len(self.scripts) > 0
  867. def has_data_files(self):
  868. return self.data_files and len(self.data_files) > 0
  869. def is_pure(self):
  870. return (
  871. self.has_pure_modules()
  872. and not self.has_ext_modules()
  873. and not self.has_c_libraries()
  874. )
  875. # -- Metadata query methods ----------------------------------------
  876. # If you're looking for 'get_name()', 'get_version()', and so forth,
  877. # they are defined in a sneaky way: the constructor binds self.get_XXX
  878. # to self.metadata.get_XXX. The actual code is in the
  879. # DistributionMetadata class, below.
  880. class DistributionMetadata:
  881. """Dummy class to hold the distribution meta-data: name, version,
  882. author, and so forth.
  883. """
  884. _METHOD_BASENAMES = (
  885. "name",
  886. "version",
  887. "author",
  888. "author_email",
  889. "maintainer",
  890. "maintainer_email",
  891. "url",
  892. "license",
  893. "description",
  894. "long_description",
  895. "keywords",
  896. "platforms",
  897. "fullname",
  898. "contact",
  899. "contact_email",
  900. "classifiers",
  901. "download_url",
  902. # PEP 314
  903. "provides",
  904. "requires",
  905. "obsoletes",
  906. )
  907. def __init__(self, path=None):
  908. if path is not None:
  909. self.read_pkg_file(open(path))
  910. else:
  911. self.name = None
  912. self.version = None
  913. self.author = None
  914. self.author_email = None
  915. self.maintainer = None
  916. self.maintainer_email = None
  917. self.url = None
  918. self.license = None
  919. self.description = None
  920. self.long_description = None
  921. self.keywords = None
  922. self.platforms = None
  923. self.classifiers = None
  924. self.download_url = None
  925. # PEP 314
  926. self.provides = None
  927. self.requires = None
  928. self.obsoletes = None
  929. def read_pkg_file(self, file):
  930. """Reads the metadata values from a file object."""
  931. msg = message_from_file(file)
  932. def _read_field(name):
  933. value = msg[name]
  934. if value and value != "UNKNOWN":
  935. return value
  936. def _read_list(name):
  937. values = msg.get_all(name, None)
  938. if values == []:
  939. return None
  940. return values
  941. metadata_version = msg['metadata-version']
  942. self.name = _read_field('name')
  943. self.version = _read_field('version')
  944. self.description = _read_field('summary')
  945. # we are filling author only.
  946. self.author = _read_field('author')
  947. self.maintainer = None
  948. self.author_email = _read_field('author-email')
  949. self.maintainer_email = None
  950. self.url = _read_field('home-page')
  951. self.license = _read_field('license')
  952. if 'download-url' in msg:
  953. self.download_url = _read_field('download-url')
  954. else:
  955. self.download_url = None
  956. self.long_description = _read_field('description')
  957. self.description = _read_field('summary')
  958. if 'keywords' in msg:
  959. self.keywords = _read_field('keywords').split(',')
  960. self.platforms = _read_list('platform')
  961. self.classifiers = _read_list('classifier')
  962. # PEP 314 - these fields only exist in 1.1
  963. if metadata_version == '1.1':
  964. self.requires = _read_list('requires')
  965. self.provides = _read_list('provides')
  966. self.obsoletes = _read_list('obsoletes')
  967. else:
  968. self.requires = None
  969. self.provides = None
  970. self.obsoletes = None
  971. def write_pkg_info(self, base_dir):
  972. """Write the PKG-INFO file into the release tree."""
  973. with open(
  974. os.path.join(base_dir, 'PKG-INFO'), 'w', encoding='UTF-8'
  975. ) as pkg_info:
  976. self.write_pkg_file(pkg_info)
  977. def write_pkg_file(self, file):
  978. """Write the PKG-INFO format data to a file object."""
  979. version = '1.0'
  980. if (
  981. self.provides
  982. or self.requires
  983. or self.obsoletes
  984. or self.classifiers
  985. or self.download_url
  986. ):
  987. version = '1.1'
  988. # required fields
  989. file.write('Metadata-Version: %s\n' % version)
  990. file.write('Name: %s\n' % self.get_name())
  991. file.write('Version: %s\n' % self.get_version())
  992. def maybe_write(header, val):
  993. if val:
  994. file.write(f"{header}: {val}\n")
  995. # optional fields
  996. maybe_write("Summary", self.get_description())
  997. maybe_write("Home-page", self.get_url())
  998. maybe_write("Author", self.get_contact())
  999. maybe_write("Author-email", self.get_contact_email())
  1000. maybe_write("License", self.get_license())
  1001. maybe_write("Download-URL", self.download_url)
  1002. maybe_write("Description", rfc822_escape(self.get_long_description() or ""))
  1003. maybe_write("Keywords", ",".join(self.get_keywords()))
  1004. self._write_list(file, 'Platform', self.get_platforms())
  1005. self._write_list(file, 'Classifier', self.get_classifiers())
  1006. # PEP 314
  1007. self._write_list(file, 'Requires', self.get_requires())
  1008. self._write_list(file, 'Provides', self.get_provides())
  1009. self._write_list(file, 'Obsoletes', self.get_obsoletes())
  1010. def _write_list(self, file, name, values):
  1011. values = values or []
  1012. for value in values:
  1013. file.write('{}: {}\n'.format(name, value))
  1014. # -- Metadata query methods ----------------------------------------
  1015. def get_name(self):
  1016. return self.name or "UNKNOWN"
  1017. def get_version(self):
  1018. return self.version or "0.0.0"
  1019. def get_fullname(self):
  1020. return "{}-{}".format(self.get_name(), self.get_version())
  1021. def get_author(self):
  1022. return self.author
  1023. def get_author_email(self):
  1024. return self.author_email
  1025. def get_maintainer(self):
  1026. return self.maintainer
  1027. def get_maintainer_email(self):
  1028. return self.maintainer_email
  1029. def get_contact(self):
  1030. return self.maintainer or self.author
  1031. def get_contact_email(self):
  1032. return self.maintainer_email or self.author_email
  1033. def get_url(self):
  1034. return self.url
  1035. def get_license(self):
  1036. return self.license
  1037. get_licence = get_license
  1038. def get_description(self):
  1039. return self.description
  1040. def get_long_description(self):
  1041. return self.long_description
  1042. def get_keywords(self):
  1043. return self.keywords or []
  1044. def set_keywords(self, value):
  1045. self.keywords = _ensure_list(value, 'keywords')
  1046. def get_platforms(self):
  1047. return self.platforms
  1048. def set_platforms(self, value):
  1049. self.platforms = _ensure_list(value, 'platforms')
  1050. def get_classifiers(self):
  1051. return self.classifiers or []
  1052. def set_classifiers(self, value):
  1053. self.classifiers = _ensure_list(value, 'classifiers')
  1054. def get_download_url(self):
  1055. return self.download_url
  1056. # PEP 314
  1057. def get_requires(self):
  1058. return self.requires or []
  1059. def set_requires(self, value):
  1060. import distutils.versionpredicate
  1061. for v in value:
  1062. distutils.versionpredicate.VersionPredicate(v)
  1063. self.requires = list(value)
  1064. def get_provides(self):
  1065. return self.provides or []
  1066. def set_provides(self, value):
  1067. value = [v.strip() for v in value]
  1068. for v in value:
  1069. import distutils.versionpredicate
  1070. distutils.versionpredicate.split_provision(v)
  1071. self.provides = value
  1072. def get_obsoletes(self):
  1073. return self.obsoletes or []
  1074. def set_obsoletes(self, value):
  1075. import distutils.versionpredicate
  1076. for v in value:
  1077. distutils.versionpredicate.VersionPredicate(v)
  1078. self.obsoletes = list(value)
  1079. def fix_help_options(options):
  1080. """Convert a 4-tuple 'help_options' list as found in various command
  1081. classes to the 3-tuple form required by FancyGetopt.
  1082. """
  1083. new_options = []
  1084. for help_tuple in options:
  1085. new_options.append(help_tuple[0:3])
  1086. return new_options