dist.py 45 KB

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