PageRenderTime 50ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/edk2/AppPkg/Applications/Python/Python-2.7.2/Lib/distutils/dist.py

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