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

/python/lib/Lib/distutils/dist.py

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