blob: f20a92a21d631d0b339c65da08eca02963b413d9 [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
Tarek Ziadéc01cbc42009-06-01 22:22:13 +00009import sys, os, re
Tarek Ziadé4b7f9432009-12-08 09:39:51 +000010from email import message_from_file
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
Tarek Ziadé2b66da72009-12-21 01:22:46 +000017from distutils.errors import (DistutilsOptionError, DistutilsArgError,
18 DistutilsModuleError, DistutilsClassError)
Greg Ward2f2b6c62000-09-25 01:58:07 +000019from distutils.fancy_getopt import FancyGetopt, translate_longopt
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +000020from distutils.util import check_environ, strtobool, rfc822_escape
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000021from distutils import log
Jeremy Hyltonfcd73532002-09-11 16:31:53 +000022from distutils.debug import DEBUG
Greg Wardfe6462c2000-04-04 01:40:52 +000023
Marc-André Lemburgb339b2a2008-09-03 11:13:56 +000024# Encoding used for the PKG-INFO files
25PKG_INFO_ENCODING = 'utf-8'
26
Greg Wardfe6462c2000-04-04 01:40:52 +000027# Regex to define acceptable Distutils command names. This is not *quite*
28# the same as a Python NAME -- I don't allow leading underscores. The fact
29# that they're very similar is no coincidence; the default naming scheme is
30# to look for a Python module named after the command.
31command_re = re.compile (r'^[a-zA-Z]([a-zA-Z0-9_]*)$')
32
33
34class Distribution:
Greg Ward8ff5a3f2000-06-02 00:44:53 +000035 """The core of the Distutils. Most of the work hiding behind 'setup'
36 is really done within a Distribution instance, which farms the work out
37 to the Distutils commands specified on the command line.
Greg Wardfe6462c2000-04-04 01:40:52 +000038
Greg Ward8ff5a3f2000-06-02 00:44:53 +000039 Setup scripts will almost never instantiate Distribution directly,
40 unless the 'setup()' function is totally inadequate to their needs.
41 However, it is conceivable that a setup script might wish to subclass
42 Distribution for some specialized purpose, and then pass the subclass
43 to 'setup()' as the 'distclass' keyword argument. If so, it is
44 necessary to respect the expectations that 'setup' has of Distribution.
45 See the code for 'setup()', in core.py, for details.
46 """
Greg Wardfe6462c2000-04-04 01:40:52 +000047
48
49 # 'global_options' describes the command-line options that may be
Greg Ward82715e12000-04-21 02:28:14 +000050 # supplied to the setup script prior to any actual commands.
51 # Eg. "./setup.py -n" or "./setup.py --quiet" both take advantage of
Greg Wardfe6462c2000-04-04 01:40:52 +000052 # these global options. This list should be kept to a bare minimum,
53 # since every global option is also valid as a command option -- and we
54 # don't want to pollute the commands with too many options that they
55 # have minimal control over.
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000056 # The fourth entry for verbose means that it can be repeated.
57 global_options = [('verbose', 'v', "run verbosely (default)", 1),
Greg Wardd5d8a992000-05-23 01:42:17 +000058 ('quiet', 'q', "run quietly (turns verbosity off)"),
59 ('dry-run', 'n', "don't actually do anything"),
60 ('help', 'h', "show detailed help message"),
Tarek Ziadé40b998b2009-10-27 23:06:10 +000061 ('no-user-cfg', None,
62 'ignore pydistutils.cfg in your home directory'),
63 ]
Greg Ward82715e12000-04-21 02:28:14 +000064
Martin v. Löwis8ed338a2005-03-03 08:12:27 +000065 # 'common_usage' is a short (2-3 line) string describing the common
66 # usage of the setup script.
67 common_usage = """\
68Common commands: (see '--help-commands' for more)
69
70 setup.py build will build the package underneath 'build/'
71 setup.py install will install the package
72"""
73
Greg Ward82715e12000-04-21 02:28:14 +000074 # options that are not propagated to the commands
75 display_options = [
76 ('help-commands', None,
77 "list all available commands"),
78 ('name', None,
79 "print package name"),
80 ('version', 'V',
81 "print package version"),
82 ('fullname', None,
83 "print <package name>-<version>"),
84 ('author', None,
85 "print the author's name"),
86 ('author-email', None,
87 "print the author's email address"),
88 ('maintainer', None,
89 "print the maintainer's name"),
90 ('maintainer-email', None,
91 "print the maintainer's email address"),
92 ('contact', None,
Greg Wardd5d8a992000-05-23 01:42:17 +000093 "print the maintainer's name if known, else the author's"),
Greg Ward82715e12000-04-21 02:28:14 +000094 ('contact-email', None,
Greg Wardd5d8a992000-05-23 01:42:17 +000095 "print the maintainer's email address if known, else the author's"),
Greg Ward82715e12000-04-21 02:28:14 +000096 ('url', None,
97 "print the URL for this package"),
Greg Ward82715e12000-04-21 02:28:14 +000098 ('license', None,
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +000099 "print the license of the package"),
100 ('licence', None,
101 "alias for --license"),
Greg Ward82715e12000-04-21 02:28:14 +0000102 ('description', None,
103 "print the package description"),
Greg Warde5a584e2000-04-26 02:26:55 +0000104 ('long-description', None,
105 "print the long package description"),
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000106 ('platforms', None,
107 "print the list of platforms"),
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +0000108 ('classifiers', None,
109 "print the list of classifiers"),
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000110 ('keywords', None,
111 "print the list of keywords"),
Fred Drakedb7b0022005-03-20 22:19:47 +0000112 ('provides', None,
113 "print the list of packages/modules provided"),
114 ('requires', None,
115 "print the list of packages/modules required"),
116 ('obsoletes', None,
117 "print the list of packages/modules made obsolete")
Greg Ward82715e12000-04-21 02:28:14 +0000118 ]
Greg Ward2f2b6c62000-09-25 01:58:07 +0000119 display_option_names = map(lambda x: translate_longopt(x[0]),
120 display_options)
Greg Ward82715e12000-04-21 02:28:14 +0000121
122 # negative options are options that exclude other options
Greg Wardfe6462c2000-04-04 01:40:52 +0000123 negative_opt = {'quiet': 'verbose'}
124
125
126 # -- Creation/initialization methods -------------------------------
Fred Drakeb94b8492001-12-06 20:51:35 +0000127
Greg Wardfe6462c2000-04-04 01:40:52 +0000128 def __init__ (self, attrs=None):
129 """Construct a new Distribution instance: initialize all the
Greg Ward8ff5a3f2000-06-02 00:44:53 +0000130 attributes of a Distribution, and then use 'attrs' (a dictionary
131 mapping attribute names to values) to assign some of those
132 attributes their "real" values. (Any attributes not mentioned in
133 'attrs' will be assigned to some null value: 0, None, an empty list
134 or dictionary, etc.) Most importantly, initialize the
135 'command_obj' attribute to the empty dictionary; this will be
136 filled in with real command objects by 'parse_command_line()'.
137 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000138
139 # Default values for our command-line options
140 self.verbose = 1
141 self.dry_run = 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000142 self.help = 0
Greg Ward82715e12000-04-21 02:28:14 +0000143 for attr in self.display_option_names:
144 setattr(self, attr, 0)
Greg Wardfe6462c2000-04-04 01:40:52 +0000145
Greg Ward82715e12000-04-21 02:28:14 +0000146 # Store the distribution meta-data (name, version, author, and so
147 # forth) in a separate object -- we're getting to have enough
148 # information here (and enough command-line options) that it's
149 # worth it. Also delegate 'get_XXX()' methods to the 'metadata'
150 # object in a sneaky and underhanded (but efficient!) way.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000151 self.metadata = DistributionMetadata()
Neil Schemenauera8aefe52001-09-03 15:47:21 +0000152 for basename in self.metadata._METHOD_BASENAMES:
Greg Ward4982f982000-04-22 02:52:44 +0000153 method_name = "get_" + basename
154 setattr(self, method_name, getattr(self.metadata, method_name))
Greg Wardfe6462c2000-04-04 01:40:52 +0000155
156 # 'cmdclass' maps command names to class objects, so we
157 # can 1) quickly figure out which class to instantiate when
158 # we need to create a new command object, and 2) have a way
Greg Ward82715e12000-04-21 02:28:14 +0000159 # for the setup script to override command classes
Greg Wardfe6462c2000-04-04 01:40:52 +0000160 self.cmdclass = {}
161
Fred Draked04573f2004-08-03 16:37:40 +0000162 # 'command_packages' is a list of packages in which commands
163 # are searched for. The factory for command 'foo' is expected
164 # to be named 'foo' in the module 'foo' in one of the packages
165 # named here. This list is searched from the left; an error
166 # is raised if no named package provides the command being
167 # searched for. (Always access using get_command_packages().)
168 self.command_packages = None
169
Greg Ward9821bf42000-08-29 01:15:18 +0000170 # 'script_name' and 'script_args' are usually set to sys.argv[0]
171 # and sys.argv[1:], but they can be overridden when the caller is
172 # not necessarily a setup script run from the command-line.
173 self.script_name = None
174 self.script_args = None
175
Greg Wardd5d8a992000-05-23 01:42:17 +0000176 # 'command_options' is where we store command options between
177 # parsing them (from config files, the command-line, etc.) and when
178 # they are actually needed -- ie. when the command in question is
179 # instantiated. It is a dictionary of dictionaries of 2-tuples:
180 # command_options = { command_name : { option : (source, value) } }
Gregory P. Smith14263542000-05-12 00:41:33 +0000181 self.command_options = {}
182
Martin v. Löwis98da5622005-03-23 18:54:36 +0000183 # 'dist_files' is the list of (command, pyversion, file) that
184 # have been created by any dist commands run so far. This is
185 # filled regardless of whether the run is dry or not. pyversion
186 # gives sysconfig.get_python_version() if the dist file is
187 # specific to a Python version, 'any' if it is good for all
188 # Python versions on the target platform, and '' for a source
189 # file. pyversion should not be used to specify minimum or
190 # maximum required Python versions; use the metainfo for that
191 # instead.
Martin v. Löwis55f1bb82005-03-21 20:56:35 +0000192 self.dist_files = []
193
Greg Wardfe6462c2000-04-04 01:40:52 +0000194 # These options are really the business of various commands, rather
195 # than of the Distribution itself. We provide aliases for them in
196 # Distribution as a convenience to the developer.
Greg Wardfe6462c2000-04-04 01:40:52 +0000197 self.packages = None
Fred Drake0eb32a62004-06-11 21:50:33 +0000198 self.package_data = {}
Greg Wardfe6462c2000-04-04 01:40:52 +0000199 self.package_dir = None
200 self.py_modules = None
201 self.libraries = None
Greg Ward51def7d2000-05-27 01:36:14 +0000202 self.headers = None
Greg Wardfe6462c2000-04-04 01:40:52 +0000203 self.ext_modules = None
204 self.ext_package = None
205 self.include_dirs = None
206 self.extra_path = None
Gregory P. Smithb2e3bb32000-05-12 00:52:23 +0000207 self.scripts = None
Gregory P. Smith6a901dd2000-05-13 03:09:50 +0000208 self.data_files = None
Tarek Ziadé1a240fb2009-01-08 23:56:31 +0000209 self.password = ''
Greg Wardfe6462c2000-04-04 01:40:52 +0000210
211 # And now initialize bookkeeping stuff that can't be supplied by
212 # the caller at all. 'command_obj' maps command names to
213 # Command instances -- that's how we enforce that every command
214 # class is a singleton.
215 self.command_obj = {}
216
217 # 'have_run' maps command names to boolean values; it keeps track
218 # of whether we have actually run a particular command, to make it
219 # cheap to "run" a command whenever we think we might need to -- if
220 # it's already been done, no need for expensive filesystem
221 # operations, we just check the 'have_run' dictionary and carry on.
222 # It's only safe to query 'have_run' for a command class that has
223 # been instantiated -- a false value will be inserted when the
224 # command object is created, and replaced with a true value when
Greg Ward612eb9f2000-07-27 02:13:20 +0000225 # the command is successfully run. Thus it's probably best to use
Greg Wardfe6462c2000-04-04 01:40:52 +0000226 # '.get()' rather than a straight lookup.
227 self.have_run = {}
228
229 # Now we'll use the attrs dictionary (ultimately, keyword args from
Greg Ward82715e12000-04-21 02:28:14 +0000230 # the setup script) to possibly override any or all of these
231 # distribution options.
232
Greg Wardfe6462c2000-04-04 01:40:52 +0000233 if attrs:
Greg Wardfe6462c2000-04-04 01:40:52 +0000234 # Pull out the set of command options and work on them
235 # specifically. Note that this order guarantees that aliased
236 # command options will override any supplied redundantly
237 # through the general options dictionary.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000238 options = attrs.get('options')
Tarek Ziadéc13acb12008-12-29 22:23:53 +0000239 if options is not None:
Greg Wardfe6462c2000-04-04 01:40:52 +0000240 del attrs['options']
241 for (command, cmd_options) in options.items():
Greg Ward0e48cfd2000-05-26 01:00:15 +0000242 opt_dict = self.get_option_dict(command)
243 for (opt, val) in cmd_options.items():
244 opt_dict[opt] = ("setup script", val)
Greg Wardfe6462c2000-04-04 01:40:52 +0000245
Guido van Rossum8bc09652008-02-21 18:18:37 +0000246 if 'licence' in attrs:
Andrew M. Kuchlinga52b8522003-03-03 20:07:27 +0000247 attrs['license'] = attrs['licence']
248 del attrs['licence']
249 msg = "'licence' distribution option is deprecated; use 'license'"
250 if warnings is not None:
251 warnings.warn(msg)
252 else:
253 sys.stderr.write(msg + "\n")
254
Greg Wardfe6462c2000-04-04 01:40:52 +0000255 # Now work on the rest of the attributes. Any attribute that's
256 # not already defined is invalid!
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000257 for (key, val) in attrs.items():
Fred Drakedb7b0022005-03-20 22:19:47 +0000258 if hasattr(self.metadata, "set_" + key):
259 getattr(self.metadata, "set_" + key)(val)
260 elif hasattr(self.metadata, key):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000261 setattr(self.metadata, key, val)
262 elif hasattr(self, key):
263 setattr(self, key, val)
Anthony Baxter73cc8472004-10-13 13:22:34 +0000264 else:
Andrew M. Kuchlingff4ad9a2002-10-31 13:22:41 +0000265 msg = "Unknown distribution option: %s" % repr(key)
266 if warnings is not None:
267 warnings.warn(msg)
268 else:
269 sys.stderr.write(msg + "\n")
Greg Wardfe6462c2000-04-04 01:40:52 +0000270
Tarek Ziadé40b998b2009-10-27 23:06:10 +0000271 # no-user-cfg is handled before other command line args
272 # because other args override the config files, and this
273 # one is needed before we can load the config files.
274 # If attrs['script_args'] wasn't passed, assume false.
275 #
276 # This also make sure we just look at the global options
277 self.want_user_cfg = True
278
279 if self.script_args is not None:
280 for arg in self.script_args:
281 if not arg.startswith('-'):
282 break
283 if arg == '--no-user-cfg':
284 self.want_user_cfg = False
285 break
286
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000287 self.finalize_options()
Fred Drakeb94b8492001-12-06 20:51:35 +0000288
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000289 def get_option_dict(self, command):
Greg Ward0e48cfd2000-05-26 01:00:15 +0000290 """Get the option dictionary for a given command. If that
291 command's option dictionary hasn't been created yet, then create it
292 and return the new dictionary; otherwise, return the existing
293 option dictionary.
294 """
Greg Ward0e48cfd2000-05-26 01:00:15 +0000295 dict = self.command_options.get(command)
296 if dict is None:
297 dict = self.command_options[command] = {}
298 return dict
299
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000300 def dump_option_dicts(self, header=None, commands=None, indent=""):
Greg Wardc32d9a62000-05-28 23:53:06 +0000301 from pprint import pformat
302
303 if commands is None: # dump all command option dicts
304 commands = self.command_options.keys()
305 commands.sort()
306
307 if header is not None:
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000308 self.announce(indent + header)
Greg Wardc32d9a62000-05-28 23:53:06 +0000309 indent = indent + " "
310
311 if not commands:
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000312 self.announce(indent + "no commands known yet")
Greg Wardc32d9a62000-05-28 23:53:06 +0000313 return
314
315 for cmd_name in commands:
316 opt_dict = self.command_options.get(cmd_name)
317 if opt_dict is None:
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000318 self.announce(indent +
319 "no option dict for '%s' command" % cmd_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000320 else:
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000321 self.announce(indent +
322 "option dict for '%s' command:" % cmd_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000323 out = pformat(opt_dict)
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000324 for line in out.split('\n'):
325 self.announce(indent + " " + line)
Greg Wardc32d9a62000-05-28 23:53:06 +0000326
Greg Wardd5d8a992000-05-23 01:42:17 +0000327 # -- Config file finding/parsing methods ---------------------------
328
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000329 def find_config_files(self):
Gregory P. Smith14263542000-05-12 00:41:33 +0000330 """Find as many configuration files as should be processed for this
331 platform, and return a list of filenames in the order in which they
332 should be parsed. The filenames returned are guaranteed to exist
333 (modulo nasty race conditions).
334
Andrew M. Kuchlingd303b612001-12-06 16:32:05 +0000335 There are three possible config files: distutils.cfg in the
336 Distutils installation directory (ie. where the top-level
337 Distutils __inst__.py file lives), a file in the user's home
338 directory named .pydistutils.cfg on Unix and pydistutils.cfg
Tarek Ziadé40b998b2009-10-27 23:06:10 +0000339 on Windows/Mac; and setup.cfg in the current directory.
340
341 The file in the user's home directory can be disabled with the
342 --no-user-cfg option.
Greg Wardd5d8a992000-05-23 01:42:17 +0000343 """
Gregory P. Smith14263542000-05-12 00:41:33 +0000344 files = []
Greg Wardacf3f6a2000-06-07 02:26:19 +0000345 check_environ()
Gregory P. Smith14263542000-05-12 00:41:33 +0000346
Greg Ward11696872000-06-07 02:29:03 +0000347 # Where to look for the system-wide Distutils config file
348 sys_dir = os.path.dirname(sys.modules['distutils'].__file__)
349
350 # Look for the system config file
351 sys_file = os.path.join(sys_dir, "distutils.cfg")
Greg Wardacf3f6a2000-06-07 02:26:19 +0000352 if os.path.isfile(sys_file):
353 files.append(sys_file)
Gregory P. Smith14263542000-05-12 00:41:33 +0000354
Greg Ward11696872000-06-07 02:29:03 +0000355 # What to call the per-user config file
356 if os.name == 'posix':
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000357 user_filename = ".pydistutils.cfg"
358 else:
359 user_filename = "pydistutils.cfg"
Greg Wardfa9ff762000-10-14 04:06:40 +0000360
Greg Ward11696872000-06-07 02:29:03 +0000361 # And look for the user config file
Tarek Ziadé40b998b2009-10-27 23:06:10 +0000362 if self.want_user_cfg:
363 user_file = os.path.join(os.path.expanduser('~'), user_filename)
364 if os.path.isfile(user_file):
365 files.append(user_file)
Gregory P. Smith14263542000-05-12 00:41:33 +0000366
Gregory P. Smith14263542000-05-12 00:41:33 +0000367 # All platforms support local setup.cfg
368 local_file = "setup.cfg"
369 if os.path.isfile(local_file):
370 files.append(local_file)
371
Tarek Ziadé40b998b2009-10-27 23:06:10 +0000372 if DEBUG:
373 self.announce("using config files: %s" % ', '.join(files))
374
Gregory P. Smith14263542000-05-12 00:41:33 +0000375 return files
376
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000377 def parse_config_files(self, filenames=None):
Georg Brandl392c6fc2008-05-25 07:25:25 +0000378 from ConfigParser import ConfigParser
Gregory P. Smith14263542000-05-12 00:41:33 +0000379
380 if filenames is None:
381 filenames = self.find_config_files()
382
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000383 if DEBUG:
384 self.announce("Distribution.parse_config_files():")
Greg Ward47460772000-05-23 03:47:35 +0000385
Gregory P. Smith14263542000-05-12 00:41:33 +0000386 parser = ConfigParser()
Greg Wardd5d8a992000-05-23 01:42:17 +0000387 for filename in filenames:
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000388 if DEBUG:
Tarek Ziadé99773352009-09-21 13:41:08 +0000389 self.announce(" reading %s" % filename)
Greg Wardd5d8a992000-05-23 01:42:17 +0000390 parser.read(filename)
391 for section in parser.sections():
392 options = parser.options(section)
Greg Ward0e48cfd2000-05-26 01:00:15 +0000393 opt_dict = self.get_option_dict(section)
Gregory P. Smith14263542000-05-12 00:41:33 +0000394
Greg Wardd5d8a992000-05-23 01:42:17 +0000395 for opt in options:
396 if opt != '__name__':
Greg Wardceb9e222000-09-25 01:23:52 +0000397 val = parser.get(section,opt)
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000398 opt = opt.replace('-', '_')
Greg Wardceb9e222000-09-25 01:23:52 +0000399 opt_dict[opt] = (filename, val)
Gregory P. Smith14263542000-05-12 00:41:33 +0000400
Greg Ward47460772000-05-23 03:47:35 +0000401 # Make the ConfigParser forget everything (so we retain
Fred Drakef06116d2004-02-17 22:35:19 +0000402 # the original filenames that options come from)
Greg Ward47460772000-05-23 03:47:35 +0000403 parser.__init__()
Gregory P. Smith14263542000-05-12 00:41:33 +0000404
Greg Wardceb9e222000-09-25 01:23:52 +0000405 # If there was a "global" section in the config file, use it
406 # to set Distribution options.
407
Guido van Rossum8bc09652008-02-21 18:18:37 +0000408 if 'global' in self.command_options:
Greg Wardceb9e222000-09-25 01:23:52 +0000409 for (opt, (src, val)) in self.command_options['global'].items():
410 alias = self.negative_opt.get(opt)
411 try:
412 if alias:
413 setattr(self, alias, not strtobool(val))
414 elif opt in ('verbose', 'dry_run'): # ugh!
415 setattr(self, opt, strtobool(val))
Fred Draked04573f2004-08-03 16:37:40 +0000416 else:
417 setattr(self, opt, val)
Greg Wardceb9e222000-09-25 01:23:52 +0000418 except ValueError, msg:
419 raise DistutilsOptionError, msg
420
Greg Wardd5d8a992000-05-23 01:42:17 +0000421 # -- Command-line parsing methods ----------------------------------
422
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000423 def parse_command_line(self):
Greg Ward9821bf42000-08-29 01:15:18 +0000424 """Parse the setup script's command line, taken from the
425 'script_args' instance attribute (which defaults to 'sys.argv[1:]'
426 -- see 'setup()' in core.py). This list is first processed for
427 "global options" -- options that set attributes of the Distribution
428 instance. Then, it is alternately scanned for Distutils commands
429 and options for that command. Each new command terminates the
430 options for the previous command. The allowed options for a
431 command are determined by the 'user_options' attribute of the
432 command class -- thus, we have to be able to load command classes
433 in order to parse the command line. Any error in that 'options'
434 attribute raises DistutilsGetoptError; any error on the
435 command-line raises DistutilsArgError. If no Distutils commands
436 were found on the command line, raises DistutilsArgError. Return
Greg Wardceb9e222000-09-25 01:23:52 +0000437 true if command-line was successfully parsed and we should carry
Greg Ward9821bf42000-08-29 01:15:18 +0000438 on with executing commands; false if no errors but we shouldn't
439 execute commands (currently, this only happens if user asks for
440 help).
Greg Wardd5d8a992000-05-23 01:42:17 +0000441 """
Andrew M. Kuchling3f819ec2001-01-15 16:09:35 +0000442 #
Fred Drake981a1782001-08-10 18:59:30 +0000443 # We now have enough information to show the Macintosh dialog
444 # that allows the user to interactively specify the "command line".
Andrew M. Kuchling3f819ec2001-01-15 16:09:35 +0000445 #
Fred Draked04573f2004-08-03 16:37:40 +0000446 toplevel_options = self._get_toplevel_options()
Fred Drakeb94b8492001-12-06 20:51:35 +0000447
Greg Wardfe6462c2000-04-04 01:40:52 +0000448 # We have to parse the command line a bit at a time -- global
449 # options, then the first command, then its options, and so on --
450 # because each command will be handled by a different class, and
Greg Wardd5d8a992000-05-23 01:42:17 +0000451 # the options that are valid for a particular class aren't known
452 # until we have loaded the command class, which doesn't happen
453 # until we know what the command is.
Greg Wardfe6462c2000-04-04 01:40:52 +0000454
455 self.commands = []
Fred Draked04573f2004-08-03 16:37:40 +0000456 parser = FancyGetopt(toplevel_options + self.display_options)
Greg Wardfd7b91e2000-09-26 01:52:25 +0000457 parser.set_negative_aliases(self.negative_opt)
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +0000458 parser.set_aliases({'licence': 'license'})
Greg Wardfd7b91e2000-09-26 01:52:25 +0000459 args = parser.getopt(args=self.script_args, object=self)
Greg Ward82715e12000-04-21 02:28:14 +0000460 option_order = parser.get_option_order()
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000461 log.set_verbosity(self.verbose)
Greg Wardfe6462c2000-04-04 01:40:52 +0000462
Greg Ward82715e12000-04-21 02:28:14 +0000463 # for display options we return immediately
464 if self.handle_display_options(option_order):
Greg Wardfe6462c2000-04-04 01:40:52 +0000465 return
Greg Wardfe6462c2000-04-04 01:40:52 +0000466 while args:
Greg Wardd5d8a992000-05-23 01:42:17 +0000467 args = self._parse_command_opts(parser, args)
468 if args is None: # user asked for help (and got it)
Greg Wardfe6462c2000-04-04 01:40:52 +0000469 return
Greg Wardfe6462c2000-04-04 01:40:52 +0000470
Greg Wardd5d8a992000-05-23 01:42:17 +0000471 # Handle the cases of --help as a "global" option, ie.
472 # "setup.py --help" and "setup.py --help command ...". For the
473 # former, we show global options (--verbose, --dry-run, etc.)
474 # and display-only options (--name, --version, etc.); for the
475 # latter, we omit the display-only options and show help for
476 # each command listed on the command line.
Greg Wardfe6462c2000-04-04 01:40:52 +0000477 if self.help:
Greg Wardd5d8a992000-05-23 01:42:17 +0000478 self._show_help(parser,
479 display_options=len(self.commands) == 0,
480 commands=self.commands)
Greg Wardfe6462c2000-04-04 01:40:52 +0000481 return
482
483 # Oops, no commands found -- an end-user error
484 if not self.commands:
485 raise DistutilsArgError, "no commands supplied"
486
487 # All is well: return true
488 return 1
489
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000490 def _get_toplevel_options(self):
Fred Draked04573f2004-08-03 16:37:40 +0000491 """Return the non-display options recognized at the top level.
492
493 This includes options that are recognized *only* at the top
494 level as well as options recognized for commands.
495 """
496 return self.global_options + [
497 ("command-packages=", None,
498 "list of packages that provide distutils commands"),
499 ]
500
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000501 def _parse_command_opts(self, parser, args):
Greg Wardd5d8a992000-05-23 01:42:17 +0000502 """Parse the command-line options for a single command.
503 'parser' must be a FancyGetopt instance; 'args' must be the list
504 of arguments, starting with the current command (whose options
505 we are about to parse). Returns a new version of 'args' with
506 the next command at the front of the list; will be the empty
507 list if there are no more commands on the command line. Returns
508 None if the user asked for help on this command.
509 """
510 # late import because of mutual dependence between these modules
511 from distutils.cmd import Command
512
513 # Pull the current command from the head of the command line
514 command = args[0]
Greg Wardfd7b91e2000-09-26 01:52:25 +0000515 if not command_re.match(command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000516 raise SystemExit, "invalid command name '%s'" % command
Greg Wardfd7b91e2000-09-26 01:52:25 +0000517 self.commands.append(command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000518
519 # Dig up the command class that implements this command, so we
520 # 1) know that it's a valid command, and 2) know which options
521 # it takes.
522 try:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000523 cmd_class = self.get_command_class(command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000524 except DistutilsModuleError, msg:
525 raise DistutilsArgError, msg
526
527 # Require that the command class be derived from Command -- want
528 # to be sure that the basic "command" interface is implemented.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000529 if not issubclass(cmd_class, Command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000530 raise DistutilsClassError, \
531 "command class %s must subclass Command" % cmd_class
532
533 # Also make sure that the command object provides a list of its
534 # known options.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000535 if not (hasattr(cmd_class, 'user_options') and
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000536 isinstance(cmd_class.user_options, list)):
Greg Wardd5d8a992000-05-23 01:42:17 +0000537 raise DistutilsClassError, \
538 ("command class %s must provide " +
539 "'user_options' attribute (a list of tuples)") % \
540 cmd_class
541
542 # If the command class has a list of negative alias options,
543 # merge it in with the global negative aliases.
544 negative_opt = self.negative_opt
Greg Wardfd7b91e2000-09-26 01:52:25 +0000545 if hasattr(cmd_class, 'negative_opt'):
Antoine Pitrouf5413782009-05-15 17:27:30 +0000546 negative_opt = negative_opt.copy()
Greg Wardfd7b91e2000-09-26 01:52:25 +0000547 negative_opt.update(cmd_class.negative_opt)
Greg Wardd5d8a992000-05-23 01:42:17 +0000548
Greg Wardfa9ff762000-10-14 04:06:40 +0000549 # Check for help_options in command class. They have a different
550 # format (tuple of four) so we need to preprocess them here.
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000551 if (hasattr(cmd_class, 'help_options') and
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000552 isinstance(cmd_class.help_options, list)):
Greg Ward2ff78872000-06-24 00:23:20 +0000553 help_options = fix_help_options(cmd_class.help_options)
554 else:
Greg Ward55fced32000-06-24 01:22:41 +0000555 help_options = []
Greg Ward2ff78872000-06-24 00:23:20 +0000556
Greg Ward9d17a7a2000-06-07 03:00:06 +0000557
Greg Wardd5d8a992000-05-23 01:42:17 +0000558 # All commands support the global options too, just by adding
559 # in 'global_options'.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000560 parser.set_option_table(self.global_options +
561 cmd_class.user_options +
562 help_options)
563 parser.set_negative_aliases(negative_opt)
564 (args, opts) = parser.getopt(args[1:])
Greg Ward47460772000-05-23 03:47:35 +0000565 if hasattr(opts, 'help') and opts.help:
Greg Wardd5d8a992000-05-23 01:42:17 +0000566 self._show_help(parser, display_options=0, commands=[cmd_class])
567 return
568
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000569 if (hasattr(cmd_class, 'help_options') and
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000570 isinstance(cmd_class.help_options, list)):
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000571 help_option_found=0
572 for (help_option, short, desc, func) in cmd_class.help_options:
573 if hasattr(opts, parser.get_attr_name(help_option)):
574 help_option_found=1
Benjamin Petersonde055992009-10-09 22:05:45 +0000575 if hasattr(func, '__call__'):
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000576 func()
Greg Ward55fced32000-06-24 01:22:41 +0000577 else:
Fred Drake981a1782001-08-10 18:59:30 +0000578 raise DistutilsClassError(
Walter Dörwald70a6b492004-02-12 17:35:32 +0000579 "invalid help function %r for help option '%s': "
Fred Drake981a1782001-08-10 18:59:30 +0000580 "must be a callable object (function, etc.)"
Walter Dörwald70a6b492004-02-12 17:35:32 +0000581 % (func, help_option))
Greg Ward55fced32000-06-24 01:22:41 +0000582
Fred Drakeb94b8492001-12-06 20:51:35 +0000583 if help_option_found:
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000584 return
Greg Ward9d17a7a2000-06-07 03:00:06 +0000585
Greg Wardd5d8a992000-05-23 01:42:17 +0000586 # Put the options from the command-line into their official
587 # holding pen, the 'command_options' dictionary.
Greg Ward0e48cfd2000-05-26 01:00:15 +0000588 opt_dict = self.get_option_dict(command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000589 for (name, value) in vars(opts).items():
Greg Ward0e48cfd2000-05-26 01:00:15 +0000590 opt_dict[name] = ("command line", value)
Greg Wardd5d8a992000-05-23 01:42:17 +0000591
592 return args
593
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000594 def finalize_options(self):
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000595 """Set final values for all the options on the Distribution
596 instance, analogous to the .finalize_options() method of Command
597 objects.
598 """
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000599 for attr in ('keywords', 'platforms'):
600 value = getattr(self.metadata, attr)
601 if value is None:
602 continue
603 if isinstance(value, str):
604 value = [elm.strip() for elm in value.split(',')]
605 setattr(self.metadata, attr, value)
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000606
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000607 def _show_help(self, parser, global_options=1, display_options=1,
608 commands=[]):
Greg Wardd5d8a992000-05-23 01:42:17 +0000609 """Show help for the setup script command-line in the form of
610 several lists of command-line options. 'parser' should be a
611 FancyGetopt instance; do not expect it to be returned in the
612 same state, as its option table will be reset to make it
613 generate the correct help text.
614
615 If 'global_options' is true, lists the global options:
616 --verbose, --dry-run, etc. If 'display_options' is true, lists
617 the "display-only" options: --name, --version, etc. Finally,
618 lists per-command help for every command name or command class
619 in 'commands'.
620 """
621 # late import because of mutual dependence between these modules
Greg Ward9821bf42000-08-29 01:15:18 +0000622 from distutils.core import gen_usage
Greg Wardd5d8a992000-05-23 01:42:17 +0000623 from distutils.cmd import Command
624
625 if global_options:
Fred Draked04573f2004-08-03 16:37:40 +0000626 if display_options:
627 options = self._get_toplevel_options()
628 else:
629 options = self.global_options
630 parser.set_option_table(options)
Martin v. Löwis8ed338a2005-03-03 08:12:27 +0000631 parser.print_help(self.common_usage + "\nGlobal options:")
Tarek Ziadécd947e02009-07-04 02:59:19 +0000632 print('')
Greg Wardd5d8a992000-05-23 01:42:17 +0000633
634 if display_options:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000635 parser.set_option_table(self.display_options)
636 parser.print_help(
Greg Wardd5d8a992000-05-23 01:42:17 +0000637 "Information display options (just display " +
638 "information, ignore any commands)")
Tarek Ziadécd947e02009-07-04 02:59:19 +0000639 print('')
Greg Wardd5d8a992000-05-23 01:42:17 +0000640
641 for command in self.commands:
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000642 if isinstance(command, type) and issubclass(command, Command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000643 klass = command
644 else:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000645 klass = self.get_command_class(command)
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000646 if (hasattr(klass, 'help_options') and
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000647 isinstance(klass.help_options, list)):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000648 parser.set_option_table(klass.user_options +
649 fix_help_options(klass.help_options))
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000650 else:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000651 parser.set_option_table(klass.user_options)
652 parser.print_help("Options for '%s' command:" % klass.__name__)
Tarek Ziadécd947e02009-07-04 02:59:19 +0000653 print('')
Greg Wardd5d8a992000-05-23 01:42:17 +0000654
Tarek Ziadécd947e02009-07-04 02:59:19 +0000655 print(gen_usage(self.script_name))
Greg Wardd5d8a992000-05-23 01:42:17 +0000656
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000657 def handle_display_options(self, option_order):
Greg Ward82715e12000-04-21 02:28:14 +0000658 """If there were any non-global "display-only" options
Greg Wardd5d8a992000-05-23 01:42:17 +0000659 (--help-commands or the metadata display options) on the command
660 line, display the requested info and return true; else return
661 false.
662 """
Greg Ward9821bf42000-08-29 01:15:18 +0000663 from distutils.core import gen_usage
Greg Ward82715e12000-04-21 02:28:14 +0000664
665 # User just wants a list of commands -- we'll print it out and stop
666 # processing now (ie. if they ran "setup --help-commands foo bar",
667 # we ignore "foo bar").
668 if self.help_commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000669 self.print_commands()
Tarek Ziadécd947e02009-07-04 02:59:19 +0000670 print('')
671 print(gen_usage(self.script_name))
Greg Ward82715e12000-04-21 02:28:14 +0000672 return 1
673
674 # If user supplied any of the "display metadata" options, then
675 # display that metadata in the order in which the user supplied the
676 # metadata options.
677 any_display_options = 0
678 is_display_option = {}
679 for option in self.display_options:
680 is_display_option[option[0]] = 1
681
682 for (opt, val) in option_order:
683 if val and is_display_option.get(opt):
Greg Ward2f2b6c62000-09-25 01:58:07 +0000684 opt = translate_longopt(opt)
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000685 value = getattr(self.metadata, "get_"+opt)()
686 if opt in ['keywords', 'platforms']:
Tarek Ziadécd947e02009-07-04 02:59:19 +0000687 print(','.join(value))
Fred Drakedb7b0022005-03-20 22:19:47 +0000688 elif opt in ('classifiers', 'provides', 'requires',
689 'obsoletes'):
Tarek Ziadécd947e02009-07-04 02:59:19 +0000690 print('\n'.join(value))
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000691 else:
Tarek Ziadécd947e02009-07-04 02:59:19 +0000692 print(value)
Greg Ward82715e12000-04-21 02:28:14 +0000693 any_display_options = 1
694
695 return any_display_options
696
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000697 def print_command_list(self, commands, header, max_length):
Greg Wardfe6462c2000-04-04 01:40:52 +0000698 """Print a subset of the list of all commands -- used by
Greg Wardd5d8a992000-05-23 01:42:17 +0000699 'print_commands()'.
700 """
Tarek Ziadécd947e02009-07-04 02:59:19 +0000701 print(header + ":")
Greg Wardfe6462c2000-04-04 01:40:52 +0000702
703 for cmd in commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000704 klass = self.cmdclass.get(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000705 if not klass:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000706 klass = self.get_command_class(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000707 try:
708 description = klass.description
709 except AttributeError:
710 description = "(no description available)"
711
Tarek Ziadécd947e02009-07-04 02:59:19 +0000712 print(" %-*s %s" % (max_length, cmd, description))
Greg Wardfe6462c2000-04-04 01:40:52 +0000713
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000714 def print_commands(self):
Greg Wardd5d8a992000-05-23 01:42:17 +0000715 """Print out a help message listing all available commands with a
716 description of each. The list is divided into "standard commands"
717 (listed in distutils.command.__all__) and "extra commands"
718 (mentioned in self.cmdclass, but not a standard command). The
719 descriptions come from the command class attribute
720 'description'.
721 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000722 import distutils.command
723 std_commands = distutils.command.__all__
724 is_std = {}
725 for cmd in std_commands:
726 is_std[cmd] = 1
727
728 extra_commands = []
729 for cmd in self.cmdclass.keys():
730 if not is_std.get(cmd):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000731 extra_commands.append(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000732
733 max_length = 0
734 for cmd in (std_commands + extra_commands):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000735 if len(cmd) > max_length:
736 max_length = len(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000737
Greg Wardfd7b91e2000-09-26 01:52:25 +0000738 self.print_command_list(std_commands,
739 "Standard commands",
740 max_length)
Greg Wardfe6462c2000-04-04 01:40:52 +0000741 if extra_commands:
742 print
Greg Wardfd7b91e2000-09-26 01:52:25 +0000743 self.print_command_list(extra_commands,
744 "Extra commands",
745 max_length)
Greg Wardfe6462c2000-04-04 01:40:52 +0000746
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000747 def get_command_list(self):
Greg Wardf6fc8752000-11-11 02:47:11 +0000748 """Get a list of (command, description) tuples.
749 The list is divided into "standard commands" (listed in
750 distutils.command.__all__) and "extra commands" (mentioned in
751 self.cmdclass, but not a standard command). The descriptions come
752 from the command class attribute 'description'.
753 """
754 # Currently this is only used on Mac OS, for the Mac-only GUI
755 # Distutils interface (by Jack Jansen)
756
757 import distutils.command
758 std_commands = distutils.command.__all__
759 is_std = {}
760 for cmd in std_commands:
761 is_std[cmd] = 1
762
763 extra_commands = []
764 for cmd in self.cmdclass.keys():
765 if not is_std.get(cmd):
766 extra_commands.append(cmd)
767
768 rv = []
769 for cmd in (std_commands + extra_commands):
770 klass = self.cmdclass.get(cmd)
771 if not klass:
772 klass = self.get_command_class(cmd)
773 try:
774 description = klass.description
775 except AttributeError:
776 description = "(no description available)"
777 rv.append((cmd, description))
778 return rv
Greg Wardfe6462c2000-04-04 01:40:52 +0000779
780 # -- Command class/object methods ----------------------------------
781
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000782 def get_command_packages(self):
Fred Draked04573f2004-08-03 16:37:40 +0000783 """Return a list of packages from which commands are loaded."""
784 pkgs = self.command_packages
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000785 if not isinstance(pkgs, list):
786 if pkgs is None:
787 pkgs = ''
788 pkgs = [pkg.strip() for pkg in pkgs.split(',') if pkg != '']
Fred Draked04573f2004-08-03 16:37:40 +0000789 if "distutils.command" not in pkgs:
790 pkgs.insert(0, "distutils.command")
791 self.command_packages = pkgs
792 return pkgs
793
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000794 def get_command_class(self, command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000795 """Return the class that implements the Distutils command named by
796 'command'. First we check the 'cmdclass' dictionary; if the
797 command is mentioned there, we fetch the class object from the
798 dictionary and return it. Otherwise we load the command module
799 ("distutils.command." + command) and fetch the command class from
800 the module. The loaded class is also stored in 'cmdclass'
801 to speed future calls to 'get_command_class()'.
Greg Wardfe6462c2000-04-04 01:40:52 +0000802
Gregory P. Smith14263542000-05-12 00:41:33 +0000803 Raises DistutilsModuleError if the expected module could not be
Greg Wardd5d8a992000-05-23 01:42:17 +0000804 found, or if that module does not define the expected class.
805 """
806 klass = self.cmdclass.get(command)
807 if klass:
808 return klass
Greg Wardfe6462c2000-04-04 01:40:52 +0000809
Fred Draked04573f2004-08-03 16:37:40 +0000810 for pkgname in self.get_command_packages():
811 module_name = "%s.%s" % (pkgname, command)
812 klass_name = command
Greg Wardfe6462c2000-04-04 01:40:52 +0000813
Fred Draked04573f2004-08-03 16:37:40 +0000814 try:
815 __import__ (module_name)
816 module = sys.modules[module_name]
817 except ImportError:
818 continue
Greg Wardfe6462c2000-04-04 01:40:52 +0000819
Fred Draked04573f2004-08-03 16:37:40 +0000820 try:
821 klass = getattr(module, klass_name)
822 except AttributeError:
823 raise DistutilsModuleError, \
824 "invalid command '%s' (no class '%s' in module '%s')" \
825 % (command, klass_name, module_name)
Greg Wardfe6462c2000-04-04 01:40:52 +0000826
Fred Draked04573f2004-08-03 16:37:40 +0000827 self.cmdclass[command] = klass
828 return klass
829
830 raise DistutilsModuleError("invalid command '%s'" % command)
831
Greg Wardfe6462c2000-04-04 01:40:52 +0000832
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000833 def get_command_obj(self, command, create=1):
Greg Wardd5d8a992000-05-23 01:42:17 +0000834 """Return the command object for 'command'. Normally this object
Greg Ward612eb9f2000-07-27 02:13:20 +0000835 is cached on a previous call to 'get_command_obj()'; if no command
Greg Wardd5d8a992000-05-23 01:42:17 +0000836 object for 'command' is in the cache, then we either create and
837 return it (if 'create' is true) or return None.
838 """
839 cmd_obj = self.command_obj.get(command)
Greg Wardfe6462c2000-04-04 01:40:52 +0000840 if not cmd_obj and create:
Greg Ward2bd3f422000-06-02 01:59:33 +0000841 if DEBUG:
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000842 self.announce("Distribution.get_command_obj(): " \
843 "creating '%s' command object" % command)
Greg Ward47460772000-05-23 03:47:35 +0000844
Greg Wardd5d8a992000-05-23 01:42:17 +0000845 klass = self.get_command_class(command)
Greg Ward47460772000-05-23 03:47:35 +0000846 cmd_obj = self.command_obj[command] = klass(self)
847 self.have_run[command] = 0
848
849 # Set any options that were supplied in config files
850 # or on the command line. (NB. support for error
851 # reporting is lame here: any errors aren't reported
852 # until 'finalize_options()' is called, which means
853 # we won't report the source of the error.)
854 options = self.command_options.get(command)
855 if options:
Greg Wardc32d9a62000-05-28 23:53:06 +0000856 self._set_command_options(cmd_obj, options)
Greg Wardfe6462c2000-04-04 01:40:52 +0000857
858 return cmd_obj
859
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000860 def _set_command_options(self, command_obj, option_dict=None):
Greg Wardc32d9a62000-05-28 23:53:06 +0000861 """Set the options for 'command_obj' from 'option_dict'. Basically
862 this means copying elements of a dictionary ('option_dict') to
863 attributes of an instance ('command').
864
Greg Wardceb9e222000-09-25 01:23:52 +0000865 'command_obj' must be a Command instance. If 'option_dict' is not
Greg Wardc32d9a62000-05-28 23:53:06 +0000866 supplied, uses the standard option dictionary for this command
867 (from 'self.command_options').
868 """
Greg Wardc32d9a62000-05-28 23:53:06 +0000869 command_name = command_obj.get_command_name()
870 if option_dict is None:
871 option_dict = self.get_option_dict(command_name)
872
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000873 if DEBUG:
874 self.announce(" setting options for '%s' command:" % command_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000875 for (option, (source, value)) in option_dict.items():
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000876 if DEBUG:
877 self.announce(" %s = %s (from %s)" % (option, value,
878 source))
Greg Wardceb9e222000-09-25 01:23:52 +0000879 try:
Greg Ward2f2b6c62000-09-25 01:58:07 +0000880 bool_opts = map(translate_longopt, command_obj.boolean_options)
Greg Wardceb9e222000-09-25 01:23:52 +0000881 except AttributeError:
882 bool_opts = []
883 try:
884 neg_opt = command_obj.negative_opt
885 except AttributeError:
886 neg_opt = {}
887
888 try:
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000889 is_string = isinstance(value, str)
Guido van Rossum8bc09652008-02-21 18:18:37 +0000890 if option in neg_opt and is_string:
Greg Wardceb9e222000-09-25 01:23:52 +0000891 setattr(command_obj, neg_opt[option], not strtobool(value))
Greg Ward2c08cf02000-09-27 00:15:37 +0000892 elif option in bool_opts and is_string:
Greg Wardceb9e222000-09-25 01:23:52 +0000893 setattr(command_obj, option, strtobool(value))
894 elif hasattr(command_obj, option):
895 setattr(command_obj, option, value)
896 else:
897 raise DistutilsOptionError, \
898 ("error in %s: command '%s' has no such option '%s'"
899 % (source, command_name, option))
900 except ValueError, msg:
901 raise DistutilsOptionError, msg
Greg Wardc32d9a62000-05-28 23:53:06 +0000902
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000903 def reinitialize_command(self, command, reinit_subcommands=0):
Greg Wardc32d9a62000-05-28 23:53:06 +0000904 """Reinitializes a command to the state it was in when first
905 returned by 'get_command_obj()': ie., initialized but not yet
Greg Ward7d9c7052000-06-28 01:25:27 +0000906 finalized. This provides the opportunity to sneak option
Greg Wardc32d9a62000-05-28 23:53:06 +0000907 values in programmatically, overriding or supplementing
908 user-supplied values from the config files and command line.
909 You'll have to re-finalize the command object (by calling
910 'finalize_options()' or 'ensure_finalized()') before using it for
Fred Drakeb94b8492001-12-06 20:51:35 +0000911 real.
Greg Wardc32d9a62000-05-28 23:53:06 +0000912
Greg Wardf449ea52000-09-16 15:23:28 +0000913 'command' should be a command name (string) or command object. If
914 'reinit_subcommands' is true, also reinitializes the command's
915 sub-commands, as declared by the 'sub_commands' class attribute (if
916 it has one). See the "install" command for an example. Only
917 reinitializes the sub-commands that actually matter, ie. those
918 whose test predicates return true.
919
Greg Wardc32d9a62000-05-28 23:53:06 +0000920 Returns the reinitialized command object.
921 """
922 from distutils.cmd import Command
923 if not isinstance(command, Command):
924 command_name = command
925 command = self.get_command_obj(command_name)
926 else:
927 command_name = command.get_command_name()
928
929 if not command.finalized:
Greg Ward282c7a02000-06-01 01:09:47 +0000930 return command
Greg Wardc32d9a62000-05-28 23:53:06 +0000931 command.initialize_options()
932 command.finalized = 0
Greg Ward43955c92000-06-06 02:52:36 +0000933 self.have_run[command_name] = 0
Greg Wardc32d9a62000-05-28 23:53:06 +0000934 self._set_command_options(command)
Greg Wardf449ea52000-09-16 15:23:28 +0000935
Greg Wardf449ea52000-09-16 15:23:28 +0000936 if reinit_subcommands:
Greg Wardf449ea52000-09-16 15:23:28 +0000937 for sub in command.get_sub_commands():
Fred Drakeb94b8492001-12-06 20:51:35 +0000938 self.reinitialize_command(sub, reinit_subcommands)
Greg Wardf449ea52000-09-16 15:23:28 +0000939
Greg Wardc32d9a62000-05-28 23:53:06 +0000940 return command
941
Greg Wardfe6462c2000-04-04 01:40:52 +0000942 # -- Methods that operate on the Distribution ----------------------
943
Tarek Ziadé63f17382009-07-04 02:02:41 +0000944 def announce(self, msg, level=log.INFO):
945 log.log(level, msg)
Greg Wardfe6462c2000-04-04 01:40:52 +0000946
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000947 def run_commands(self):
Greg Ward82715e12000-04-21 02:28:14 +0000948 """Run each command that was seen on the setup script command line.
Greg Wardd5d8a992000-05-23 01:42:17 +0000949 Uses the list of commands found and cache of command objects
Greg Wardfd7b91e2000-09-26 01:52:25 +0000950 created by 'get_command_obj()'.
951 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000952 for cmd in self.commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000953 self.run_command(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000954
Greg Wardfe6462c2000-04-04 01:40:52 +0000955 # -- Methods that operate on its Commands --------------------------
956
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000957 def run_command(self, command):
Greg Wardfe6462c2000-04-04 01:40:52 +0000958 """Do whatever it takes to run a command (including nothing at all,
Greg Wardd5d8a992000-05-23 01:42:17 +0000959 if the command has already been run). Specifically: if we have
960 already created and run the command named by 'command', return
961 silently without doing anything. If the command named by 'command'
962 doesn't even have a command object yet, create one. Then invoke
963 'run()' on that command object (or an existing one).
964 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000965 # Already been here, done that? then return silently.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000966 if self.have_run.get(command):
Greg Wardfe6462c2000-04-04 01:40:52 +0000967 return
968
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000969 log.info("running %s", command)
Greg Wardfd7b91e2000-09-26 01:52:25 +0000970 cmd_obj = self.get_command_obj(command)
971 cmd_obj.ensure_finalized()
972 cmd_obj.run()
Greg Wardfe6462c2000-04-04 01:40:52 +0000973 self.have_run[command] = 1
974
975
Greg Wardfe6462c2000-04-04 01:40:52 +0000976 # -- Distribution query methods ------------------------------------
977
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000978 def has_pure_modules(self):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000979 return len(self.packages or self.py_modules or []) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000980
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000981 def has_ext_modules(self):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000982 return self.ext_modules and len(self.ext_modules) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000983
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000984 def has_c_libraries(self):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000985 return self.libraries and len(self.libraries) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000986
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000987 def has_modules(self):
Greg Wardfe6462c2000-04-04 01:40:52 +0000988 return self.has_pure_modules() or self.has_ext_modules()
989
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000990 def has_headers(self):
Greg Ward51def7d2000-05-27 01:36:14 +0000991 return self.headers and len(self.headers) > 0
992
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000993 def has_scripts(self):
Greg Ward44a61bb2000-05-20 15:06:48 +0000994 return self.scripts and len(self.scripts) > 0
995
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000996 def has_data_files(self):
Greg Ward44a61bb2000-05-20 15:06:48 +0000997 return self.data_files and len(self.data_files) > 0
998
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000999 def is_pure(self):
Greg Wardfe6462c2000-04-04 01:40:52 +00001000 return (self.has_pure_modules() and
1001 not self.has_ext_modules() and
1002 not self.has_c_libraries())
1003
Greg Ward82715e12000-04-21 02:28:14 +00001004 # -- Metadata query methods ----------------------------------------
1005
1006 # If you're looking for 'get_name()', 'get_version()', and so forth,
1007 # they are defined in a sneaky way: the constructor binds self.get_XXX
1008 # to self.metadata.get_XXX. The actual code is in the
1009 # DistributionMetadata class, below.
1010
Greg Ward82715e12000-04-21 02:28:14 +00001011class DistributionMetadata:
1012 """Dummy class to hold the distribution meta-data: name, version,
Greg Wardfd7b91e2000-09-26 01:52:25 +00001013 author, and so forth.
1014 """
Greg Ward82715e12000-04-21 02:28:14 +00001015
Neil Schemenauera8aefe52001-09-03 15:47:21 +00001016 _METHOD_BASENAMES = ("name", "version", "author", "author_email",
1017 "maintainer", "maintainer_email", "url",
1018 "license", "description", "long_description",
1019 "keywords", "platforms", "fullname", "contact",
Andrew M. Kuchlinga52b8522003-03-03 20:07:27 +00001020 "contact_email", "license", "classifiers",
Fred Drakedb7b0022005-03-20 22:19:47 +00001021 "download_url",
1022 # PEP 314
1023 "provides", "requires", "obsoletes",
1024 )
Neil Schemenauera8aefe52001-09-03 15:47:21 +00001025
Tarek Ziadéa939ecd2009-12-08 08:56:49 +00001026 def __init__(self, path=None):
1027 if path is not None:
1028 self.read_pkg_file(open(path))
1029 else:
1030 self.name = None
1031 self.version = None
1032 self.author = None
1033 self.author_email = None
1034 self.maintainer = None
1035 self.maintainer_email = None
1036 self.url = None
1037 self.license = None
1038 self.description = None
1039 self.long_description = None
1040 self.keywords = None
1041 self.platforms = None
1042 self.classifiers = None
1043 self.download_url = None
1044 # PEP 314
1045 self.provides = None
1046 self.requires = None
1047 self.obsoletes = None
1048
1049 def read_pkg_file(self, file):
1050 """Reads the metadata values from a file object."""
Tarek Ziadé4b7f9432009-12-08 09:39:51 +00001051 msg = message_from_file(file)
1052
1053 def _read_field(name):
1054 value = msg[name]
1055 if value == 'UNKNOWN':
1056 return None
1057 return value
1058
1059 def _read_list(name):
1060 values = msg.get_all(name, None)
1061 if values == []:
1062 return None
1063 return values
1064
Tarek Ziadéa939ecd2009-12-08 08:56:49 +00001065 metadata_version = msg['metadata-version']
Tarek Ziadé4b7f9432009-12-08 09:39:51 +00001066 self.name = _read_field('name')
1067 self.version = _read_field('version')
1068 self.description = _read_field('summary')
Tarek Ziadéa939ecd2009-12-08 08:56:49 +00001069 # we are filling author only.
Tarek Ziadé4b7f9432009-12-08 09:39:51 +00001070 self.author = _read_field('author')
Greg Ward82715e12000-04-21 02:28:14 +00001071 self.maintainer = None
Tarek Ziadé4b7f9432009-12-08 09:39:51 +00001072 self.author_email = _read_field('author-email')
Greg Ward82715e12000-04-21 02:28:14 +00001073 self.maintainer_email = None
Tarek Ziadé4b7f9432009-12-08 09:39:51 +00001074 self.url = _read_field('home-page')
1075 self.license = _read_field('license')
Tarek Ziadéa939ecd2009-12-08 08:56:49 +00001076
1077 if 'download-url' in msg:
Tarek Ziadé4b7f9432009-12-08 09:39:51 +00001078 self.download_url = _read_field('download-url')
Tarek Ziadéa939ecd2009-12-08 08:56:49 +00001079 else:
1080 self.download_url = None
1081
Tarek Ziadé4b7f9432009-12-08 09:39:51 +00001082 self.long_description = _read_field('description')
1083 self.description = _read_field('summary')
Tarek Ziadéa939ecd2009-12-08 08:56:49 +00001084
1085 if 'keywords' in msg:
Tarek Ziadé4b7f9432009-12-08 09:39:51 +00001086 self.keywords = _read_field('keywords').split(',')
Tarek Ziadéa939ecd2009-12-08 08:56:49 +00001087
Tarek Ziadé4b7f9432009-12-08 09:39:51 +00001088 self.platforms = _read_list('platform')
1089 self.classifiers = _read_list('classifier')
Tarek Ziadéa939ecd2009-12-08 08:56:49 +00001090
1091 # PEP 314 - these fields only exist in 1.1
1092 if metadata_version == '1.1':
Tarek Ziadé4b7f9432009-12-08 09:39:51 +00001093 self.requires = _read_list('requires')
1094 self.provides = _read_list('provides')
1095 self.obsoletes = _read_list('obsoletes')
Tarek Ziadéa939ecd2009-12-08 08:56:49 +00001096 else:
1097 self.requires = None
1098 self.provides = None
1099 self.obsoletes = None
Fred Drakeb94b8492001-12-06 20:51:35 +00001100
Tarek Ziadéae6acfc2009-05-16 18:29:40 +00001101 def write_pkg_info(self, base_dir):
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001102 """Write the PKG-INFO file into the release tree.
1103 """
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001104 pkg_info = open( os.path.join(base_dir, 'PKG-INFO'), 'w')
Fred Drakedb7b0022005-03-20 22:19:47 +00001105 self.write_pkg_file(pkg_info)
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001106 pkg_info.close()
Fred Drakeb94b8492001-12-06 20:51:35 +00001107
Tarek Ziadéae6acfc2009-05-16 18:29:40 +00001108 def write_pkg_file(self, file):
Fred Drakedb7b0022005-03-20 22:19:47 +00001109 """Write the PKG-INFO format data to a file object.
1110 """
1111 version = '1.0'
1112 if self.provides or self.requires or self.obsoletes:
1113 version = '1.1'
1114
Marc-André Lemburgb339b2a2008-09-03 11:13:56 +00001115 self._write_field(file, 'Metadata-Version', version)
1116 self._write_field(file, 'Name', self.get_name())
1117 self._write_field(file, 'Version', self.get_version())
1118 self._write_field(file, 'Summary', self.get_description())
1119 self._write_field(file, 'Home-page', self.get_url())
1120 self._write_field(file, 'Author', self.get_contact())
1121 self._write_field(file, 'Author-email', self.get_contact_email())
1122 self._write_field(file, 'License', self.get_license())
Fred Drakedb7b0022005-03-20 22:19:47 +00001123 if self.download_url:
Marc-André Lemburgb339b2a2008-09-03 11:13:56 +00001124 self._write_field(file, 'Download-URL', self.download_url)
Fred Drakedb7b0022005-03-20 22:19:47 +00001125
Tarek Ziadéc01cbc42009-06-01 22:22:13 +00001126 long_desc = rfc822_escape(self.get_long_description())
Marc-André Lemburgb339b2a2008-09-03 11:13:56 +00001127 self._write_field(file, 'Description', long_desc)
Fred Drakedb7b0022005-03-20 22:19:47 +00001128
Tarek Ziadéc01cbc42009-06-01 22:22:13 +00001129 keywords = ','.join(self.get_keywords())
Fred Drakedb7b0022005-03-20 22:19:47 +00001130 if keywords:
Marc-André Lemburgb339b2a2008-09-03 11:13:56 +00001131 self._write_field(file, 'Keywords', keywords)
Fred Drakedb7b0022005-03-20 22:19:47 +00001132
1133 self._write_list(file, 'Platform', self.get_platforms())
1134 self._write_list(file, 'Classifier', self.get_classifiers())
1135
1136 # PEP 314
1137 self._write_list(file, 'Requires', self.get_requires())
1138 self._write_list(file, 'Provides', self.get_provides())
1139 self._write_list(file, 'Obsoletes', self.get_obsoletes())
1140
Marc-André Lemburgb339b2a2008-09-03 11:13:56 +00001141 def _write_field(self, file, name, value):
Marc-André Lemburgb339b2a2008-09-03 11:13:56 +00001142 if isinstance(value, unicode):
1143 value = value.encode(PKG_INFO_ENCODING)
1144 else:
1145 value = str(value)
1146 file.write('%s: %s\n' % (name, value))
1147
Fred Drakedb7b0022005-03-20 22:19:47 +00001148 def _write_list (self, file, name, values):
1149 for value in values:
Marc-André Lemburgb339b2a2008-09-03 11:13:56 +00001150 self._write_field(file, name, value)
Fred Drakedb7b0022005-03-20 22:19:47 +00001151
Greg Ward82715e12000-04-21 02:28:14 +00001152 # -- Metadata query methods ----------------------------------------
1153
Tarek Ziadéae6acfc2009-05-16 18:29:40 +00001154 def get_name(self):
Greg Wardfe6462c2000-04-04 01:40:52 +00001155 return self.name or "UNKNOWN"
1156
Greg Ward82715e12000-04-21 02:28:14 +00001157 def get_version(self):
Thomas Hellerbcd89752001-12-06 20:44:19 +00001158 return self.version or "0.0.0"
Greg Wardfe6462c2000-04-04 01:40:52 +00001159
Tarek Ziadéae6acfc2009-05-16 18:29:40 +00001160 def get_fullname(self):
Greg Ward82715e12000-04-21 02:28:14 +00001161 return "%s-%s" % (self.get_name(), self.get_version())
1162
1163 def get_author(self):
1164 return self.author or "UNKNOWN"
1165
1166 def get_author_email(self):
1167 return self.author_email or "UNKNOWN"
1168
1169 def get_maintainer(self):
1170 return self.maintainer or "UNKNOWN"
1171
1172 def get_maintainer_email(self):
1173 return self.maintainer_email or "UNKNOWN"
1174
1175 def get_contact(self):
Tarek Ziadéae6acfc2009-05-16 18:29:40 +00001176 return self.maintainer or self.author or "UNKNOWN"
Greg Ward82715e12000-04-21 02:28:14 +00001177
1178 def get_contact_email(self):
Tarek Ziadéae6acfc2009-05-16 18:29:40 +00001179 return self.maintainer_email or self.author_email or "UNKNOWN"
Greg Ward82715e12000-04-21 02:28:14 +00001180
1181 def get_url(self):
1182 return self.url or "UNKNOWN"
1183
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +00001184 def get_license(self):
1185 return self.license or "UNKNOWN"
1186 get_licence = get_license
Fred Drakeb94b8492001-12-06 20:51:35 +00001187
Greg Ward82715e12000-04-21 02:28:14 +00001188 def get_description(self):
1189 return self.description or "UNKNOWN"
Greg Warde5a584e2000-04-26 02:26:55 +00001190
1191 def get_long_description(self):
1192 return self.long_description or "UNKNOWN"
1193
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001194 def get_keywords(self):
1195 return self.keywords or []
1196
1197 def get_platforms(self):
1198 return self.platforms or ["UNKNOWN"]
1199
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +00001200 def get_classifiers(self):
1201 return self.classifiers or []
1202
Andrew M. Kuchling188d85f2003-02-19 14:16:01 +00001203 def get_download_url(self):
1204 return self.download_url or "UNKNOWN"
1205
Fred Drakedb7b0022005-03-20 22:19:47 +00001206 # PEP 314
Fred Drakedb7b0022005-03-20 22:19:47 +00001207 def get_requires(self):
1208 return self.requires or []
1209
1210 def set_requires(self, value):
1211 import distutils.versionpredicate
1212 for v in value:
1213 distutils.versionpredicate.VersionPredicate(v)
1214 self.requires = value
1215
1216 def get_provides(self):
1217 return self.provides or []
1218
1219 def set_provides(self, value):
1220 value = [v.strip() for v in value]
1221 for v in value:
1222 import distutils.versionpredicate
Fred Drake227e8ff2005-03-21 06:36:32 +00001223 distutils.versionpredicate.split_provision(v)
Fred Drakedb7b0022005-03-20 22:19:47 +00001224 self.provides = value
1225
1226 def get_obsoletes(self):
1227 return self.obsoletes or []
1228
1229 def set_obsoletes(self, value):
1230 import distutils.versionpredicate
1231 for v in value:
1232 distutils.versionpredicate.VersionPredicate(v)
1233 self.obsoletes = value
1234
Tarek Ziadéae6acfc2009-05-16 18:29:40 +00001235def fix_help_options(options):
Greg Ward2ff78872000-06-24 00:23:20 +00001236 """Convert a 4-tuple 'help_options' list as found in various command
1237 classes to the 3-tuple form required by FancyGetopt.
1238 """
1239 new_options = []
1240 for help_tuple in options:
1241 new_options.append(help_tuple[0:3])
1242 return new_options