PageRenderTime 1622ms CodeModel.GetById 4ms RepoModel.GetById 0ms app.codeStats 0ms

/Lib/distutils/dist.py

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