PageRenderTime 29ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/Lib/distutils/dist.py

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