blob: 5a107e7d83b0f371727b9793d8cfae98a2c37767 [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
Tarek Ziadéb88a4962009-12-08 09:45:25 +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é88e2c5d2009-12-21 01:49:00 +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
24# Regex to define acceptable Distutils command names. This is not *quite*
25# the same as a Python NAME -- I don't allow leading underscores. The fact
26# that they're very similar is no coincidence; the default naming scheme is
27# to look for a Python module named after the command.
28command_re = re.compile (r'^[a-zA-Z]([a-zA-Z0-9_]*)$')
29
30
31class Distribution:
Greg Ward8ff5a3f2000-06-02 00:44:53 +000032 """The core of the Distutils. Most of the work hiding behind 'setup'
33 is really done within a Distribution instance, which farms the work out
34 to the Distutils commands specified on the command line.
Greg Wardfe6462c2000-04-04 01:40:52 +000035
Greg Ward8ff5a3f2000-06-02 00:44:53 +000036 Setup scripts will almost never instantiate Distribution directly,
37 unless the 'setup()' function is totally inadequate to their needs.
38 However, it is conceivable that a setup script might wish to subclass
39 Distribution for some specialized purpose, and then pass the subclass
40 to 'setup()' as the 'distclass' keyword argument. If so, it is
41 necessary to respect the expectations that 'setup' has of Distribution.
42 See the code for 'setup()', in core.py, for details.
43 """
Greg Wardfe6462c2000-04-04 01:40:52 +000044
45
46 # 'global_options' describes the command-line options that may be
Greg Ward82715e12000-04-21 02:28:14 +000047 # supplied to the setup script prior to any actual commands.
48 # Eg. "./setup.py -n" or "./setup.py --quiet" both take advantage of
Greg Wardfe6462c2000-04-04 01:40:52 +000049 # these global options. This list should be kept to a bare minimum,
50 # since every global option is also valid as a command option -- and we
51 # don't want to pollute the commands with too many options that they
52 # have minimal control over.
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000053 # The fourth entry for verbose means that it can be repeated.
54 global_options = [('verbose', 'v', "run verbosely (default)", 1),
Greg Wardd5d8a992000-05-23 01:42:17 +000055 ('quiet', 'q', "run quietly (turns verbosity off)"),
56 ('dry-run', 'n', "don't actually do anything"),
57 ('help', 'h', "show detailed help message"),
Tarek Ziadéc7c71ff2009-10-27 23:12:01 +000058 ('no-user-cfg', None,
59 'ignore pydistutils.cfg in your home directory'),
60 ]
Greg Ward82715e12000-04-21 02:28:14 +000061
Martin v. Löwis8ed338a2005-03-03 08:12:27 +000062 # 'common_usage' is a short (2-3 line) string describing the common
63 # usage of the setup script.
64 common_usage = """\
65Common commands: (see '--help-commands' for more)
66
67 setup.py build will build the package underneath 'build/'
68 setup.py install will install the package
69"""
70
Greg Ward82715e12000-04-21 02:28:14 +000071 # options that are not propagated to the commands
72 display_options = [
73 ('help-commands', None,
74 "list all available commands"),
75 ('name', None,
76 "print package name"),
77 ('version', 'V',
78 "print package version"),
79 ('fullname', None,
80 "print <package name>-<version>"),
81 ('author', None,
82 "print the author's name"),
83 ('author-email', None,
84 "print the author's email address"),
85 ('maintainer', None,
86 "print the maintainer's name"),
87 ('maintainer-email', None,
88 "print the maintainer's email address"),
89 ('contact', None,
Greg Wardd5d8a992000-05-23 01:42:17 +000090 "print the maintainer's name if known, else the author's"),
Greg Ward82715e12000-04-21 02:28:14 +000091 ('contact-email', None,
Greg Wardd5d8a992000-05-23 01:42:17 +000092 "print the maintainer's email address if known, else the author's"),
Greg Ward82715e12000-04-21 02:28:14 +000093 ('url', None,
94 "print the URL for this package"),
Greg Ward82715e12000-04-21 02:28:14 +000095 ('license', None,
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +000096 "print the license of the package"),
97 ('licence', None,
98 "alias for --license"),
Greg Ward82715e12000-04-21 02:28:14 +000099 ('description', None,
100 "print the package description"),
Greg Warde5a584e2000-04-26 02:26:55 +0000101 ('long-description', None,
102 "print the long package description"),
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000103 ('platforms', None,
104 "print the list of platforms"),
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +0000105 ('classifiers', None,
106 "print the list of classifiers"),
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000107 ('keywords', None,
108 "print the list of keywords"),
Fred Drakedb7b0022005-03-20 22:19:47 +0000109 ('provides', None,
110 "print the list of packages/modules provided"),
111 ('requires', None,
112 "print the list of packages/modules required"),
113 ('obsoletes', None,
114 "print the list of packages/modules made obsolete")
Greg Ward82715e12000-04-21 02:28:14 +0000115 ]
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000116 display_option_names = [translate_longopt(x[0]) for x in display_options]
Greg Ward82715e12000-04-21 02:28:14 +0000117
118 # negative options are options that exclude other options
Greg Wardfe6462c2000-04-04 01:40:52 +0000119 negative_opt = {'quiet': 'verbose'}
120
121
122 # -- Creation/initialization methods -------------------------------
Fred Drakeb94b8492001-12-06 20:51:35 +0000123
Greg Wardfe6462c2000-04-04 01:40:52 +0000124 def __init__ (self, attrs=None):
125 """Construct a new Distribution instance: initialize all the
Greg Ward8ff5a3f2000-06-02 00:44:53 +0000126 attributes of a Distribution, and then use 'attrs' (a dictionary
127 mapping attribute names to values) to assign some of those
128 attributes their "real" values. (Any attributes not mentioned in
129 'attrs' will be assigned to some null value: 0, None, an empty list
130 or dictionary, etc.) Most importantly, initialize the
131 'command_obj' attribute to the empty dictionary; this will be
132 filled in with real command objects by 'parse_command_line()'.
133 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000134
135 # Default values for our command-line options
136 self.verbose = 1
137 self.dry_run = 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000138 self.help = 0
Greg Ward82715e12000-04-21 02:28:14 +0000139 for attr in self.display_option_names:
140 setattr(self, attr, 0)
Greg Wardfe6462c2000-04-04 01:40:52 +0000141
Greg Ward82715e12000-04-21 02:28:14 +0000142 # Store the distribution meta-data (name, version, author, and so
143 # forth) in a separate object -- we're getting to have enough
144 # information here (and enough command-line options) that it's
145 # worth it. Also delegate 'get_XXX()' methods to the 'metadata'
146 # object in a sneaky and underhanded (but efficient!) way.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000147 self.metadata = DistributionMetadata()
Neil Schemenauera8aefe52001-09-03 15:47:21 +0000148 for basename in self.metadata._METHOD_BASENAMES:
Greg Ward4982f982000-04-22 02:52:44 +0000149 method_name = "get_" + basename
150 setattr(self, method_name, getattr(self.metadata, method_name))
Greg Wardfe6462c2000-04-04 01:40:52 +0000151
152 # 'cmdclass' maps command names to class objects, so we
153 # can 1) quickly figure out which class to instantiate when
154 # we need to create a new command object, and 2) have a way
Greg Ward82715e12000-04-21 02:28:14 +0000155 # for the setup script to override command classes
Greg Wardfe6462c2000-04-04 01:40:52 +0000156 self.cmdclass = {}
157
Fred Draked04573f2004-08-03 16:37:40 +0000158 # 'command_packages' is a list of packages in which commands
159 # are searched for. The factory for command 'foo' is expected
160 # to be named 'foo' in the module 'foo' in one of the packages
161 # named here. This list is searched from the left; an error
162 # is raised if no named package provides the command being
163 # searched for. (Always access using get_command_packages().)
164 self.command_packages = None
165
Greg Ward9821bf42000-08-29 01:15:18 +0000166 # 'script_name' and 'script_args' are usually set to sys.argv[0]
167 # and sys.argv[1:], but they can be overridden when the caller is
168 # not necessarily a setup script run from the command-line.
169 self.script_name = None
170 self.script_args = None
171
Greg Wardd5d8a992000-05-23 01:42:17 +0000172 # 'command_options' is where we store command options between
173 # parsing them (from config files, the command-line, etc.) and when
174 # they are actually needed -- ie. when the command in question is
175 # instantiated. It is a dictionary of dictionaries of 2-tuples:
176 # command_options = { command_name : { option : (source, value) } }
Gregory P. Smith14263542000-05-12 00:41:33 +0000177 self.command_options = {}
178
Martin v. Löwis98da5622005-03-23 18:54:36 +0000179 # 'dist_files' is the list of (command, pyversion, file) that
180 # have been created by any dist commands run so far. This is
181 # filled regardless of whether the run is dry or not. pyversion
182 # gives sysconfig.get_python_version() if the dist file is
183 # specific to a Python version, 'any' if it is good for all
184 # Python versions on the target platform, and '' for a source
185 # file. pyversion should not be used to specify minimum or
186 # maximum required Python versions; use the metainfo for that
187 # instead.
Martin v. Löwis55f1bb82005-03-21 20:56:35 +0000188 self.dist_files = []
189
Greg Wardfe6462c2000-04-04 01:40:52 +0000190 # These options are really the business of various commands, rather
191 # than of the Distribution itself. We provide aliases for them in
192 # Distribution as a convenience to the developer.
Greg Wardfe6462c2000-04-04 01:40:52 +0000193 self.packages = None
Fred Drake0eb32a62004-06-11 21:50:33 +0000194 self.package_data = {}
Greg Wardfe6462c2000-04-04 01:40:52 +0000195 self.package_dir = None
196 self.py_modules = None
197 self.libraries = None
Greg Ward51def7d2000-05-27 01:36:14 +0000198 self.headers = None
Greg Wardfe6462c2000-04-04 01:40:52 +0000199 self.ext_modules = None
200 self.ext_package = None
201 self.include_dirs = None
202 self.extra_path = None
Gregory P. Smithb2e3bb32000-05-12 00:52:23 +0000203 self.scripts = None
Gregory P. Smith6a901dd2000-05-13 03:09:50 +0000204 self.data_files = None
Tarek Ziadé13f7c3b2009-01-09 00:15:45 +0000205 self.password = ''
Greg Wardfe6462c2000-04-04 01:40:52 +0000206
207 # And now initialize bookkeeping stuff that can't be supplied by
208 # the caller at all. 'command_obj' maps command names to
209 # Command instances -- that's how we enforce that every command
210 # class is a singleton.
211 self.command_obj = {}
212
213 # 'have_run' maps command names to boolean values; it keeps track
214 # of whether we have actually run a particular command, to make it
215 # cheap to "run" a command whenever we think we might need to -- if
216 # it's already been done, no need for expensive filesystem
217 # operations, we just check the 'have_run' dictionary and carry on.
218 # It's only safe to query 'have_run' for a command class that has
219 # been instantiated -- a false value will be inserted when the
220 # command object is created, and replaced with a true value when
Greg Ward612eb9f2000-07-27 02:13:20 +0000221 # the command is successfully run. Thus it's probably best to use
Greg Wardfe6462c2000-04-04 01:40:52 +0000222 # '.get()' rather than a straight lookup.
223 self.have_run = {}
224
225 # Now we'll use the attrs dictionary (ultimately, keyword args from
Greg Ward82715e12000-04-21 02:28:14 +0000226 # the setup script) to possibly override any or all of these
227 # distribution options.
228
Greg Wardfe6462c2000-04-04 01:40:52 +0000229 if attrs:
Greg Wardfe6462c2000-04-04 01:40:52 +0000230 # Pull out the set of command options and work on them
231 # specifically. Note that this order guarantees that aliased
232 # command options will override any supplied redundantly
233 # through the general options dictionary.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000234 options = attrs.get('options')
Tarek Ziadé4450dcf2008-12-29 22:38:38 +0000235 if options is not None:
Greg Wardfe6462c2000-04-04 01:40:52 +0000236 del attrs['options']
237 for (command, cmd_options) in options.items():
Greg Ward0e48cfd2000-05-26 01:00:15 +0000238 opt_dict = self.get_option_dict(command)
239 for (opt, val) in cmd_options.items():
240 opt_dict[opt] = ("setup script", val)
Greg Wardfe6462c2000-04-04 01:40:52 +0000241
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000242 if 'licence' in attrs:
Andrew M. Kuchlinga52b8522003-03-03 20:07:27 +0000243 attrs['license'] = attrs['licence']
244 del attrs['licence']
245 msg = "'licence' distribution option is deprecated; use 'license'"
246 if warnings is not None:
247 warnings.warn(msg)
248 else:
249 sys.stderr.write(msg + "\n")
250
Greg Wardfe6462c2000-04-04 01:40:52 +0000251 # Now work on the rest of the attributes. Any attribute that's
252 # not already defined is invalid!
Tarek Ziadéf11be752009-06-01 22:36:26 +0000253 for (key, val) in attrs.items():
Fred Drakedb7b0022005-03-20 22:19:47 +0000254 if hasattr(self.metadata, "set_" + key):
255 getattr(self.metadata, "set_" + key)(val)
256 elif hasattr(self.metadata, key):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000257 setattr(self.metadata, key, val)
258 elif hasattr(self, key):
259 setattr(self, key, val)
Anthony Baxter73cc8472004-10-13 13:22:34 +0000260 else:
Andrew M. Kuchlingff4ad9a2002-10-31 13:22:41 +0000261 msg = "Unknown distribution option: %s" % repr(key)
262 if warnings is not None:
263 warnings.warn(msg)
264 else:
265 sys.stderr.write(msg + "\n")
Greg Wardfe6462c2000-04-04 01:40:52 +0000266
Tarek Ziadéc7c71ff2009-10-27 23:12:01 +0000267 # no-user-cfg is handled before other command line args
268 # because other args override the config files, and this
269 # one is needed before we can load the config files.
270 # If attrs['script_args'] wasn't passed, assume false.
271 #
272 # This also make sure we just look at the global options
273 self.want_user_cfg = True
274
275 if self.script_args is not None:
276 for arg in self.script_args:
277 if not arg.startswith('-'):
278 break
279 if arg == '--no-user-cfg':
280 self.want_user_cfg = False
281 break
282
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000283 self.finalize_options()
Fred Drakeb94b8492001-12-06 20:51:35 +0000284
Tarek Ziadé188789d2009-05-16 18:37:32 +0000285 def get_option_dict(self, command):
Greg Ward0e48cfd2000-05-26 01:00:15 +0000286 """Get the option dictionary for a given command. If that
287 command's option dictionary hasn't been created yet, then create it
288 and return the new dictionary; otherwise, return the existing
289 option dictionary.
290 """
Greg Ward0e48cfd2000-05-26 01:00:15 +0000291 dict = self.command_options.get(command)
292 if dict is None:
293 dict = self.command_options[command] = {}
294 return dict
295
Tarek Ziadé188789d2009-05-16 18:37:32 +0000296 def dump_option_dicts(self, header=None, commands=None, indent=""):
Greg Wardc32d9a62000-05-28 23:53:06 +0000297 from pprint import pformat
298
299 if commands is None: # dump all command option dicts
Guido van Rossumd4ee1672007-10-15 01:27:53 +0000300 commands = sorted(self.command_options.keys())
Greg Wardc32d9a62000-05-28 23:53:06 +0000301
302 if header is not None:
Tarek Ziadéf11be752009-06-01 22:36:26 +0000303 self.announce(indent + header)
Greg Wardc32d9a62000-05-28 23:53:06 +0000304 indent = indent + " "
305
306 if not commands:
Tarek Ziadéf11be752009-06-01 22:36:26 +0000307 self.announce(indent + "no commands known yet")
Greg Wardc32d9a62000-05-28 23:53:06 +0000308 return
309
310 for cmd_name in commands:
311 opt_dict = self.command_options.get(cmd_name)
312 if opt_dict is None:
Tarek Ziadéf11be752009-06-01 22:36:26 +0000313 self.announce(indent +
314 "no option dict for '%s' command" % cmd_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000315 else:
Tarek Ziadéf11be752009-06-01 22:36:26 +0000316 self.announce(indent +
317 "option dict for '%s' command:" % cmd_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000318 out = pformat(opt_dict)
Tarek Ziadéf11be752009-06-01 22:36:26 +0000319 for line in out.split('\n'):
320 self.announce(indent + " " + line)
Greg Wardc32d9a62000-05-28 23:53:06 +0000321
Greg Wardd5d8a992000-05-23 01:42:17 +0000322 # -- Config file finding/parsing methods ---------------------------
323
Tarek Ziadé188789d2009-05-16 18:37:32 +0000324 def find_config_files(self):
Gregory P. Smith14263542000-05-12 00:41:33 +0000325 """Find as many configuration files as should be processed for this
326 platform, and return a list of filenames in the order in which they
327 should be parsed. The filenames returned are guaranteed to exist
328 (modulo nasty race conditions).
329
Andrew M. Kuchlingd303b612001-12-06 16:32:05 +0000330 There are three possible config files: distutils.cfg in the
331 Distutils installation directory (ie. where the top-level
332 Distutils __inst__.py file lives), a file in the user's home
333 directory named .pydistutils.cfg on Unix and pydistutils.cfg
Tarek Ziadéc7c71ff2009-10-27 23:12:01 +0000334 on Windows/Mac; and setup.cfg in the current directory.
335
336 The file in the user's home directory can be disabled with the
337 --no-user-cfg option.
Greg Wardd5d8a992000-05-23 01:42:17 +0000338 """
Gregory P. Smith14263542000-05-12 00:41:33 +0000339 files = []
Greg Wardacf3f6a2000-06-07 02:26:19 +0000340 check_environ()
Gregory P. Smith14263542000-05-12 00:41:33 +0000341
Greg Ward11696872000-06-07 02:29:03 +0000342 # Where to look for the system-wide Distutils config file
343 sys_dir = os.path.dirname(sys.modules['distutils'].__file__)
344
345 # Look for the system config file
346 sys_file = os.path.join(sys_dir, "distutils.cfg")
Greg Wardacf3f6a2000-06-07 02:26:19 +0000347 if os.path.isfile(sys_file):
348 files.append(sys_file)
Gregory P. Smith14263542000-05-12 00:41:33 +0000349
Greg Ward11696872000-06-07 02:29:03 +0000350 # What to call the per-user config file
351 if os.name == 'posix':
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000352 user_filename = ".pydistutils.cfg"
353 else:
354 user_filename = "pydistutils.cfg"
Greg Wardfa9ff762000-10-14 04:06:40 +0000355
Greg Ward11696872000-06-07 02:29:03 +0000356 # And look for the user config file
Tarek Ziadéc7c71ff2009-10-27 23:12:01 +0000357 if self.want_user_cfg:
358 user_file = os.path.join(os.path.expanduser('~'), user_filename)
359 if os.path.isfile(user_file):
360 files.append(user_file)
Gregory P. Smith14263542000-05-12 00:41:33 +0000361
Gregory P. Smith14263542000-05-12 00:41:33 +0000362 # All platforms support local setup.cfg
363 local_file = "setup.cfg"
364 if os.path.isfile(local_file):
365 files.append(local_file)
366
Tarek Ziadéc7c71ff2009-10-27 23:12:01 +0000367 if DEBUG:
368 self.announce("using config files: %s" % ', '.join(files))
369
Gregory P. Smith14263542000-05-12 00:41:33 +0000370 return files
371
Tarek Ziadé188789d2009-05-16 18:37:32 +0000372 def parse_config_files(self, filenames=None):
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000373 from configparser import ConfigParser
Gregory P. Smith14263542000-05-12 00:41:33 +0000374
375 if filenames is None:
376 filenames = self.find_config_files()
377
Tarek Ziadéf11be752009-06-01 22:36:26 +0000378 if DEBUG:
379 self.announce("Distribution.parse_config_files():")
Greg Ward47460772000-05-23 03:47:35 +0000380
Gregory P. Smith14263542000-05-12 00:41:33 +0000381 parser = ConfigParser()
Greg Wardd5d8a992000-05-23 01:42:17 +0000382 for filename in filenames:
Tarek Ziadéf11be752009-06-01 22:36:26 +0000383 if DEBUG:
Tarek Ziadé31d46072009-09-21 13:55:19 +0000384 self.announce(" reading %s" % filename)
Greg Wardd5d8a992000-05-23 01:42:17 +0000385 parser.read(filename)
386 for section in parser.sections():
387 options = parser.options(section)
Greg Ward0e48cfd2000-05-26 01:00:15 +0000388 opt_dict = self.get_option_dict(section)
Gregory P. Smith14263542000-05-12 00:41:33 +0000389
Greg Wardd5d8a992000-05-23 01:42:17 +0000390 for opt in options:
391 if opt != '__name__':
Greg Wardceb9e222000-09-25 01:23:52 +0000392 val = parser.get(section,opt)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000393 opt = opt.replace('-', '_')
Greg Wardceb9e222000-09-25 01:23:52 +0000394 opt_dict[opt] = (filename, val)
Gregory P. Smith14263542000-05-12 00:41:33 +0000395
Greg Ward47460772000-05-23 03:47:35 +0000396 # Make the ConfigParser forget everything (so we retain
Fred Drakef06116d2004-02-17 22:35:19 +0000397 # the original filenames that options come from)
Greg Ward47460772000-05-23 03:47:35 +0000398 parser.__init__()
Gregory P. Smith14263542000-05-12 00:41:33 +0000399
Greg Wardceb9e222000-09-25 01:23:52 +0000400 # If there was a "global" section in the config file, use it
401 # to set Distribution options.
402
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000403 if 'global' in self.command_options:
Greg Wardceb9e222000-09-25 01:23:52 +0000404 for (opt, (src, val)) in self.command_options['global'].items():
405 alias = self.negative_opt.get(opt)
406 try:
407 if alias:
408 setattr(self, alias, not strtobool(val))
409 elif opt in ('verbose', 'dry_run'): # ugh!
410 setattr(self, opt, strtobool(val))
Fred Draked04573f2004-08-03 16:37:40 +0000411 else:
412 setattr(self, opt, val)
Guido van Rossumb940e112007-01-10 16:19:56 +0000413 except ValueError as msg:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000414 raise DistutilsOptionError(msg)
Greg Wardceb9e222000-09-25 01:23:52 +0000415
Greg Wardd5d8a992000-05-23 01:42:17 +0000416 # -- Command-line parsing methods ----------------------------------
417
Tarek Ziadé188789d2009-05-16 18:37:32 +0000418 def parse_command_line(self):
Greg Ward9821bf42000-08-29 01:15:18 +0000419 """Parse the setup script's command line, taken from the
420 'script_args' instance attribute (which defaults to 'sys.argv[1:]'
421 -- see 'setup()' in core.py). This list is first processed for
422 "global options" -- options that set attributes of the Distribution
423 instance. Then, it is alternately scanned for Distutils commands
424 and options for that command. Each new command terminates the
425 options for the previous command. The allowed options for a
426 command are determined by the 'user_options' attribute of the
427 command class -- thus, we have to be able to load command classes
428 in order to parse the command line. Any error in that 'options'
429 attribute raises DistutilsGetoptError; any error on the
430 command-line raises DistutilsArgError. If no Distutils commands
431 were found on the command line, raises DistutilsArgError. Return
Greg Wardceb9e222000-09-25 01:23:52 +0000432 true if command-line was successfully parsed and we should carry
Greg Ward9821bf42000-08-29 01:15:18 +0000433 on with executing commands; false if no errors but we shouldn't
434 execute commands (currently, this only happens if user asks for
435 help).
Greg Wardd5d8a992000-05-23 01:42:17 +0000436 """
Andrew M. Kuchling3f819ec2001-01-15 16:09:35 +0000437 #
Fred Drake981a1782001-08-10 18:59:30 +0000438 # We now have enough information to show the Macintosh dialog
439 # that allows the user to interactively specify the "command line".
Andrew M. Kuchling3f819ec2001-01-15 16:09:35 +0000440 #
Fred Draked04573f2004-08-03 16:37:40 +0000441 toplevel_options = self._get_toplevel_options()
Fred Drakeb94b8492001-12-06 20:51:35 +0000442
Greg Wardfe6462c2000-04-04 01:40:52 +0000443 # We have to parse the command line a bit at a time -- global
444 # options, then the first command, then its options, and so on --
445 # because each command will be handled by a different class, and
Greg Wardd5d8a992000-05-23 01:42:17 +0000446 # the options that are valid for a particular class aren't known
447 # until we have loaded the command class, which doesn't happen
448 # until we know what the command is.
Greg Wardfe6462c2000-04-04 01:40:52 +0000449
450 self.commands = []
Fred Draked04573f2004-08-03 16:37:40 +0000451 parser = FancyGetopt(toplevel_options + self.display_options)
Greg Wardfd7b91e2000-09-26 01:52:25 +0000452 parser.set_negative_aliases(self.negative_opt)
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +0000453 parser.set_aliases({'licence': 'license'})
Greg Wardfd7b91e2000-09-26 01:52:25 +0000454 args = parser.getopt(args=self.script_args, object=self)
Greg Ward82715e12000-04-21 02:28:14 +0000455 option_order = parser.get_option_order()
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000456 log.set_verbosity(self.verbose)
Greg Wardfe6462c2000-04-04 01:40:52 +0000457
Greg Ward82715e12000-04-21 02:28:14 +0000458 # for display options we return immediately
459 if self.handle_display_options(option_order):
Greg Wardfe6462c2000-04-04 01:40:52 +0000460 return
Greg Wardfe6462c2000-04-04 01:40:52 +0000461 while args:
Greg Wardd5d8a992000-05-23 01:42:17 +0000462 args = self._parse_command_opts(parser, args)
463 if args is None: # user asked for help (and got it)
Greg Wardfe6462c2000-04-04 01:40:52 +0000464 return
Greg Wardfe6462c2000-04-04 01:40:52 +0000465
Greg Wardd5d8a992000-05-23 01:42:17 +0000466 # Handle the cases of --help as a "global" option, ie.
467 # "setup.py --help" and "setup.py --help command ...". For the
468 # former, we show global options (--verbose, --dry-run, etc.)
469 # and display-only options (--name, --version, etc.); for the
470 # latter, we omit the display-only options and show help for
471 # each command listed on the command line.
Greg Wardfe6462c2000-04-04 01:40:52 +0000472 if self.help:
Greg Wardd5d8a992000-05-23 01:42:17 +0000473 self._show_help(parser,
474 display_options=len(self.commands) == 0,
475 commands=self.commands)
Greg Wardfe6462c2000-04-04 01:40:52 +0000476 return
477
478 # Oops, no commands found -- an end-user error
479 if not self.commands:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000480 raise DistutilsArgError("no commands supplied")
Greg Wardfe6462c2000-04-04 01:40:52 +0000481
482 # All is well: return true
Collin Winter5b7e9d72007-08-30 03:52:21 +0000483 return True
Greg Wardfe6462c2000-04-04 01:40:52 +0000484
Tarek Ziadé188789d2009-05-16 18:37:32 +0000485 def _get_toplevel_options(self):
Fred Draked04573f2004-08-03 16:37:40 +0000486 """Return the non-display options recognized at the top level.
487
488 This includes options that are recognized *only* at the top
489 level as well as options recognized for commands.
490 """
491 return self.global_options + [
492 ("command-packages=", None,
493 "list of packages that provide distutils commands"),
494 ]
495
Tarek Ziadé188789d2009-05-16 18:37:32 +0000496 def _parse_command_opts(self, parser, args):
Greg Wardd5d8a992000-05-23 01:42:17 +0000497 """Parse the command-line options for a single command.
498 'parser' must be a FancyGetopt instance; 'args' must be the list
499 of arguments, starting with the current command (whose options
500 we are about to parse). Returns a new version of 'args' with
501 the next command at the front of the list; will be the empty
502 list if there are no more commands on the command line. Returns
503 None if the user asked for help on this command.
504 """
505 # late import because of mutual dependence between these modules
506 from distutils.cmd import Command
507
508 # Pull the current command from the head of the command line
509 command = args[0]
Greg Wardfd7b91e2000-09-26 01:52:25 +0000510 if not command_re.match(command):
Collin Winter5b7e9d72007-08-30 03:52:21 +0000511 raise SystemExit("invalid command name '%s'" % command)
Greg Wardfd7b91e2000-09-26 01:52:25 +0000512 self.commands.append(command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000513
514 # Dig up the command class that implements this command, so we
515 # 1) know that it's a valid command, and 2) know which options
516 # it takes.
517 try:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000518 cmd_class = self.get_command_class(command)
Guido van Rossumb940e112007-01-10 16:19:56 +0000519 except DistutilsModuleError as msg:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000520 raise DistutilsArgError(msg)
Greg Wardd5d8a992000-05-23 01:42:17 +0000521
522 # Require that the command class be derived from Command -- want
523 # to be sure that the basic "command" interface is implemented.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000524 if not issubclass(cmd_class, Command):
Collin Winter5b7e9d72007-08-30 03:52:21 +0000525 raise DistutilsClassError(
526 "command class %s must subclass Command" % cmd_class)
Greg Wardd5d8a992000-05-23 01:42:17 +0000527
528 # Also make sure that the command object provides a list of its
529 # known options.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000530 if not (hasattr(cmd_class, 'user_options') and
Guido van Rossum13257902007-06-07 23:15:56 +0000531 isinstance(cmd_class.user_options, list)):
Collin Winter5b7e9d72007-08-30 03:52:21 +0000532 raise DistutilsClassError(("command class %s must provide " +
Greg Wardd5d8a992000-05-23 01:42:17 +0000533 "'user_options' attribute (a list of tuples)") % \
Collin Winter5b7e9d72007-08-30 03:52:21 +0000534 cmd_class)
Greg Wardd5d8a992000-05-23 01:42:17 +0000535
536 # If the command class has a list of negative alias options,
537 # merge it in with the global negative aliases.
538 negative_opt = self.negative_opt
Greg Wardfd7b91e2000-09-26 01:52:25 +0000539 if hasattr(cmd_class, 'negative_opt'):
Antoine Pitrou56a00de2009-05-15 17:34:21 +0000540 negative_opt = negative_opt.copy()
Greg Wardfd7b91e2000-09-26 01:52:25 +0000541 negative_opt.update(cmd_class.negative_opt)
Greg Wardd5d8a992000-05-23 01:42:17 +0000542
Greg Wardfa9ff762000-10-14 04:06:40 +0000543 # Check for help_options in command class. They have a different
544 # format (tuple of four) so we need to preprocess them here.
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000545 if (hasattr(cmd_class, 'help_options') and
Guido van Rossum13257902007-06-07 23:15:56 +0000546 isinstance(cmd_class.help_options, list)):
Greg Ward2ff78872000-06-24 00:23:20 +0000547 help_options = fix_help_options(cmd_class.help_options)
548 else:
Greg Ward55fced32000-06-24 01:22:41 +0000549 help_options = []
Greg Ward2ff78872000-06-24 00:23:20 +0000550
Greg Ward9d17a7a2000-06-07 03:00:06 +0000551
Greg Wardd5d8a992000-05-23 01:42:17 +0000552 # All commands support the global options too, just by adding
553 # in 'global_options'.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000554 parser.set_option_table(self.global_options +
555 cmd_class.user_options +
556 help_options)
557 parser.set_negative_aliases(negative_opt)
558 (args, opts) = parser.getopt(args[1:])
Greg Ward47460772000-05-23 03:47:35 +0000559 if hasattr(opts, 'help') and opts.help:
Greg Wardd5d8a992000-05-23 01:42:17 +0000560 self._show_help(parser, display_options=0, commands=[cmd_class])
561 return
562
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000563 if (hasattr(cmd_class, 'help_options') and
Guido van Rossum13257902007-06-07 23:15:56 +0000564 isinstance(cmd_class.help_options, list)):
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000565 help_option_found=0
566 for (help_option, short, desc, func) in cmd_class.help_options:
567 if hasattr(opts, parser.get_attr_name(help_option)):
568 help_option_found=1
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000569 if hasattr(func, '__call__'):
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000570 func()
Greg Ward55fced32000-06-24 01:22:41 +0000571 else:
Fred Drake981a1782001-08-10 18:59:30 +0000572 raise DistutilsClassError(
Walter Dörwald70a6b492004-02-12 17:35:32 +0000573 "invalid help function %r for help option '%s': "
Fred Drake981a1782001-08-10 18:59:30 +0000574 "must be a callable object (function, etc.)"
Walter Dörwald70a6b492004-02-12 17:35:32 +0000575 % (func, help_option))
Greg Ward55fced32000-06-24 01:22:41 +0000576
Fred Drakeb94b8492001-12-06 20:51:35 +0000577 if help_option_found:
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000578 return
Greg Ward9d17a7a2000-06-07 03:00:06 +0000579
Greg Wardd5d8a992000-05-23 01:42:17 +0000580 # Put the options from the command-line into their official
581 # holding pen, the 'command_options' dictionary.
Greg Ward0e48cfd2000-05-26 01:00:15 +0000582 opt_dict = self.get_option_dict(command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000583 for (name, value) in vars(opts).items():
Greg Ward0e48cfd2000-05-26 01:00:15 +0000584 opt_dict[name] = ("command line", value)
Greg Wardd5d8a992000-05-23 01:42:17 +0000585
586 return args
587
Tarek Ziadé188789d2009-05-16 18:37:32 +0000588 def finalize_options(self):
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000589 """Set final values for all the options on the Distribution
590 instance, analogous to the .finalize_options() method of Command
591 objects.
592 """
Tarek Ziadéf11be752009-06-01 22:36:26 +0000593 for attr in ('keywords', 'platforms'):
594 value = getattr(self.metadata, attr)
595 if value is None:
596 continue
597 if isinstance(value, str):
598 value = [elm.strip() for elm in value.split(',')]
599 setattr(self.metadata, attr, value)
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000600
Tarek Ziadé188789d2009-05-16 18:37:32 +0000601 def _show_help(self, parser, global_options=1, display_options=1,
602 commands=[]):
Greg Wardd5d8a992000-05-23 01:42:17 +0000603 """Show help for the setup script command-line in the form of
604 several lists of command-line options. 'parser' should be a
605 FancyGetopt instance; do not expect it to be returned in the
606 same state, as its option table will be reset to make it
607 generate the correct help text.
608
609 If 'global_options' is true, lists the global options:
610 --verbose, --dry-run, etc. If 'display_options' is true, lists
611 the "display-only" options: --name, --version, etc. Finally,
612 lists per-command help for every command name or command class
613 in 'commands'.
614 """
615 # late import because of mutual dependence between these modules
Greg Ward9821bf42000-08-29 01:15:18 +0000616 from distutils.core import gen_usage
Greg Wardd5d8a992000-05-23 01:42:17 +0000617 from distutils.cmd import Command
618
619 if global_options:
Fred Draked04573f2004-08-03 16:37:40 +0000620 if display_options:
621 options = self._get_toplevel_options()
622 else:
623 options = self.global_options
624 parser.set_option_table(options)
Martin v. Löwis8ed338a2005-03-03 08:12:27 +0000625 parser.print_help(self.common_usage + "\nGlobal options:")
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000626 print('')
Greg Wardd5d8a992000-05-23 01:42:17 +0000627
628 if display_options:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000629 parser.set_option_table(self.display_options)
630 parser.print_help(
Greg Wardd5d8a992000-05-23 01:42:17 +0000631 "Information display options (just display " +
632 "information, ignore any commands)")
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000633 print('')
Greg Wardd5d8a992000-05-23 01:42:17 +0000634
635 for command in self.commands:
Guido van Rossum13257902007-06-07 23:15:56 +0000636 if isinstance(command, type) and issubclass(command, Command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000637 klass = command
638 else:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000639 klass = self.get_command_class(command)
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000640 if (hasattr(klass, 'help_options') and
Guido van Rossum13257902007-06-07 23:15:56 +0000641 isinstance(klass.help_options, list)):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000642 parser.set_option_table(klass.user_options +
643 fix_help_options(klass.help_options))
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000644 else:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000645 parser.set_option_table(klass.user_options)
646 parser.print_help("Options for '%s' command:" % klass.__name__)
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000647 print('')
Greg Wardd5d8a992000-05-23 01:42:17 +0000648
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000649 print(gen_usage(self.script_name))
Greg Wardd5d8a992000-05-23 01:42:17 +0000650
Tarek Ziadé188789d2009-05-16 18:37:32 +0000651 def handle_display_options(self, option_order):
Greg Ward82715e12000-04-21 02:28:14 +0000652 """If there were any non-global "display-only" options
Greg Wardd5d8a992000-05-23 01:42:17 +0000653 (--help-commands or the metadata display options) on the command
654 line, display the requested info and return true; else return
655 false.
656 """
Greg Ward9821bf42000-08-29 01:15:18 +0000657 from distutils.core import gen_usage
Greg Ward82715e12000-04-21 02:28:14 +0000658
659 # User just wants a list of commands -- we'll print it out and stop
660 # processing now (ie. if they ran "setup --help-commands foo bar",
661 # we ignore "foo bar").
662 if self.help_commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000663 self.print_commands()
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000664 print('')
665 print(gen_usage(self.script_name))
Greg Ward82715e12000-04-21 02:28:14 +0000666 return 1
667
668 # If user supplied any of the "display metadata" options, then
669 # display that metadata in the order in which the user supplied the
670 # metadata options.
671 any_display_options = 0
672 is_display_option = {}
673 for option in self.display_options:
674 is_display_option[option[0]] = 1
675
676 for (opt, val) in option_order:
677 if val and is_display_option.get(opt):
Greg Ward2f2b6c62000-09-25 01:58:07 +0000678 opt = translate_longopt(opt)
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000679 value = getattr(self.metadata, "get_"+opt)()
680 if opt in ['keywords', 'platforms']:
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000681 print(','.join(value))
Fred Drakedb7b0022005-03-20 22:19:47 +0000682 elif opt in ('classifiers', 'provides', 'requires',
683 'obsoletes'):
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000684 print('\n'.join(value))
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000685 else:
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000686 print(value)
Greg Ward82715e12000-04-21 02:28:14 +0000687 any_display_options = 1
688
689 return any_display_options
690
Tarek Ziadé188789d2009-05-16 18:37:32 +0000691 def print_command_list(self, commands, header, max_length):
Greg Wardfe6462c2000-04-04 01:40:52 +0000692 """Print a subset of the list of all commands -- used by
Greg Wardd5d8a992000-05-23 01:42:17 +0000693 'print_commands()'.
694 """
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000695 print(header + ":")
Greg Wardfe6462c2000-04-04 01:40:52 +0000696
697 for cmd in commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000698 klass = self.cmdclass.get(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000699 if not klass:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000700 klass = self.get_command_class(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000701 try:
702 description = klass.description
703 except AttributeError:
704 description = "(no description available)"
705
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000706 print(" %-*s %s" % (max_length, cmd, description))
Greg Wardfe6462c2000-04-04 01:40:52 +0000707
Tarek Ziadé188789d2009-05-16 18:37:32 +0000708 def print_commands(self):
Greg Wardd5d8a992000-05-23 01:42:17 +0000709 """Print out a help message listing all available commands with a
710 description of each. The list is divided into "standard commands"
711 (listed in distutils.command.__all__) and "extra commands"
712 (mentioned in self.cmdclass, but not a standard command). The
713 descriptions come from the command class attribute
714 'description'.
715 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000716 import distutils.command
717 std_commands = distutils.command.__all__
718 is_std = {}
719 for cmd in std_commands:
720 is_std[cmd] = 1
721
722 extra_commands = []
723 for cmd in self.cmdclass.keys():
724 if not is_std.get(cmd):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000725 extra_commands.append(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000726
727 max_length = 0
728 for cmd in (std_commands + extra_commands):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000729 if len(cmd) > max_length:
730 max_length = len(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000731
Greg Wardfd7b91e2000-09-26 01:52:25 +0000732 self.print_command_list(std_commands,
733 "Standard commands",
734 max_length)
Greg Wardfe6462c2000-04-04 01:40:52 +0000735 if extra_commands:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000736 print()
Greg Wardfd7b91e2000-09-26 01:52:25 +0000737 self.print_command_list(extra_commands,
738 "Extra commands",
739 max_length)
Greg Wardfe6462c2000-04-04 01:40:52 +0000740
Tarek Ziadé188789d2009-05-16 18:37:32 +0000741 def get_command_list(self):
Greg Wardf6fc8752000-11-11 02:47:11 +0000742 """Get a list of (command, description) tuples.
743 The list is divided into "standard commands" (listed in
744 distutils.command.__all__) and "extra commands" (mentioned in
745 self.cmdclass, but not a standard command). The descriptions come
746 from the command class attribute 'description'.
747 """
748 # Currently this is only used on Mac OS, for the Mac-only GUI
749 # Distutils interface (by Jack Jansen)
Greg Wardf6fc8752000-11-11 02:47:11 +0000750 import distutils.command
751 std_commands = distutils.command.__all__
752 is_std = {}
753 for cmd in std_commands:
754 is_std[cmd] = 1
755
756 extra_commands = []
757 for cmd in self.cmdclass.keys():
758 if not is_std.get(cmd):
759 extra_commands.append(cmd)
760
761 rv = []
762 for cmd in (std_commands + extra_commands):
763 klass = self.cmdclass.get(cmd)
764 if not klass:
765 klass = self.get_command_class(cmd)
766 try:
767 description = klass.description
768 except AttributeError:
769 description = "(no description available)"
770 rv.append((cmd, description))
771 return rv
Greg Wardfe6462c2000-04-04 01:40:52 +0000772
773 # -- Command class/object methods ----------------------------------
774
Tarek Ziadé188789d2009-05-16 18:37:32 +0000775 def get_command_packages(self):
Fred Draked04573f2004-08-03 16:37:40 +0000776 """Return a list of packages from which commands are loaded."""
777 pkgs = self.command_packages
Tarek Ziadéf11be752009-06-01 22:36:26 +0000778 if not isinstance(pkgs, list):
779 if pkgs is None:
780 pkgs = ''
781 pkgs = [pkg.strip() for pkg in pkgs.split(',') if pkg != '']
Fred Draked04573f2004-08-03 16:37:40 +0000782 if "distutils.command" not in pkgs:
783 pkgs.insert(0, "distutils.command")
784 self.command_packages = pkgs
785 return pkgs
786
Tarek Ziadé188789d2009-05-16 18:37:32 +0000787 def get_command_class(self, command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000788 """Return the class that implements the Distutils command named by
789 'command'. First we check the 'cmdclass' dictionary; if the
790 command is mentioned there, we fetch the class object from the
791 dictionary and return it. Otherwise we load the command module
792 ("distutils.command." + command) and fetch the command class from
793 the module. The loaded class is also stored in 'cmdclass'
794 to speed future calls to 'get_command_class()'.
Greg Wardfe6462c2000-04-04 01:40:52 +0000795
Gregory P. Smith14263542000-05-12 00:41:33 +0000796 Raises DistutilsModuleError if the expected module could not be
Greg Wardd5d8a992000-05-23 01:42:17 +0000797 found, or if that module does not define the expected class.
798 """
799 klass = self.cmdclass.get(command)
800 if klass:
801 return klass
Greg Wardfe6462c2000-04-04 01:40:52 +0000802
Fred Draked04573f2004-08-03 16:37:40 +0000803 for pkgname in self.get_command_packages():
804 module_name = "%s.%s" % (pkgname, command)
805 klass_name = command
Greg Wardfe6462c2000-04-04 01:40:52 +0000806
Fred Draked04573f2004-08-03 16:37:40 +0000807 try:
808 __import__ (module_name)
809 module = sys.modules[module_name]
810 except ImportError:
811 continue
Greg Wardfe6462c2000-04-04 01:40:52 +0000812
Fred Draked04573f2004-08-03 16:37:40 +0000813 try:
814 klass = getattr(module, klass_name)
815 except AttributeError:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000816 raise DistutilsModuleError(
817 "invalid command '%s' (no class '%s' in module '%s')"
818 % (command, klass_name, module_name))
Greg Wardfe6462c2000-04-04 01:40:52 +0000819
Fred Draked04573f2004-08-03 16:37:40 +0000820 self.cmdclass[command] = klass
821 return klass
822
823 raise DistutilsModuleError("invalid command '%s'" % command)
824
Tarek Ziadé188789d2009-05-16 18:37:32 +0000825 def get_command_obj(self, command, create=1):
Greg Wardd5d8a992000-05-23 01:42:17 +0000826 """Return the command object for 'command'. Normally this object
Greg Ward612eb9f2000-07-27 02:13:20 +0000827 is cached on a previous call to 'get_command_obj()'; if no command
Greg Wardd5d8a992000-05-23 01:42:17 +0000828 object for 'command' is in the cache, then we either create and
829 return it (if 'create' is true) or return None.
830 """
831 cmd_obj = self.command_obj.get(command)
Greg Wardfe6462c2000-04-04 01:40:52 +0000832 if not cmd_obj and create:
Greg Ward2bd3f422000-06-02 01:59:33 +0000833 if DEBUG:
Tarek Ziadéf11be752009-06-01 22:36:26 +0000834 self.announce("Distribution.get_command_obj(): " \
835 "creating '%s' command object" % command)
Greg Ward47460772000-05-23 03:47:35 +0000836
Greg Wardd5d8a992000-05-23 01:42:17 +0000837 klass = self.get_command_class(command)
Greg Ward47460772000-05-23 03:47:35 +0000838 cmd_obj = self.command_obj[command] = klass(self)
839 self.have_run[command] = 0
840
841 # Set any options that were supplied in config files
842 # or on the command line. (NB. support for error
843 # reporting is lame here: any errors aren't reported
844 # until 'finalize_options()' is called, which means
845 # we won't report the source of the error.)
846 options = self.command_options.get(command)
847 if options:
Greg Wardc32d9a62000-05-28 23:53:06 +0000848 self._set_command_options(cmd_obj, options)
Greg Wardfe6462c2000-04-04 01:40:52 +0000849
850 return cmd_obj
851
Tarek Ziadé188789d2009-05-16 18:37:32 +0000852 def _set_command_options(self, command_obj, option_dict=None):
Greg Wardc32d9a62000-05-28 23:53:06 +0000853 """Set the options for 'command_obj' from 'option_dict'. Basically
854 this means copying elements of a dictionary ('option_dict') to
855 attributes of an instance ('command').
856
Greg Wardceb9e222000-09-25 01:23:52 +0000857 'command_obj' must be a Command instance. If 'option_dict' is not
Greg Wardc32d9a62000-05-28 23:53:06 +0000858 supplied, uses the standard option dictionary for this command
859 (from 'self.command_options').
860 """
Greg Wardc32d9a62000-05-28 23:53:06 +0000861 command_name = command_obj.get_command_name()
862 if option_dict is None:
863 option_dict = self.get_option_dict(command_name)
864
Tarek Ziadéf11be752009-06-01 22:36:26 +0000865 if DEBUG:
866 self.announce(" setting options for '%s' command:" % command_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000867 for (option, (source, value)) in option_dict.items():
Tarek Ziadéf11be752009-06-01 22:36:26 +0000868 if DEBUG:
869 self.announce(" %s = %s (from %s)" % (option, value,
870 source))
Greg Wardceb9e222000-09-25 01:23:52 +0000871 try:
Amaury Forgeot d'Arc61cb0872008-07-26 20:09:45 +0000872 bool_opts = [translate_longopt(o)
873 for o in command_obj.boolean_options]
Greg Wardceb9e222000-09-25 01:23:52 +0000874 except AttributeError:
875 bool_opts = []
876 try:
877 neg_opt = command_obj.negative_opt
878 except AttributeError:
879 neg_opt = {}
880
881 try:
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000882 is_string = isinstance(value, str)
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000883 if option in neg_opt and is_string:
Greg Wardceb9e222000-09-25 01:23:52 +0000884 setattr(command_obj, neg_opt[option], not strtobool(value))
Greg Ward2c08cf02000-09-27 00:15:37 +0000885 elif option in bool_opts and is_string:
Greg Wardceb9e222000-09-25 01:23:52 +0000886 setattr(command_obj, option, strtobool(value))
887 elif hasattr(command_obj, option):
888 setattr(command_obj, option, value)
889 else:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000890 raise DistutilsOptionError(
891 "error in %s: command '%s' has no such option '%s'"
892 % (source, command_name, option))
Guido van Rossumb940e112007-01-10 16:19:56 +0000893 except ValueError as msg:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000894 raise DistutilsOptionError(msg)
Greg Wardc32d9a62000-05-28 23:53:06 +0000895
Tarek Ziadé188789d2009-05-16 18:37:32 +0000896 def reinitialize_command(self, command, reinit_subcommands=0):
Greg Wardc32d9a62000-05-28 23:53:06 +0000897 """Reinitializes a command to the state it was in when first
898 returned by 'get_command_obj()': ie., initialized but not yet
Greg Ward7d9c7052000-06-28 01:25:27 +0000899 finalized. This provides the opportunity to sneak option
Greg Wardc32d9a62000-05-28 23:53:06 +0000900 values in programmatically, overriding or supplementing
901 user-supplied values from the config files and command line.
902 You'll have to re-finalize the command object (by calling
903 'finalize_options()' or 'ensure_finalized()') before using it for
Fred Drakeb94b8492001-12-06 20:51:35 +0000904 real.
Greg Wardc32d9a62000-05-28 23:53:06 +0000905
Greg Wardf449ea52000-09-16 15:23:28 +0000906 'command' should be a command name (string) or command object. If
907 'reinit_subcommands' is true, also reinitializes the command's
908 sub-commands, as declared by the 'sub_commands' class attribute (if
909 it has one). See the "install" command for an example. Only
910 reinitializes the sub-commands that actually matter, ie. those
911 whose test predicates return true.
912
Greg Wardc32d9a62000-05-28 23:53:06 +0000913 Returns the reinitialized command object.
914 """
915 from distutils.cmd import Command
916 if not isinstance(command, Command):
917 command_name = command
918 command = self.get_command_obj(command_name)
919 else:
920 command_name = command.get_command_name()
921
922 if not command.finalized:
Greg Ward282c7a02000-06-01 01:09:47 +0000923 return command
Greg Wardc32d9a62000-05-28 23:53:06 +0000924 command.initialize_options()
925 command.finalized = 0
Greg Ward43955c92000-06-06 02:52:36 +0000926 self.have_run[command_name] = 0
Greg Wardc32d9a62000-05-28 23:53:06 +0000927 self._set_command_options(command)
Greg Wardf449ea52000-09-16 15:23:28 +0000928
Greg Wardf449ea52000-09-16 15:23:28 +0000929 if reinit_subcommands:
Greg Wardf449ea52000-09-16 15:23:28 +0000930 for sub in command.get_sub_commands():
Fred Drakeb94b8492001-12-06 20:51:35 +0000931 self.reinitialize_command(sub, reinit_subcommands)
Greg Wardf449ea52000-09-16 15:23:28 +0000932
Greg Wardc32d9a62000-05-28 23:53:06 +0000933 return command
934
Greg Wardfe6462c2000-04-04 01:40:52 +0000935 # -- Methods that operate on the Distribution ----------------------
936
Tarek Ziadé05bf01a2009-07-04 02:04:21 +0000937 def announce(self, msg, level=log.INFO):
938 log.log(level, msg)
Greg Wardfe6462c2000-04-04 01:40:52 +0000939
Tarek Ziadé188789d2009-05-16 18:37:32 +0000940 def run_commands(self):
Greg Ward82715e12000-04-21 02:28:14 +0000941 """Run each command that was seen on the setup script command line.
Greg Wardd5d8a992000-05-23 01:42:17 +0000942 Uses the list of commands found and cache of command objects
Greg Wardfd7b91e2000-09-26 01:52:25 +0000943 created by 'get_command_obj()'.
944 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000945 for cmd in self.commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000946 self.run_command(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000947
Greg Wardfe6462c2000-04-04 01:40:52 +0000948 # -- Methods that operate on its Commands --------------------------
949
Tarek Ziadé188789d2009-05-16 18:37:32 +0000950 def run_command(self, command):
Greg Wardfe6462c2000-04-04 01:40:52 +0000951 """Do whatever it takes to run a command (including nothing at all,
Greg Wardd5d8a992000-05-23 01:42:17 +0000952 if the command has already been run). Specifically: if we have
953 already created and run the command named by 'command', return
954 silently without doing anything. If the command named by 'command'
955 doesn't even have a command object yet, create one. Then invoke
956 'run()' on that command object (or an existing one).
957 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000958 # Already been here, done that? then return silently.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000959 if self.have_run.get(command):
Greg Wardfe6462c2000-04-04 01:40:52 +0000960 return
961
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000962 log.info("running %s", command)
Greg Wardfd7b91e2000-09-26 01:52:25 +0000963 cmd_obj = self.get_command_obj(command)
964 cmd_obj.ensure_finalized()
965 cmd_obj.run()
Greg Wardfe6462c2000-04-04 01:40:52 +0000966 self.have_run[command] = 1
967
968
Greg Wardfe6462c2000-04-04 01:40:52 +0000969 # -- Distribution query methods ------------------------------------
970
Tarek Ziadé188789d2009-05-16 18:37:32 +0000971 def has_pure_modules(self):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000972 return len(self.packages or self.py_modules or []) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000973
Tarek Ziadé188789d2009-05-16 18:37:32 +0000974 def has_ext_modules(self):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000975 return self.ext_modules and len(self.ext_modules) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000976
Tarek Ziadé188789d2009-05-16 18:37:32 +0000977 def has_c_libraries(self):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000978 return self.libraries and len(self.libraries) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000979
Tarek Ziadé188789d2009-05-16 18:37:32 +0000980 def has_modules(self):
Greg Wardfe6462c2000-04-04 01:40:52 +0000981 return self.has_pure_modules() or self.has_ext_modules()
982
Tarek Ziadé188789d2009-05-16 18:37:32 +0000983 def has_headers(self):
Greg Ward51def7d2000-05-27 01:36:14 +0000984 return self.headers and len(self.headers) > 0
985
Tarek Ziadé188789d2009-05-16 18:37:32 +0000986 def has_scripts(self):
Greg Ward44a61bb2000-05-20 15:06:48 +0000987 return self.scripts and len(self.scripts) > 0
988
Tarek Ziadé188789d2009-05-16 18:37:32 +0000989 def has_data_files(self):
Greg Ward44a61bb2000-05-20 15:06:48 +0000990 return self.data_files and len(self.data_files) > 0
991
Tarek Ziadé188789d2009-05-16 18:37:32 +0000992 def is_pure(self):
Greg Wardfe6462c2000-04-04 01:40:52 +0000993 return (self.has_pure_modules() and
994 not self.has_ext_modules() and
995 not self.has_c_libraries())
996
Greg Ward82715e12000-04-21 02:28:14 +0000997 # -- Metadata query methods ----------------------------------------
998
999 # If you're looking for 'get_name()', 'get_version()', and so forth,
1000 # they are defined in a sneaky way: the constructor binds self.get_XXX
1001 # to self.metadata.get_XXX. The actual code is in the
1002 # DistributionMetadata class, below.
1003
Greg Ward82715e12000-04-21 02:28:14 +00001004class 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
Tarek Ziadéb88a4962009-12-08 09:45:25 +00001019 def __init__(self, path=None):
1020 if path is not None:
1021 self.read_pkg_file(open(path))
1022 else:
1023 self.name = None
1024 self.version = None
1025 self.author = None
1026 self.author_email = None
1027 self.maintainer = None
1028 self.maintainer_email = None
1029 self.url = None
1030 self.license = None
1031 self.description = None
1032 self.long_description = None
1033 self.keywords = None
1034 self.platforms = None
1035 self.classifiers = None
1036 self.download_url = None
1037 # PEP 314
1038 self.provides = None
1039 self.requires = None
1040 self.obsoletes = None
1041
1042 def read_pkg_file(self, file):
1043 """Reads the metadata values from a file object."""
1044 msg = message_from_file(file)
1045
1046 def _read_field(name):
1047 value = msg[name]
1048 if value == 'UNKNOWN':
1049 return None
1050 return value
1051
1052 def _read_list(name):
1053 values = msg.get_all(name, None)
1054 if values == []:
1055 return None
1056 return values
1057
1058 metadata_version = msg['metadata-version']
1059 self.name = _read_field('name')
1060 self.version = _read_field('version')
1061 self.description = _read_field('summary')
1062 # we are filling author only.
1063 self.author = _read_field('author')
Greg Ward82715e12000-04-21 02:28:14 +00001064 self.maintainer = None
Tarek Ziadéb88a4962009-12-08 09:45:25 +00001065 self.author_email = _read_field('author-email')
Greg Ward82715e12000-04-21 02:28:14 +00001066 self.maintainer_email = None
Tarek Ziadéb88a4962009-12-08 09:45:25 +00001067 self.url = _read_field('home-page')
1068 self.license = _read_field('license')
1069
1070 if 'download-url' in msg:
1071 self.download_url = _read_field('download-url')
1072 else:
1073 self.download_url = None
1074
1075 self.long_description = _read_field('description')
1076 self.description = _read_field('summary')
1077
1078 if 'keywords' in msg:
1079 self.keywords = _read_field('keywords').split(',')
1080
1081 self.platforms = _read_list('platform')
1082 self.classifiers = _read_list('classifier')
1083
1084 # PEP 314 - these fields only exist in 1.1
1085 if metadata_version == '1.1':
1086 self.requires = _read_list('requires')
1087 self.provides = _read_list('provides')
1088 self.obsoletes = _read_list('obsoletes')
1089 else:
1090 self.requires = None
1091 self.provides = None
1092 self.obsoletes = None
Fred Drakeb94b8492001-12-06 20:51:35 +00001093
Tarek Ziadé188789d2009-05-16 18:37:32 +00001094 def write_pkg_info(self, base_dir):
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001095 """Write the PKG-INFO file into the release tree.
1096 """
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001097 pkg_info = open( os.path.join(base_dir, 'PKG-INFO'), 'w')
Fred Drakedb7b0022005-03-20 22:19:47 +00001098 self.write_pkg_file(pkg_info)
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001099 pkg_info.close()
Fred Drakeb94b8492001-12-06 20:51:35 +00001100
Tarek Ziadé188789d2009-05-16 18:37:32 +00001101 def write_pkg_file(self, file):
Fred Drakedb7b0022005-03-20 22:19:47 +00001102 """Write the PKG-INFO format data to a file object.
1103 """
1104 version = '1.0'
1105 if self.provides or self.requires or self.obsoletes:
1106 version = '1.1'
1107
1108 file.write('Metadata-Version: %s\n' % version)
1109 file.write('Name: %s\n' % self.get_name() )
1110 file.write('Version: %s\n' % self.get_version() )
1111 file.write('Summary: %s\n' % self.get_description() )
1112 file.write('Home-page: %s\n' % self.get_url() )
1113 file.write('Author: %s\n' % self.get_contact() )
1114 file.write('Author-email: %s\n' % self.get_contact_email() )
1115 file.write('License: %s\n' % self.get_license() )
1116 if self.download_url:
1117 file.write('Download-URL: %s\n' % self.download_url)
1118
Tarek Ziadéf11be752009-06-01 22:36:26 +00001119 long_desc = rfc822_escape(self.get_long_description())
Fred Drakedb7b0022005-03-20 22:19:47 +00001120 file.write('Description: %s\n' % long_desc)
1121
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001122 keywords = ','.join(self.get_keywords())
Fred Drakedb7b0022005-03-20 22:19:47 +00001123 if keywords:
1124 file.write('Keywords: %s\n' % keywords )
1125
1126 self._write_list(file, 'Platform', self.get_platforms())
1127 self._write_list(file, 'Classifier', self.get_classifiers())
1128
1129 # PEP 314
1130 self._write_list(file, 'Requires', self.get_requires())
1131 self._write_list(file, 'Provides', self.get_provides())
1132 self._write_list(file, 'Obsoletes', self.get_obsoletes())
1133
Tarek Ziadé188789d2009-05-16 18:37:32 +00001134 def _write_list(self, file, name, values):
Fred Drakedb7b0022005-03-20 22:19:47 +00001135 for value in values:
1136 file.write('%s: %s\n' % (name, value))
1137
Greg Ward82715e12000-04-21 02:28:14 +00001138 # -- Metadata query methods ----------------------------------------
1139
Tarek Ziadé188789d2009-05-16 18:37:32 +00001140 def get_name(self):
Greg Wardfe6462c2000-04-04 01:40:52 +00001141 return self.name or "UNKNOWN"
1142
Greg Ward82715e12000-04-21 02:28:14 +00001143 def get_version(self):
Thomas Hellerbcd89752001-12-06 20:44:19 +00001144 return self.version or "0.0.0"
Greg Wardfe6462c2000-04-04 01:40:52 +00001145
Tarek Ziadé188789d2009-05-16 18:37:32 +00001146 def get_fullname(self):
Greg Ward82715e12000-04-21 02:28:14 +00001147 return "%s-%s" % (self.get_name(), self.get_version())
1148
1149 def get_author(self):
1150 return self.author or "UNKNOWN"
1151
1152 def get_author_email(self):
1153 return self.author_email or "UNKNOWN"
1154
1155 def get_maintainer(self):
1156 return self.maintainer or "UNKNOWN"
1157
1158 def get_maintainer_email(self):
1159 return self.maintainer_email or "UNKNOWN"
1160
1161 def get_contact(self):
Tarek Ziadé188789d2009-05-16 18:37:32 +00001162 return self.maintainer or self.author or "UNKNOWN"
Greg Ward82715e12000-04-21 02:28:14 +00001163
1164 def get_contact_email(self):
Tarek Ziadé188789d2009-05-16 18:37:32 +00001165 return self.maintainer_email or self.author_email or "UNKNOWN"
Greg Ward82715e12000-04-21 02:28:14 +00001166
1167 def get_url(self):
1168 return self.url or "UNKNOWN"
1169
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +00001170 def get_license(self):
1171 return self.license or "UNKNOWN"
1172 get_licence = get_license
Fred Drakeb94b8492001-12-06 20:51:35 +00001173
Greg Ward82715e12000-04-21 02:28:14 +00001174 def get_description(self):
1175 return self.description or "UNKNOWN"
Greg Warde5a584e2000-04-26 02:26:55 +00001176
1177 def get_long_description(self):
1178 return self.long_description or "UNKNOWN"
1179
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001180 def get_keywords(self):
1181 return self.keywords or []
1182
1183 def get_platforms(self):
1184 return self.platforms or ["UNKNOWN"]
1185
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +00001186 def get_classifiers(self):
1187 return self.classifiers or []
1188
Andrew M. Kuchling188d85f2003-02-19 14:16:01 +00001189 def get_download_url(self):
1190 return self.download_url or "UNKNOWN"
1191
Fred Drakedb7b0022005-03-20 22:19:47 +00001192 # PEP 314
Fred Drakedb7b0022005-03-20 22:19:47 +00001193 def get_requires(self):
1194 return self.requires or []
1195
1196 def set_requires(self, value):
1197 import distutils.versionpredicate
1198 for v in value:
1199 distutils.versionpredicate.VersionPredicate(v)
1200 self.requires = value
1201
1202 def get_provides(self):
1203 return self.provides or []
1204
1205 def set_provides(self, value):
1206 value = [v.strip() for v in value]
1207 for v in value:
1208 import distutils.versionpredicate
Fred Drake227e8ff2005-03-21 06:36:32 +00001209 distutils.versionpredicate.split_provision(v)
Fred Drakedb7b0022005-03-20 22:19:47 +00001210 self.provides = value
1211
1212 def get_obsoletes(self):
1213 return self.obsoletes or []
1214
1215 def set_obsoletes(self, value):
1216 import distutils.versionpredicate
1217 for v in value:
1218 distutils.versionpredicate.VersionPredicate(v)
1219 self.obsoletes = value
1220
Tarek Ziadé188789d2009-05-16 18:37:32 +00001221def fix_help_options(options):
Greg Ward2ff78872000-06-24 00:23:20 +00001222 """Convert a 4-tuple 'help_options' list as found in various command
1223 classes to the 3-tuple form required by FancyGetopt.
1224 """
1225 new_options = []
1226 for help_tuple in options:
1227 new_options.append(help_tuple[0:3])
1228 return new_options