blob: ade2ab795c8c9f785e140ce4498ae8446dfc6b36 [file] [log] [blame]
Greg Wardfe6462c2000-04-04 01:40:52 +00001"""distutils.dist
2
3Provides the Distribution class, which represents the module distribution
Greg Ward8ff5a3f2000-06-02 00:44:53 +00004being built/installed/distributed.
5"""
Greg Wardfe6462c2000-04-04 01:40:52 +00006
Greg Wardfe6462c2000-04-04 01:40:52 +00007__revision__ = "$Id$"
8
Neal Norwitz9d72bb42007-04-17 08:48:32 +00009import sys, os, re
Greg Wardfe6462c2000-04-04 01:40:52 +000010from copy import copy
Andrew M. Kuchlingff4ad9a2002-10-31 13:22:41 +000011
12try:
13 import warnings
Andrew M. Kuchlingccf4e422002-10-31 13:39:33 +000014except ImportError:
Andrew M. Kuchlingff4ad9a2002-10-31 13:22:41 +000015 warnings = None
16
Greg Wardfe6462c2000-04-04 01:40:52 +000017from distutils.errors import *
Greg Ward2f2b6c62000-09-25 01:58:07 +000018from distutils.fancy_getopt import FancyGetopt, translate_longopt
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +000019from distutils.util import check_environ, strtobool, rfc822_escape
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000020from distutils import log
Jeremy Hyltonfcd73532002-09-11 16:31:53 +000021from distutils.debug import DEBUG
Greg Wardfe6462c2000-04-04 01:40:52 +000022
23# Regex to define acceptable Distutils command names. This is not *quite*
24# the same as a Python NAME -- I don't allow leading underscores. The fact
25# that they're very similar is no coincidence; the default naming scheme is
26# to look for a Python module named after the command.
27command_re = re.compile (r'^[a-zA-Z]([a-zA-Z0-9_]*)$')
28
29
30class Distribution:
Greg Ward8ff5a3f2000-06-02 00:44:53 +000031 """The core of the Distutils. Most of the work hiding behind 'setup'
32 is really done within a Distribution instance, which farms the work out
33 to the Distutils commands specified on the command line.
Greg Wardfe6462c2000-04-04 01:40:52 +000034
Greg Ward8ff5a3f2000-06-02 00:44:53 +000035 Setup scripts will almost never instantiate Distribution directly,
36 unless the 'setup()' function is totally inadequate to their needs.
37 However, it is conceivable that a setup script might wish to subclass
38 Distribution for some specialized purpose, and then pass the subclass
39 to 'setup()' as the 'distclass' keyword argument. If so, it is
40 necessary to respect the expectations that 'setup' has of Distribution.
41 See the code for 'setup()', in core.py, for details.
42 """
Greg Wardfe6462c2000-04-04 01:40:52 +000043
44
45 # 'global_options' describes the command-line options that may be
Greg Ward82715e12000-04-21 02:28:14 +000046 # supplied to the setup script prior to any actual commands.
47 # Eg. "./setup.py -n" or "./setup.py --quiet" both take advantage of
Greg Wardfe6462c2000-04-04 01:40:52 +000048 # these global options. This list should be kept to a bare minimum,
49 # since every global option is also valid as a command option -- and we
50 # don't want to pollute the commands with too many options that they
51 # have minimal control over.
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000052 # The fourth entry for verbose means that it can be repeated.
53 global_options = [('verbose', 'v', "run verbosely (default)", 1),
Greg Wardd5d8a992000-05-23 01:42:17 +000054 ('quiet', 'q', "run quietly (turns verbosity off)"),
55 ('dry-run', 'n', "don't actually do anything"),
56 ('help', 'h', "show detailed help message"),
Greg Wardfe6462c2000-04-04 01:40:52 +000057 ]
Greg Ward82715e12000-04-21 02:28:14 +000058
Martin v. Löwis8ed338a2005-03-03 08:12:27 +000059 # 'common_usage' is a short (2-3 line) string describing the common
60 # usage of the setup script.
61 common_usage = """\
62Common commands: (see '--help-commands' for more)
63
64 setup.py build will build the package underneath 'build/'
65 setup.py install will install the package
66"""
67
Greg Ward82715e12000-04-21 02:28:14 +000068 # options that are not propagated to the commands
69 display_options = [
70 ('help-commands', None,
71 "list all available commands"),
72 ('name', None,
73 "print package name"),
74 ('version', 'V',
75 "print package version"),
76 ('fullname', None,
77 "print <package name>-<version>"),
78 ('author', None,
79 "print the author's name"),
80 ('author-email', None,
81 "print the author's email address"),
82 ('maintainer', None,
83 "print the maintainer's name"),
84 ('maintainer-email', None,
85 "print the maintainer's email address"),
86 ('contact', None,
Greg Wardd5d8a992000-05-23 01:42:17 +000087 "print the maintainer's name if known, else the author's"),
Greg Ward82715e12000-04-21 02:28:14 +000088 ('contact-email', None,
Greg Wardd5d8a992000-05-23 01:42:17 +000089 "print the maintainer's email address if known, else the author's"),
Greg Ward82715e12000-04-21 02:28:14 +000090 ('url', None,
91 "print the URL for this package"),
Greg Ward82715e12000-04-21 02:28:14 +000092 ('license', None,
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +000093 "print the license of the package"),
94 ('licence', None,
95 "alias for --license"),
Greg Ward82715e12000-04-21 02:28:14 +000096 ('description', None,
97 "print the package description"),
Greg Warde5a584e2000-04-26 02:26:55 +000098 ('long-description', None,
99 "print the long package description"),
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000100 ('platforms', None,
101 "print the list of platforms"),
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +0000102 ('classifiers', None,
103 "print the list of classifiers"),
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000104 ('keywords', None,
105 "print the list of keywords"),
Fred Drakedb7b0022005-03-20 22:19:47 +0000106 ('provides', None,
107 "print the list of packages/modules provided"),
108 ('requires', None,
109 "print the list of packages/modules required"),
110 ('obsoletes', None,
111 "print the list of packages/modules made obsolete")
Greg Ward82715e12000-04-21 02:28:14 +0000112 ]
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000113 display_option_names = [translate_longopt(x[0]) for x in display_options]
Greg Ward82715e12000-04-21 02:28:14 +0000114
115 # negative options are options that exclude other options
Greg Wardfe6462c2000-04-04 01:40:52 +0000116 negative_opt = {'quiet': 'verbose'}
117
118
119 # -- Creation/initialization methods -------------------------------
Fred Drakeb94b8492001-12-06 20:51:35 +0000120
Greg Wardfe6462c2000-04-04 01:40:52 +0000121 def __init__ (self, attrs=None):
122 """Construct a new Distribution instance: initialize all the
Greg Ward8ff5a3f2000-06-02 00:44:53 +0000123 attributes of a Distribution, and then use 'attrs' (a dictionary
124 mapping attribute names to values) to assign some of those
125 attributes their "real" values. (Any attributes not mentioned in
126 'attrs' will be assigned to some null value: 0, None, an empty list
127 or dictionary, etc.) Most importantly, initialize the
128 'command_obj' attribute to the empty dictionary; this will be
129 filled in with real command objects by 'parse_command_line()'.
130 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000131
132 # Default values for our command-line options
133 self.verbose = 1
134 self.dry_run = 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000135 self.help = 0
Greg Ward82715e12000-04-21 02:28:14 +0000136 for attr in self.display_option_names:
137 setattr(self, attr, 0)
Greg Wardfe6462c2000-04-04 01:40:52 +0000138
Greg Ward82715e12000-04-21 02:28:14 +0000139 # Store the distribution meta-data (name, version, author, and so
140 # forth) in a separate object -- we're getting to have enough
141 # information here (and enough command-line options) that it's
142 # worth it. Also delegate 'get_XXX()' methods to the 'metadata'
143 # object in a sneaky and underhanded (but efficient!) way.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000144 self.metadata = DistributionMetadata()
Neil Schemenauera8aefe52001-09-03 15:47:21 +0000145 for basename in self.metadata._METHOD_BASENAMES:
Greg Ward4982f982000-04-22 02:52:44 +0000146 method_name = "get_" + basename
147 setattr(self, method_name, getattr(self.metadata, method_name))
Greg Wardfe6462c2000-04-04 01:40:52 +0000148
149 # 'cmdclass' maps command names to class objects, so we
150 # can 1) quickly figure out which class to instantiate when
151 # we need to create a new command object, and 2) have a way
Greg Ward82715e12000-04-21 02:28:14 +0000152 # for the setup script to override command classes
Greg Wardfe6462c2000-04-04 01:40:52 +0000153 self.cmdclass = {}
154
Fred Draked04573f2004-08-03 16:37:40 +0000155 # 'command_packages' is a list of packages in which commands
156 # are searched for. The factory for command 'foo' is expected
157 # to be named 'foo' in the module 'foo' in one of the packages
158 # named here. This list is searched from the left; an error
159 # is raised if no named package provides the command being
160 # searched for. (Always access using get_command_packages().)
161 self.command_packages = None
162
Greg Ward9821bf42000-08-29 01:15:18 +0000163 # 'script_name' and 'script_args' are usually set to sys.argv[0]
164 # and sys.argv[1:], but they can be overridden when the caller is
165 # not necessarily a setup script run from the command-line.
166 self.script_name = None
167 self.script_args = None
168
Greg Wardd5d8a992000-05-23 01:42:17 +0000169 # 'command_options' is where we store command options between
170 # parsing them (from config files, the command-line, etc.) and when
171 # they are actually needed -- ie. when the command in question is
172 # instantiated. It is a dictionary of dictionaries of 2-tuples:
173 # command_options = { command_name : { option : (source, value) } }
Gregory P. Smith14263542000-05-12 00:41:33 +0000174 self.command_options = {}
175
Martin v. Löwis98da5622005-03-23 18:54:36 +0000176 # 'dist_files' is the list of (command, pyversion, file) that
177 # have been created by any dist commands run so far. This is
178 # filled regardless of whether the run is dry or not. pyversion
179 # gives sysconfig.get_python_version() if the dist file is
180 # specific to a Python version, 'any' if it is good for all
181 # Python versions on the target platform, and '' for a source
182 # file. pyversion should not be used to specify minimum or
183 # maximum required Python versions; use the metainfo for that
184 # instead.
Martin v. Löwis55f1bb82005-03-21 20:56:35 +0000185 self.dist_files = []
186
Greg Wardfe6462c2000-04-04 01:40:52 +0000187 # These options are really the business of various commands, rather
188 # than of the Distribution itself. We provide aliases for them in
189 # Distribution as a convenience to the developer.
Greg Wardfe6462c2000-04-04 01:40:52 +0000190 self.packages = None
Fred Drake0eb32a62004-06-11 21:50:33 +0000191 self.package_data = {}
Greg Wardfe6462c2000-04-04 01:40:52 +0000192 self.package_dir = None
193 self.py_modules = None
194 self.libraries = None
Greg Ward51def7d2000-05-27 01:36:14 +0000195 self.headers = None
Greg Wardfe6462c2000-04-04 01:40:52 +0000196 self.ext_modules = None
197 self.ext_package = None
198 self.include_dirs = None
199 self.extra_path = None
Gregory P. Smithb2e3bb32000-05-12 00:52:23 +0000200 self.scripts = None
Gregory P. Smith6a901dd2000-05-13 03:09:50 +0000201 self.data_files = None
Greg Wardfe6462c2000-04-04 01:40:52 +0000202
203 # And now initialize bookkeeping stuff that can't be supplied by
204 # the caller at all. 'command_obj' maps command names to
205 # Command instances -- that's how we enforce that every command
206 # class is a singleton.
207 self.command_obj = {}
208
209 # 'have_run' maps command names to boolean values; it keeps track
210 # of whether we have actually run a particular command, to make it
211 # cheap to "run" a command whenever we think we might need to -- if
212 # it's already been done, no need for expensive filesystem
213 # operations, we just check the 'have_run' dictionary and carry on.
214 # It's only safe to query 'have_run' for a command class that has
215 # been instantiated -- a false value will be inserted when the
216 # command object is created, and replaced with a true value when
Greg Ward612eb9f2000-07-27 02:13:20 +0000217 # the command is successfully run. Thus it's probably best to use
Greg Wardfe6462c2000-04-04 01:40:52 +0000218 # '.get()' rather than a straight lookup.
219 self.have_run = {}
220
221 # Now we'll use the attrs dictionary (ultimately, keyword args from
Greg Ward82715e12000-04-21 02:28:14 +0000222 # the setup script) to possibly override any or all of these
223 # distribution options.
224
Greg Wardfe6462c2000-04-04 01:40:52 +0000225 if attrs:
Greg Wardfe6462c2000-04-04 01:40:52 +0000226 # Pull out the set of command options and work on them
227 # specifically. Note that this order guarantees that aliased
228 # command options will override any supplied redundantly
229 # through the general options dictionary.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000230 options = attrs.get('options')
Greg Wardfe6462c2000-04-04 01:40:52 +0000231 if options:
232 del attrs['options']
233 for (command, cmd_options) in options.items():
Greg Ward0e48cfd2000-05-26 01:00:15 +0000234 opt_dict = self.get_option_dict(command)
235 for (opt, val) in cmd_options.items():
236 opt_dict[opt] = ("setup script", val)
Greg Wardfe6462c2000-04-04 01:40:52 +0000237
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000238 if 'licence' in attrs:
Andrew M. Kuchlinga52b8522003-03-03 20:07:27 +0000239 attrs['license'] = attrs['licence']
240 del attrs['licence']
241 msg = "'licence' distribution option is deprecated; use 'license'"
242 if warnings is not None:
243 warnings.warn(msg)
244 else:
245 sys.stderr.write(msg + "\n")
246
Greg Wardfe6462c2000-04-04 01:40:52 +0000247 # Now work on the rest of the attributes. Any attribute that's
248 # not already defined is invalid!
249 for (key,val) in attrs.items():
Fred Drakedb7b0022005-03-20 22:19:47 +0000250 if hasattr(self.metadata, "set_" + key):
251 getattr(self.metadata, "set_" + key)(val)
252 elif hasattr(self.metadata, key):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000253 setattr(self.metadata, key, val)
254 elif hasattr(self, key):
255 setattr(self, key, val)
Anthony Baxter73cc8472004-10-13 13:22:34 +0000256 else:
Andrew M. Kuchlingff4ad9a2002-10-31 13:22:41 +0000257 msg = "Unknown distribution option: %s" % repr(key)
258 if warnings is not None:
259 warnings.warn(msg)
260 else:
261 sys.stderr.write(msg + "\n")
Greg Wardfe6462c2000-04-04 01:40:52 +0000262
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000263 self.finalize_options()
Fred Drakeb94b8492001-12-06 20:51:35 +0000264
Greg Wardfe6462c2000-04-04 01:40:52 +0000265
Greg Ward0e48cfd2000-05-26 01:00:15 +0000266 def get_option_dict (self, command):
267 """Get the option dictionary for a given command. If that
268 command's option dictionary hasn't been created yet, then create it
269 and return the new dictionary; otherwise, return the existing
270 option dictionary.
271 """
272
273 dict = self.command_options.get(command)
274 if dict is None:
275 dict = self.command_options[command] = {}
276 return dict
277
278
Greg Wardc32d9a62000-05-28 23:53:06 +0000279 def dump_option_dicts (self, header=None, commands=None, indent=""):
280 from pprint import pformat
281
282 if commands is None: # dump all command option dicts
Guido van Rossumd4ee1672007-10-15 01:27:53 +0000283 commands = sorted(self.command_options.keys())
Greg Wardc32d9a62000-05-28 23:53:06 +0000284
285 if header is not None:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000286 print(indent + header)
Greg Wardc32d9a62000-05-28 23:53:06 +0000287 indent = indent + " "
288
289 if not commands:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000290 print(indent + "no commands known yet")
Greg Wardc32d9a62000-05-28 23:53:06 +0000291 return
292
293 for cmd_name in commands:
294 opt_dict = self.command_options.get(cmd_name)
295 if opt_dict is None:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000296 print(indent + "no option dict for '%s' command" % cmd_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000297 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000298 print(indent + "option dict for '%s' command:" % cmd_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000299 out = pformat(opt_dict)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000300 for line in out.split("\n"):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000301 print(indent + " " + line)
Greg Wardc32d9a62000-05-28 23:53:06 +0000302
Greg Wardc32d9a62000-05-28 23:53:06 +0000303
304
Greg Wardd5d8a992000-05-23 01:42:17 +0000305 # -- Config file finding/parsing methods ---------------------------
306
Gregory P. Smith14263542000-05-12 00:41:33 +0000307 def find_config_files (self):
308 """Find as many configuration files as should be processed for this
309 platform, and return a list of filenames in the order in which they
310 should be parsed. The filenames returned are guaranteed to exist
311 (modulo nasty race conditions).
312
Andrew M. Kuchlingd303b612001-12-06 16:32:05 +0000313 There are three possible config files: distutils.cfg in the
314 Distutils installation directory (ie. where the top-level
315 Distutils __inst__.py file lives), a file in the user's home
316 directory named .pydistutils.cfg on Unix and pydistutils.cfg
317 on Windows/Mac, and setup.cfg in the current directory.
Greg Wardd5d8a992000-05-23 01:42:17 +0000318 """
Gregory P. Smith14263542000-05-12 00:41:33 +0000319 files = []
Greg Wardacf3f6a2000-06-07 02:26:19 +0000320 check_environ()
Gregory P. Smith14263542000-05-12 00:41:33 +0000321
Greg Ward11696872000-06-07 02:29:03 +0000322 # Where to look for the system-wide Distutils config file
323 sys_dir = os.path.dirname(sys.modules['distutils'].__file__)
324
325 # Look for the system config file
326 sys_file = os.path.join(sys_dir, "distutils.cfg")
Greg Wardacf3f6a2000-06-07 02:26:19 +0000327 if os.path.isfile(sys_file):
328 files.append(sys_file)
Gregory P. Smith14263542000-05-12 00:41:33 +0000329
Greg Ward11696872000-06-07 02:29:03 +0000330 # What to call the per-user config file
331 if os.name == 'posix':
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000332 user_filename = ".pydistutils.cfg"
333 else:
334 user_filename = "pydistutils.cfg"
Greg Wardfa9ff762000-10-14 04:06:40 +0000335
Greg Ward11696872000-06-07 02:29:03 +0000336 # And look for the user config file
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000337 if 'HOME' in os.environ:
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000338 user_file = os.path.join(os.environ.get('HOME'), user_filename)
Gregory P. Smith14263542000-05-12 00:41:33 +0000339 if os.path.isfile(user_file):
340 files.append(user_file)
341
Gregory P. Smith14263542000-05-12 00:41:33 +0000342 # All platforms support local setup.cfg
343 local_file = "setup.cfg"
344 if os.path.isfile(local_file):
345 files.append(local_file)
346
347 return files
348
Gregory P. Smith14263542000-05-12 00:41:33 +0000349
350 def parse_config_files (self, filenames=None):
351
352 from ConfigParser import ConfigParser
353
354 if filenames is None:
355 filenames = self.find_config_files()
356
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000357 if DEBUG: print("Distribution.parse_config_files():")
Greg Ward47460772000-05-23 03:47:35 +0000358
Gregory P. Smith14263542000-05-12 00:41:33 +0000359 parser = ConfigParser()
Greg Wardd5d8a992000-05-23 01:42:17 +0000360 for filename in filenames:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000361 if DEBUG: print(" reading", filename)
Greg Wardd5d8a992000-05-23 01:42:17 +0000362 parser.read(filename)
363 for section in parser.sections():
364 options = parser.options(section)
Greg Ward0e48cfd2000-05-26 01:00:15 +0000365 opt_dict = self.get_option_dict(section)
Gregory P. Smith14263542000-05-12 00:41:33 +0000366
Greg Wardd5d8a992000-05-23 01:42:17 +0000367 for opt in options:
368 if opt != '__name__':
Greg Wardceb9e222000-09-25 01:23:52 +0000369 val = parser.get(section,opt)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000370 opt = opt.replace('-', '_')
Greg Wardceb9e222000-09-25 01:23:52 +0000371 opt_dict[opt] = (filename, val)
Gregory P. Smith14263542000-05-12 00:41:33 +0000372
Greg Ward47460772000-05-23 03:47:35 +0000373 # Make the ConfigParser forget everything (so we retain
Fred Drakef06116d2004-02-17 22:35:19 +0000374 # the original filenames that options come from)
Greg Ward47460772000-05-23 03:47:35 +0000375 parser.__init__()
Gregory P. Smith14263542000-05-12 00:41:33 +0000376
Greg Wardceb9e222000-09-25 01:23:52 +0000377 # If there was a "global" section in the config file, use it
378 # to set Distribution options.
379
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000380 if 'global' in self.command_options:
Greg Wardceb9e222000-09-25 01:23:52 +0000381 for (opt, (src, val)) in self.command_options['global'].items():
382 alias = self.negative_opt.get(opt)
383 try:
384 if alias:
385 setattr(self, alias, not strtobool(val))
386 elif opt in ('verbose', 'dry_run'): # ugh!
387 setattr(self, opt, strtobool(val))
Fred Draked04573f2004-08-03 16:37:40 +0000388 else:
389 setattr(self, opt, val)
Guido van Rossumb940e112007-01-10 16:19:56 +0000390 except ValueError as msg:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000391 raise DistutilsOptionError(msg)
Greg Wardceb9e222000-09-25 01:23:52 +0000392
Gregory P. Smith14263542000-05-12 00:41:33 +0000393
Greg Wardd5d8a992000-05-23 01:42:17 +0000394 # -- Command-line parsing methods ----------------------------------
395
Greg Ward9821bf42000-08-29 01:15:18 +0000396 def parse_command_line (self):
397 """Parse the setup script's command line, taken from the
398 'script_args' instance attribute (which defaults to 'sys.argv[1:]'
399 -- see 'setup()' in core.py). This list is first processed for
400 "global options" -- options that set attributes of the Distribution
401 instance. Then, it is alternately scanned for Distutils commands
402 and options for that command. Each new command terminates the
403 options for the previous command. The allowed options for a
404 command are determined by the 'user_options' attribute of the
405 command class -- thus, we have to be able to load command classes
406 in order to parse the command line. Any error in that 'options'
407 attribute raises DistutilsGetoptError; any error on the
408 command-line raises DistutilsArgError. If no Distutils commands
409 were found on the command line, raises DistutilsArgError. Return
Greg Wardceb9e222000-09-25 01:23:52 +0000410 true if command-line was successfully parsed and we should carry
Greg Ward9821bf42000-08-29 01:15:18 +0000411 on with executing commands; false if no errors but we shouldn't
412 execute commands (currently, this only happens if user asks for
413 help).
Greg Wardd5d8a992000-05-23 01:42:17 +0000414 """
Andrew M. Kuchling3f819ec2001-01-15 16:09:35 +0000415 #
Fred Drake981a1782001-08-10 18:59:30 +0000416 # We now have enough information to show the Macintosh dialog
417 # that allows the user to interactively specify the "command line".
Andrew M. Kuchling3f819ec2001-01-15 16:09:35 +0000418 #
Fred Draked04573f2004-08-03 16:37:40 +0000419 toplevel_options = self._get_toplevel_options()
Andrew M. Kuchling3f819ec2001-01-15 16:09:35 +0000420 if sys.platform == 'mac':
421 import EasyDialogs
422 cmdlist = self.get_command_list()
423 self.script_args = EasyDialogs.GetArgv(
Fred Draked04573f2004-08-03 16:37:40 +0000424 toplevel_options + self.display_options, cmdlist)
Fred Drakeb94b8492001-12-06 20:51:35 +0000425
Greg Wardfe6462c2000-04-04 01:40:52 +0000426 # We have to parse the command line a bit at a time -- global
427 # options, then the first command, then its options, and so on --
428 # because each command will be handled by a different class, and
Greg Wardd5d8a992000-05-23 01:42:17 +0000429 # the options that are valid for a particular class aren't known
430 # until we have loaded the command class, which doesn't happen
431 # until we know what the command is.
Greg Wardfe6462c2000-04-04 01:40:52 +0000432
433 self.commands = []
Fred Draked04573f2004-08-03 16:37:40 +0000434 parser = FancyGetopt(toplevel_options + self.display_options)
Greg Wardfd7b91e2000-09-26 01:52:25 +0000435 parser.set_negative_aliases(self.negative_opt)
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +0000436 parser.set_aliases({'licence': 'license'})
Greg Wardfd7b91e2000-09-26 01:52:25 +0000437 args = parser.getopt(args=self.script_args, object=self)
Greg Ward82715e12000-04-21 02:28:14 +0000438 option_order = parser.get_option_order()
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000439 log.set_verbosity(self.verbose)
Greg Wardfe6462c2000-04-04 01:40:52 +0000440
Greg Ward82715e12000-04-21 02:28:14 +0000441 # for display options we return immediately
442 if self.handle_display_options(option_order):
Greg Wardfe6462c2000-04-04 01:40:52 +0000443 return
Fred Drakeb94b8492001-12-06 20:51:35 +0000444
Greg Wardfe6462c2000-04-04 01:40:52 +0000445 while args:
Greg Wardd5d8a992000-05-23 01:42:17 +0000446 args = self._parse_command_opts(parser, args)
447 if args is None: # user asked for help (and got it)
Greg Wardfe6462c2000-04-04 01:40:52 +0000448 return
Greg Wardfe6462c2000-04-04 01:40:52 +0000449
Greg Wardd5d8a992000-05-23 01:42:17 +0000450 # Handle the cases of --help as a "global" option, ie.
451 # "setup.py --help" and "setup.py --help command ...". For the
452 # former, we show global options (--verbose, --dry-run, etc.)
453 # and display-only options (--name, --version, etc.); for the
454 # latter, we omit the display-only options and show help for
455 # each command listed on the command line.
Greg Wardfe6462c2000-04-04 01:40:52 +0000456 if self.help:
Greg Wardd5d8a992000-05-23 01:42:17 +0000457 self._show_help(parser,
458 display_options=len(self.commands) == 0,
459 commands=self.commands)
Greg Wardfe6462c2000-04-04 01:40:52 +0000460 return
461
462 # Oops, no commands found -- an end-user error
463 if not self.commands:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000464 raise DistutilsArgError("no commands supplied")
Greg Wardfe6462c2000-04-04 01:40:52 +0000465
466 # All is well: return true
Collin Winter5b7e9d72007-08-30 03:52:21 +0000467 return True
Greg Wardfe6462c2000-04-04 01:40:52 +0000468
Fred Draked04573f2004-08-03 16:37:40 +0000469 def _get_toplevel_options (self):
470 """Return the non-display options recognized at the top level.
471
472 This includes options that are recognized *only* at the top
473 level as well as options recognized for commands.
474 """
475 return self.global_options + [
476 ("command-packages=", None,
477 "list of packages that provide distutils commands"),
478 ]
479
Greg Wardd5d8a992000-05-23 01:42:17 +0000480 def _parse_command_opts (self, parser, args):
Greg Wardd5d8a992000-05-23 01:42:17 +0000481 """Parse the command-line options for a single command.
482 'parser' must be a FancyGetopt instance; 'args' must be the list
483 of arguments, starting with the current command (whose options
484 we are about to parse). Returns a new version of 'args' with
485 the next command at the front of the list; will be the empty
486 list if there are no more commands on the command line. Returns
487 None if the user asked for help on this command.
488 """
489 # late import because of mutual dependence between these modules
490 from distutils.cmd import Command
491
492 # Pull the current command from the head of the command line
493 command = args[0]
Greg Wardfd7b91e2000-09-26 01:52:25 +0000494 if not command_re.match(command):
Collin Winter5b7e9d72007-08-30 03:52:21 +0000495 raise SystemExit("invalid command name '%s'" % command)
Greg Wardfd7b91e2000-09-26 01:52:25 +0000496 self.commands.append(command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000497
498 # Dig up the command class that implements this command, so we
499 # 1) know that it's a valid command, and 2) know which options
500 # it takes.
501 try:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000502 cmd_class = self.get_command_class(command)
Guido van Rossumb940e112007-01-10 16:19:56 +0000503 except DistutilsModuleError as msg:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000504 raise DistutilsArgError(msg)
Greg Wardd5d8a992000-05-23 01:42:17 +0000505
506 # Require that the command class be derived from Command -- want
507 # to be sure that the basic "command" interface is implemented.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000508 if not issubclass(cmd_class, Command):
Collin Winter5b7e9d72007-08-30 03:52:21 +0000509 raise DistutilsClassError(
510 "command class %s must subclass Command" % cmd_class)
Greg Wardd5d8a992000-05-23 01:42:17 +0000511
512 # Also make sure that the command object provides a list of its
513 # known options.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000514 if not (hasattr(cmd_class, 'user_options') and
Guido van Rossum13257902007-06-07 23:15:56 +0000515 isinstance(cmd_class.user_options, list)):
Collin Winter5b7e9d72007-08-30 03:52:21 +0000516 raise DistutilsClassError(("command class %s must provide " +
Greg Wardd5d8a992000-05-23 01:42:17 +0000517 "'user_options' attribute (a list of tuples)") % \
Collin Winter5b7e9d72007-08-30 03:52:21 +0000518 cmd_class)
Greg Wardd5d8a992000-05-23 01:42:17 +0000519
520 # If the command class has a list of negative alias options,
521 # merge it in with the global negative aliases.
522 negative_opt = self.negative_opt
Greg Wardfd7b91e2000-09-26 01:52:25 +0000523 if hasattr(cmd_class, 'negative_opt'):
524 negative_opt = copy(negative_opt)
525 negative_opt.update(cmd_class.negative_opt)
Greg Wardd5d8a992000-05-23 01:42:17 +0000526
Greg Wardfa9ff762000-10-14 04:06:40 +0000527 # Check for help_options in command class. They have a different
528 # format (tuple of four) so we need to preprocess them here.
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000529 if (hasattr(cmd_class, 'help_options') and
Guido van Rossum13257902007-06-07 23:15:56 +0000530 isinstance(cmd_class.help_options, list)):
Greg Ward2ff78872000-06-24 00:23:20 +0000531 help_options = fix_help_options(cmd_class.help_options)
532 else:
Greg Ward55fced32000-06-24 01:22:41 +0000533 help_options = []
Greg Ward2ff78872000-06-24 00:23:20 +0000534
Greg Ward9d17a7a2000-06-07 03:00:06 +0000535
Greg Wardd5d8a992000-05-23 01:42:17 +0000536 # All commands support the global options too, just by adding
537 # in 'global_options'.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000538 parser.set_option_table(self.global_options +
539 cmd_class.user_options +
540 help_options)
541 parser.set_negative_aliases(negative_opt)
542 (args, opts) = parser.getopt(args[1:])
Greg Ward47460772000-05-23 03:47:35 +0000543 if hasattr(opts, 'help') and opts.help:
Greg Wardd5d8a992000-05-23 01:42:17 +0000544 self._show_help(parser, display_options=0, commands=[cmd_class])
545 return
546
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000547 if (hasattr(cmd_class, 'help_options') and
Guido van Rossum13257902007-06-07 23:15:56 +0000548 isinstance(cmd_class.help_options, list)):
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000549 help_option_found=0
550 for (help_option, short, desc, func) in cmd_class.help_options:
551 if hasattr(opts, parser.get_attr_name(help_option)):
552 help_option_found=1
Greg Wardfa9ff762000-10-14 04:06:40 +0000553 #print "showing help for option %s of command %s" % \
Greg Ward2ff78872000-06-24 00:23:20 +0000554 # (help_option[0],cmd_class)
Greg Ward55fced32000-06-24 01:22:41 +0000555
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000556 if hasattr(func, '__call__'):
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000557 func()
Greg Ward55fced32000-06-24 01:22:41 +0000558 else:
Fred Drake981a1782001-08-10 18:59:30 +0000559 raise DistutilsClassError(
Walter Dörwald70a6b492004-02-12 17:35:32 +0000560 "invalid help function %r for help option '%s': "
Fred Drake981a1782001-08-10 18:59:30 +0000561 "must be a callable object (function, etc.)"
Walter Dörwald70a6b492004-02-12 17:35:32 +0000562 % (func, help_option))
Greg Ward55fced32000-06-24 01:22:41 +0000563
Fred Drakeb94b8492001-12-06 20:51:35 +0000564 if help_option_found:
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000565 return
Greg Ward9d17a7a2000-06-07 03:00:06 +0000566
Greg Wardd5d8a992000-05-23 01:42:17 +0000567 # Put the options from the command-line into their official
568 # holding pen, the 'command_options' dictionary.
Greg Ward0e48cfd2000-05-26 01:00:15 +0000569 opt_dict = self.get_option_dict(command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000570 for (name, value) in vars(opts).items():
Greg Ward0e48cfd2000-05-26 01:00:15 +0000571 opt_dict[name] = ("command line", value)
Greg Wardd5d8a992000-05-23 01:42:17 +0000572
573 return args
574
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000575 def finalize_options (self):
576 """Set final values for all the options on the Distribution
577 instance, analogous to the .finalize_options() method of Command
578 objects.
579 """
580
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000581 keywords = self.metadata.keywords
582 if keywords is not None:
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000583 if isinstance(keywords, str):
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000584 keywordlist = keywords.split(',')
585 self.metadata.keywords = [x.strip() for x in keywordlist]
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000586
587 platforms = self.metadata.platforms
588 if platforms is not None:
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000589 if isinstance(platforms, str):
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000590 platformlist = platforms.split(',')
591 self.metadata.platforms = [x.strip() for x in platformlist]
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000592
Greg Wardd5d8a992000-05-23 01:42:17 +0000593 def _show_help (self,
594 parser,
595 global_options=1,
596 display_options=1,
597 commands=[]):
598 """Show help for the setup script command-line in the form of
599 several lists of command-line options. 'parser' should be a
600 FancyGetopt instance; do not expect it to be returned in the
601 same state, as its option table will be reset to make it
602 generate the correct help text.
603
604 If 'global_options' is true, lists the global options:
605 --verbose, --dry-run, etc. If 'display_options' is true, lists
606 the "display-only" options: --name, --version, etc. Finally,
607 lists per-command help for every command name or command class
608 in 'commands'.
609 """
610 # late import because of mutual dependence between these modules
Greg Ward9821bf42000-08-29 01:15:18 +0000611 from distutils.core import gen_usage
Greg Wardd5d8a992000-05-23 01:42:17 +0000612 from distutils.cmd import Command
613
614 if global_options:
Fred Draked04573f2004-08-03 16:37:40 +0000615 if display_options:
616 options = self._get_toplevel_options()
617 else:
618 options = self.global_options
619 parser.set_option_table(options)
Martin v. Löwis8ed338a2005-03-03 08:12:27 +0000620 parser.print_help(self.common_usage + "\nGlobal options:")
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000621 print()
Greg Wardd5d8a992000-05-23 01:42:17 +0000622
623 if display_options:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000624 parser.set_option_table(self.display_options)
625 parser.print_help(
Greg Wardd5d8a992000-05-23 01:42:17 +0000626 "Information display options (just display " +
627 "information, ignore any commands)")
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000628 print()
Greg Wardd5d8a992000-05-23 01:42:17 +0000629
630 for command in self.commands:
Guido van Rossum13257902007-06-07 23:15:56 +0000631 if isinstance(command, type) and issubclass(command, Command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000632 klass = command
633 else:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000634 klass = self.get_command_class(command)
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000635 if (hasattr(klass, 'help_options') and
Guido van Rossum13257902007-06-07 23:15:56 +0000636 isinstance(klass.help_options, list)):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000637 parser.set_option_table(klass.user_options +
638 fix_help_options(klass.help_options))
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000639 else:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000640 parser.set_option_table(klass.user_options)
641 parser.print_help("Options for '%s' command:" % klass.__name__)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000642 print()
Greg Wardd5d8a992000-05-23 01:42:17 +0000643
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000644 print(gen_usage(self.script_name))
Greg Wardd5d8a992000-05-23 01:42:17 +0000645 return
646
Greg Wardd5d8a992000-05-23 01:42:17 +0000647
Greg Ward82715e12000-04-21 02:28:14 +0000648 def handle_display_options (self, option_order):
649 """If there were any non-global "display-only" options
Greg Wardd5d8a992000-05-23 01:42:17 +0000650 (--help-commands or the metadata display options) on the command
651 line, display the requested info and return true; else return
652 false.
653 """
Greg Ward9821bf42000-08-29 01:15:18 +0000654 from distutils.core import gen_usage
Greg Ward82715e12000-04-21 02:28:14 +0000655
656 # User just wants a list of commands -- we'll print it out and stop
657 # processing now (ie. if they ran "setup --help-commands foo bar",
658 # we ignore "foo bar").
659 if self.help_commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000660 self.print_commands()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000661 print()
662 print(gen_usage(self.script_name))
Greg Ward82715e12000-04-21 02:28:14 +0000663 return 1
664
665 # If user supplied any of the "display metadata" options, then
666 # display that metadata in the order in which the user supplied the
667 # metadata options.
668 any_display_options = 0
669 is_display_option = {}
670 for option in self.display_options:
671 is_display_option[option[0]] = 1
672
673 for (opt, val) in option_order:
674 if val and is_display_option.get(opt):
Greg Ward2f2b6c62000-09-25 01:58:07 +0000675 opt = translate_longopt(opt)
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000676 value = getattr(self.metadata, "get_"+opt)()
677 if opt in ['keywords', 'platforms']:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000678 print(','.join(value))
Fred Drakedb7b0022005-03-20 22:19:47 +0000679 elif opt in ('classifiers', 'provides', 'requires',
680 'obsoletes'):
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000681 print('\n'.join(value))
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000682 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000683 print(value)
Greg Ward82715e12000-04-21 02:28:14 +0000684 any_display_options = 1
685
686 return any_display_options
687
Greg Wardfe6462c2000-04-04 01:40:52 +0000688 def print_command_list (self, commands, header, max_length):
689 """Print a subset of the list of all commands -- used by
Greg Wardd5d8a992000-05-23 01:42:17 +0000690 'print_commands()'.
691 """
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000692 print(header + ":")
Greg Wardfe6462c2000-04-04 01:40:52 +0000693
694 for cmd in commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000695 klass = self.cmdclass.get(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000696 if not klass:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000697 klass = self.get_command_class(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000698 try:
699 description = klass.description
700 except AttributeError:
701 description = "(no description available)"
702
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000703 print(" %-*s %s" % (max_length, cmd, description))
Greg Wardfe6462c2000-04-04 01:40:52 +0000704
Greg Wardfe6462c2000-04-04 01:40:52 +0000705
706 def print_commands (self):
Greg Wardd5d8a992000-05-23 01:42:17 +0000707 """Print out a help message listing all available commands with a
708 description of each. The list is divided into "standard commands"
709 (listed in distutils.command.__all__) and "extra commands"
710 (mentioned in self.cmdclass, but not a standard command). The
711 descriptions come from the command class attribute
712 'description'.
713 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000714 import distutils.command
715 std_commands = distutils.command.__all__
716 is_std = {}
717 for cmd in std_commands:
718 is_std[cmd] = 1
719
720 extra_commands = []
721 for cmd in self.cmdclass.keys():
722 if not is_std.get(cmd):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000723 extra_commands.append(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000724
725 max_length = 0
726 for cmd in (std_commands + extra_commands):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000727 if len(cmd) > max_length:
728 max_length = len(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000729
Greg Wardfd7b91e2000-09-26 01:52:25 +0000730 self.print_command_list(std_commands,
731 "Standard commands",
732 max_length)
Greg Wardfe6462c2000-04-04 01:40:52 +0000733 if extra_commands:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000734 print()
Greg Wardfd7b91e2000-09-26 01:52:25 +0000735 self.print_command_list(extra_commands,
736 "Extra commands",
737 max_length)
Greg Wardfe6462c2000-04-04 01:40:52 +0000738
Greg Wardf6fc8752000-11-11 02:47:11 +0000739 def get_command_list (self):
740 """Get a list of (command, description) tuples.
741 The list is divided into "standard commands" (listed in
742 distutils.command.__all__) and "extra commands" (mentioned in
743 self.cmdclass, but not a standard command). The descriptions come
744 from the command class attribute 'description'.
745 """
746 # Currently this is only used on Mac OS, for the Mac-only GUI
747 # Distutils interface (by Jack Jansen)
Greg Wardf6fc8752000-11-11 02:47:11 +0000748 import distutils.command
749 std_commands = distutils.command.__all__
750 is_std = {}
751 for cmd in std_commands:
752 is_std[cmd] = 1
753
754 extra_commands = []
755 for cmd in self.cmdclass.keys():
756 if not is_std.get(cmd):
757 extra_commands.append(cmd)
758
759 rv = []
760 for cmd in (std_commands + extra_commands):
761 klass = self.cmdclass.get(cmd)
762 if not klass:
763 klass = self.get_command_class(cmd)
764 try:
765 description = klass.description
766 except AttributeError:
767 description = "(no description available)"
768 rv.append((cmd, description))
769 return rv
Greg Wardfe6462c2000-04-04 01:40:52 +0000770
771 # -- Command class/object methods ----------------------------------
772
Fred Draked04573f2004-08-03 16:37:40 +0000773 def get_command_packages (self):
774 """Return a list of packages from which commands are loaded."""
775 pkgs = self.command_packages
776 if not isinstance(pkgs, type([])):
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000777 pkgs = (pkgs or "").split(",")
Fred Draked04573f2004-08-03 16:37:40 +0000778 for i in range(len(pkgs)):
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000779 pkgs[i] = pkgs[i].strip()
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000780 pkgs = [p for p in pkgs if p]
Fred Draked04573f2004-08-03 16:37:40 +0000781 if "distutils.command" not in pkgs:
782 pkgs.insert(0, "distutils.command")
783 self.command_packages = pkgs
784 return pkgs
785
Greg Wardd5d8a992000-05-23 01:42:17 +0000786 def get_command_class (self, command):
787 """Return the class that implements the Distutils command named by
788 'command'. First we check the 'cmdclass' dictionary; if the
789 command is mentioned there, we fetch the class object from the
790 dictionary and return it. Otherwise we load the command module
791 ("distutils.command." + command) and fetch the command class from
792 the module. The loaded class is also stored in 'cmdclass'
793 to speed future calls to 'get_command_class()'.
Greg Wardfe6462c2000-04-04 01:40:52 +0000794
Gregory P. Smith14263542000-05-12 00:41:33 +0000795 Raises DistutilsModuleError if the expected module could not be
Greg Wardd5d8a992000-05-23 01:42:17 +0000796 found, or if that module does not define the expected class.
797 """
798 klass = self.cmdclass.get(command)
799 if klass:
800 return klass
Greg Wardfe6462c2000-04-04 01:40:52 +0000801
Fred Draked04573f2004-08-03 16:37:40 +0000802 for pkgname in self.get_command_packages():
803 module_name = "%s.%s" % (pkgname, command)
804 klass_name = command
Greg Wardfe6462c2000-04-04 01:40:52 +0000805
Fred Draked04573f2004-08-03 16:37:40 +0000806 try:
807 __import__ (module_name)
808 module = sys.modules[module_name]
809 except ImportError:
810 continue
Greg Wardfe6462c2000-04-04 01:40:52 +0000811
Fred Draked04573f2004-08-03 16:37:40 +0000812 try:
813 klass = getattr(module, klass_name)
814 except AttributeError:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000815 raise DistutilsModuleError(
816 "invalid command '%s' (no class '%s' in module '%s')"
817 % (command, klass_name, module_name))
Greg Wardfe6462c2000-04-04 01:40:52 +0000818
Fred Draked04573f2004-08-03 16:37:40 +0000819 self.cmdclass[command] = klass
820 return klass
821
822 raise DistutilsModuleError("invalid command '%s'" % command)
823
Greg Wardd5d8a992000-05-23 01:42:17 +0000824 def get_command_obj (self, command, create=1):
825 """Return the command object for 'command'. Normally this object
Greg Ward612eb9f2000-07-27 02:13:20 +0000826 is cached on a previous call to 'get_command_obj()'; if no command
Greg Wardd5d8a992000-05-23 01:42:17 +0000827 object for 'command' is in the cache, then we either create and
828 return it (if 'create' is true) or return None.
829 """
830 cmd_obj = self.command_obj.get(command)
Greg Wardfe6462c2000-04-04 01:40:52 +0000831 if not cmd_obj and create:
Greg Ward2bd3f422000-06-02 01:59:33 +0000832 if DEBUG:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000833 print("Distribution.get_command_obj(): " \
834 "creating '%s' command object" % command)
Greg Ward47460772000-05-23 03:47:35 +0000835
Greg Wardd5d8a992000-05-23 01:42:17 +0000836 klass = self.get_command_class(command)
Greg Ward47460772000-05-23 03:47:35 +0000837 cmd_obj = self.command_obj[command] = klass(self)
838 self.have_run[command] = 0
839
840 # Set any options that were supplied in config files
841 # or on the command line. (NB. support for error
842 # reporting is lame here: any errors aren't reported
843 # until 'finalize_options()' is called, which means
844 # we won't report the source of the error.)
845 options = self.command_options.get(command)
846 if options:
Greg Wardc32d9a62000-05-28 23:53:06 +0000847 self._set_command_options(cmd_obj, options)
Greg Wardfe6462c2000-04-04 01:40:52 +0000848
849 return cmd_obj
850
Greg Wardc32d9a62000-05-28 23:53:06 +0000851 def _set_command_options (self, command_obj, option_dict=None):
Greg Wardc32d9a62000-05-28 23:53:06 +0000852 """Set the options for 'command_obj' from 'option_dict'. Basically
853 this means copying elements of a dictionary ('option_dict') to
854 attributes of an instance ('command').
855
Greg Wardceb9e222000-09-25 01:23:52 +0000856 'command_obj' must be a Command instance. If 'option_dict' is not
Greg Wardc32d9a62000-05-28 23:53:06 +0000857 supplied, uses the standard option dictionary for this command
858 (from 'self.command_options').
859 """
Greg Wardc32d9a62000-05-28 23:53:06 +0000860 command_name = command_obj.get_command_name()
861 if option_dict is None:
862 option_dict = self.get_option_dict(command_name)
863
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000864 if DEBUG: print(" setting options for '%s' command:" % command_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000865 for (option, (source, value)) in option_dict.items():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000866 if DEBUG: print(" %s = %s (from %s)" % (option, value, source))
Greg Wardceb9e222000-09-25 01:23:52 +0000867 try:
Greg Ward2f2b6c62000-09-25 01:58:07 +0000868 bool_opts = map(translate_longopt, command_obj.boolean_options)
Greg Wardceb9e222000-09-25 01:23:52 +0000869 except AttributeError:
870 bool_opts = []
871 try:
872 neg_opt = command_obj.negative_opt
873 except AttributeError:
874 neg_opt = {}
875
876 try:
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000877 is_string = isinstance(value, str)
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000878 if option in neg_opt and is_string:
Greg Wardceb9e222000-09-25 01:23:52 +0000879 setattr(command_obj, neg_opt[option], not strtobool(value))
Greg Ward2c08cf02000-09-27 00:15:37 +0000880 elif option in bool_opts and is_string:
Greg Wardceb9e222000-09-25 01:23:52 +0000881 setattr(command_obj, option, strtobool(value))
882 elif hasattr(command_obj, option):
883 setattr(command_obj, option, value)
884 else:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000885 raise DistutilsOptionError(
886 "error in %s: command '%s' has no such option '%s'"
887 % (source, command_name, option))
Guido van Rossumb940e112007-01-10 16:19:56 +0000888 except ValueError as msg:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000889 raise DistutilsOptionError(msg)
Greg Wardc32d9a62000-05-28 23:53:06 +0000890
Greg Wardf449ea52000-09-16 15:23:28 +0000891 def reinitialize_command (self, command, reinit_subcommands=0):
Greg Wardc32d9a62000-05-28 23:53:06 +0000892 """Reinitializes a command to the state it was in when first
893 returned by 'get_command_obj()': ie., initialized but not yet
Greg Ward7d9c7052000-06-28 01:25:27 +0000894 finalized. This provides the opportunity to sneak option
Greg Wardc32d9a62000-05-28 23:53:06 +0000895 values in programmatically, overriding or supplementing
896 user-supplied values from the config files and command line.
897 You'll have to re-finalize the command object (by calling
898 'finalize_options()' or 'ensure_finalized()') before using it for
Fred Drakeb94b8492001-12-06 20:51:35 +0000899 real.
Greg Wardc32d9a62000-05-28 23:53:06 +0000900
Greg Wardf449ea52000-09-16 15:23:28 +0000901 'command' should be a command name (string) or command object. If
902 'reinit_subcommands' is true, also reinitializes the command's
903 sub-commands, as declared by the 'sub_commands' class attribute (if
904 it has one). See the "install" command for an example. Only
905 reinitializes the sub-commands that actually matter, ie. those
906 whose test predicates return true.
907
Greg Wardc32d9a62000-05-28 23:53:06 +0000908 Returns the reinitialized command object.
909 """
910 from distutils.cmd import Command
911 if not isinstance(command, Command):
912 command_name = command
913 command = self.get_command_obj(command_name)
914 else:
915 command_name = command.get_command_name()
916
917 if not command.finalized:
Greg Ward282c7a02000-06-01 01:09:47 +0000918 return command
Greg Wardc32d9a62000-05-28 23:53:06 +0000919 command.initialize_options()
920 command.finalized = 0
Greg Ward43955c92000-06-06 02:52:36 +0000921 self.have_run[command_name] = 0
Greg Wardc32d9a62000-05-28 23:53:06 +0000922 self._set_command_options(command)
Greg Wardf449ea52000-09-16 15:23:28 +0000923
Greg Wardf449ea52000-09-16 15:23:28 +0000924 if reinit_subcommands:
Greg Wardf449ea52000-09-16 15:23:28 +0000925 for sub in command.get_sub_commands():
Fred Drakeb94b8492001-12-06 20:51:35 +0000926 self.reinitialize_command(sub, reinit_subcommands)
Greg Wardf449ea52000-09-16 15:23:28 +0000927
Greg Wardc32d9a62000-05-28 23:53:06 +0000928 return command
929
Fred Drakeb94b8492001-12-06 20:51:35 +0000930
Greg Wardfe6462c2000-04-04 01:40:52 +0000931 # -- Methods that operate on the Distribution ----------------------
932
933 def announce (self, msg, level=1):
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000934 log.debug(msg)
Greg Wardfe6462c2000-04-04 01:40:52 +0000935
936 def run_commands (self):
Greg Ward82715e12000-04-21 02:28:14 +0000937 """Run each command that was seen on the setup script command line.
Greg Wardd5d8a992000-05-23 01:42:17 +0000938 Uses the list of commands found and cache of command objects
Greg Wardfd7b91e2000-09-26 01:52:25 +0000939 created by 'get_command_obj()'.
940 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000941 for cmd in self.commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000942 self.run_command(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000943
944
Greg Wardfe6462c2000-04-04 01:40:52 +0000945 # -- Methods that operate on its Commands --------------------------
946
947 def run_command (self, command):
Greg Wardfe6462c2000-04-04 01:40:52 +0000948 """Do whatever it takes to run a command (including nothing at all,
Greg Wardd5d8a992000-05-23 01:42:17 +0000949 if the command has already been run). Specifically: if we have
950 already created and run the command named by 'command', return
951 silently without doing anything. If the command named by 'command'
952 doesn't even have a command object yet, create one. Then invoke
953 'run()' on that command object (or an existing one).
954 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000955 # Already been here, done that? then return silently.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000956 if self.have_run.get(command):
Greg Wardfe6462c2000-04-04 01:40:52 +0000957 return
958
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000959 log.info("running %s", command)
Greg Wardfd7b91e2000-09-26 01:52:25 +0000960 cmd_obj = self.get_command_obj(command)
961 cmd_obj.ensure_finalized()
962 cmd_obj.run()
Greg Wardfe6462c2000-04-04 01:40:52 +0000963 self.have_run[command] = 1
964
965
Greg Wardfe6462c2000-04-04 01:40:52 +0000966 # -- Distribution query methods ------------------------------------
967
968 def has_pure_modules (self):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000969 return len(self.packages or self.py_modules or []) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000970
971 def has_ext_modules (self):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000972 return self.ext_modules and len(self.ext_modules) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000973
974 def has_c_libraries (self):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000975 return self.libraries and len(self.libraries) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000976
977 def has_modules (self):
978 return self.has_pure_modules() or self.has_ext_modules()
979
Greg Ward51def7d2000-05-27 01:36:14 +0000980 def has_headers (self):
981 return self.headers and len(self.headers) > 0
982
Greg Ward44a61bb2000-05-20 15:06:48 +0000983 def has_scripts (self):
984 return self.scripts and len(self.scripts) > 0
985
986 def has_data_files (self):
987 return self.data_files and len(self.data_files) > 0
988
Greg Wardfe6462c2000-04-04 01:40:52 +0000989 def is_pure (self):
990 return (self.has_pure_modules() and
991 not self.has_ext_modules() and
992 not self.has_c_libraries())
993
Greg Ward82715e12000-04-21 02:28:14 +0000994 # -- Metadata query methods ----------------------------------------
995
996 # If you're looking for 'get_name()', 'get_version()', and so forth,
997 # they are defined in a sneaky way: the constructor binds self.get_XXX
998 # to self.metadata.get_XXX. The actual code is in the
999 # DistributionMetadata class, below.
1000
1001# class Distribution
1002
1003
1004class DistributionMetadata:
1005 """Dummy class to hold the distribution meta-data: name, version,
Greg Wardfd7b91e2000-09-26 01:52:25 +00001006 author, and so forth.
1007 """
Greg Ward82715e12000-04-21 02:28:14 +00001008
Neil Schemenauera8aefe52001-09-03 15:47:21 +00001009 _METHOD_BASENAMES = ("name", "version", "author", "author_email",
1010 "maintainer", "maintainer_email", "url",
1011 "license", "description", "long_description",
1012 "keywords", "platforms", "fullname", "contact",
Andrew M. Kuchlinga52b8522003-03-03 20:07:27 +00001013 "contact_email", "license", "classifiers",
Fred Drakedb7b0022005-03-20 22:19:47 +00001014 "download_url",
1015 # PEP 314
1016 "provides", "requires", "obsoletes",
1017 )
Neil Schemenauera8aefe52001-09-03 15:47:21 +00001018
Greg Ward82715e12000-04-21 02:28:14 +00001019 def __init__ (self):
1020 self.name = None
1021 self.version = None
1022 self.author = None
1023 self.author_email = None
1024 self.maintainer = None
1025 self.maintainer_email = None
1026 self.url = None
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +00001027 self.license = None
Greg Ward82715e12000-04-21 02:28:14 +00001028 self.description = None
Greg Warde5a584e2000-04-26 02:26:55 +00001029 self.long_description = None
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001030 self.keywords = None
1031 self.platforms = None
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +00001032 self.classifiers = None
Andrew M. Kuchling188d85f2003-02-19 14:16:01 +00001033 self.download_url = None
Fred Drakedb7b0022005-03-20 22:19:47 +00001034 # PEP 314
1035 self.provides = None
1036 self.requires = None
1037 self.obsoletes = None
Fred Drakeb94b8492001-12-06 20:51:35 +00001038
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001039 def write_pkg_info (self, base_dir):
1040 """Write the PKG-INFO file into the release tree.
1041 """
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001042 pkg_info = open( os.path.join(base_dir, 'PKG-INFO'), 'w')
1043
Fred Drakedb7b0022005-03-20 22:19:47 +00001044 self.write_pkg_file(pkg_info)
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +00001045
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001046 pkg_info.close()
Fred Drakeb94b8492001-12-06 20:51:35 +00001047
Fred Drakedb7b0022005-03-20 22:19:47 +00001048 def write_pkg_file (self, file):
1049 """Write the PKG-INFO format data to a file object.
1050 """
1051 version = '1.0'
1052 if self.provides or self.requires or self.obsoletes:
1053 version = '1.1'
1054
1055 file.write('Metadata-Version: %s\n' % version)
1056 file.write('Name: %s\n' % self.get_name() )
1057 file.write('Version: %s\n' % self.get_version() )
1058 file.write('Summary: %s\n' % self.get_description() )
1059 file.write('Home-page: %s\n' % self.get_url() )
1060 file.write('Author: %s\n' % self.get_contact() )
1061 file.write('Author-email: %s\n' % self.get_contact_email() )
1062 file.write('License: %s\n' % self.get_license() )
1063 if self.download_url:
1064 file.write('Download-URL: %s\n' % self.download_url)
1065
1066 long_desc = rfc822_escape( self.get_long_description() )
1067 file.write('Description: %s\n' % long_desc)
1068
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001069 keywords = ','.join(self.get_keywords())
Fred Drakedb7b0022005-03-20 22:19:47 +00001070 if keywords:
1071 file.write('Keywords: %s\n' % keywords )
1072
1073 self._write_list(file, 'Platform', self.get_platforms())
1074 self._write_list(file, 'Classifier', self.get_classifiers())
1075
1076 # PEP 314
1077 self._write_list(file, 'Requires', self.get_requires())
1078 self._write_list(file, 'Provides', self.get_provides())
1079 self._write_list(file, 'Obsoletes', self.get_obsoletes())
1080
1081 def _write_list (self, file, name, values):
1082 for value in values:
1083 file.write('%s: %s\n' % (name, value))
1084
Greg Ward82715e12000-04-21 02:28:14 +00001085 # -- Metadata query methods ----------------------------------------
1086
Greg Wardfe6462c2000-04-04 01:40:52 +00001087 def get_name (self):
1088 return self.name or "UNKNOWN"
1089
Greg Ward82715e12000-04-21 02:28:14 +00001090 def get_version(self):
Thomas Hellerbcd89752001-12-06 20:44:19 +00001091 return self.version or "0.0.0"
Greg Wardfe6462c2000-04-04 01:40:52 +00001092
Greg Ward82715e12000-04-21 02:28:14 +00001093 def get_fullname (self):
1094 return "%s-%s" % (self.get_name(), self.get_version())
1095
1096 def get_author(self):
1097 return self.author or "UNKNOWN"
1098
1099 def get_author_email(self):
1100 return self.author_email or "UNKNOWN"
1101
1102 def get_maintainer(self):
1103 return self.maintainer or "UNKNOWN"
1104
1105 def get_maintainer_email(self):
1106 return self.maintainer_email or "UNKNOWN"
1107
1108 def get_contact(self):
1109 return (self.maintainer or
1110 self.author or
1111 "UNKNOWN")
1112
1113 def get_contact_email(self):
1114 return (self.maintainer_email or
1115 self.author_email or
1116 "UNKNOWN")
1117
1118 def get_url(self):
1119 return self.url or "UNKNOWN"
1120
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +00001121 def get_license(self):
1122 return self.license or "UNKNOWN"
1123 get_licence = get_license
Fred Drakeb94b8492001-12-06 20:51:35 +00001124
Greg Ward82715e12000-04-21 02:28:14 +00001125 def get_description(self):
1126 return self.description or "UNKNOWN"
Greg Warde5a584e2000-04-26 02:26:55 +00001127
1128 def get_long_description(self):
1129 return self.long_description or "UNKNOWN"
1130
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001131 def get_keywords(self):
1132 return self.keywords or []
1133
1134 def get_platforms(self):
1135 return self.platforms or ["UNKNOWN"]
1136
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +00001137 def get_classifiers(self):
1138 return self.classifiers or []
1139
Andrew M. Kuchling188d85f2003-02-19 14:16:01 +00001140 def get_download_url(self):
1141 return self.download_url or "UNKNOWN"
1142
Fred Drakedb7b0022005-03-20 22:19:47 +00001143 # PEP 314
1144
1145 def get_requires(self):
1146 return self.requires or []
1147
1148 def set_requires(self, value):
1149 import distutils.versionpredicate
1150 for v in value:
1151 distutils.versionpredicate.VersionPredicate(v)
1152 self.requires = value
1153
1154 def get_provides(self):
1155 return self.provides or []
1156
1157 def set_provides(self, value):
1158 value = [v.strip() for v in value]
1159 for v in value:
1160 import distutils.versionpredicate
Fred Drake227e8ff2005-03-21 06:36:32 +00001161 distutils.versionpredicate.split_provision(v)
Fred Drakedb7b0022005-03-20 22:19:47 +00001162 self.provides = value
1163
1164 def get_obsoletes(self):
1165 return self.obsoletes or []
1166
1167 def set_obsoletes(self, value):
1168 import distutils.versionpredicate
1169 for v in value:
1170 distutils.versionpredicate.VersionPredicate(v)
1171 self.obsoletes = value
1172
Greg Ward2ff78872000-06-24 00:23:20 +00001173
1174def fix_help_options (options):
1175 """Convert a 4-tuple 'help_options' list as found in various command
1176 classes to the 3-tuple form required by FancyGetopt.
1177 """
1178 new_options = []
1179 for help_tuple in options:
1180 new_options.append(help_tuple[0:3])
1181 return new_options
1182
1183
Greg Wardfe6462c2000-04-04 01:40:52 +00001184if __name__ == "__main__":
Greg Wardfd7b91e2000-09-26 01:52:25 +00001185 dist = Distribution()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001186 print("ok")