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