blob: 353525e17d4debaca3c960f074fbe94f165fb152 [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
Greg Wardfe6462c2000-04-04 01:40:52 +000017from distutils.errors import *
Greg Ward2f2b6c62000-09-25 01:58:07 +000018from distutils.fancy_getopt import FancyGetopt, translate_longopt
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +000019from distutils.util import check_environ, strtobool, rfc822_escape
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000020from distutils import log
Jeremy Hyltonfcd73532002-09-11 16:31:53 +000021from distutils.debug import DEBUG
Greg Wardfe6462c2000-04-04 01:40:52 +000022
23# Regex to define acceptable Distutils command names. This is not *quite*
24# the same as a Python NAME -- I don't allow leading underscores. The fact
25# that they're very similar is no coincidence; the default naming scheme is
26# to look for a Python module named after the command.
27command_re = re.compile (r'^[a-zA-Z]([a-zA-Z0-9_]*)$')
28
29
30class Distribution:
Greg Ward8ff5a3f2000-06-02 00:44:53 +000031 """The core of the Distutils. Most of the work hiding behind 'setup'
32 is really done within a Distribution instance, which farms the work out
33 to the Distutils commands specified on the command line.
Greg Wardfe6462c2000-04-04 01:40:52 +000034
Greg Ward8ff5a3f2000-06-02 00:44:53 +000035 Setup scripts will almost never instantiate Distribution directly,
36 unless the 'setup()' function is totally inadequate to their needs.
37 However, it is conceivable that a setup script might wish to subclass
38 Distribution for some specialized purpose, and then pass the subclass
39 to 'setup()' as the 'distclass' keyword argument. If so, it is
40 necessary to respect the expectations that 'setup' has of Distribution.
41 See the code for 'setup()', in core.py, for details.
42 """
Greg Wardfe6462c2000-04-04 01:40:52 +000043
44
45 # 'global_options' describes the command-line options that may be
Greg Ward82715e12000-04-21 02:28:14 +000046 # supplied to the setup script prior to any actual commands.
47 # Eg. "./setup.py -n" or "./setup.py --quiet" both take advantage of
Greg Wardfe6462c2000-04-04 01:40:52 +000048 # these global options. This list should be kept to a bare minimum,
49 # since every global option is also valid as a command option -- and we
50 # don't want to pollute the commands with too many options that they
51 # have minimal control over.
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000052 # The fourth entry for verbose means that it can be repeated.
53 global_options = [('verbose', 'v', "run verbosely (default)", 1),
Greg Wardd5d8a992000-05-23 01:42:17 +000054 ('quiet', 'q', "run quietly (turns verbosity off)"),
55 ('dry-run', 'n', "don't actually do anything"),
56 ('help', 'h', "show detailed help message"),
Tarek Ziadéc7c71ff2009-10-27 23:12:01 +000057 ('no-user-cfg', None,
58 'ignore pydistutils.cfg in your home directory'),
59 ]
Greg Ward82715e12000-04-21 02:28:14 +000060
Martin v. Löwis8ed338a2005-03-03 08:12:27 +000061 # 'common_usage' is a short (2-3 line) string describing the common
62 # usage of the setup script.
63 common_usage = """\
64Common commands: (see '--help-commands' for more)
65
66 setup.py build will build the package underneath 'build/'
67 setup.py install will install the package
68"""
69
Greg Ward82715e12000-04-21 02:28:14 +000070 # options that are not propagated to the commands
71 display_options = [
72 ('help-commands', None,
73 "list all available commands"),
74 ('name', None,
75 "print package name"),
76 ('version', 'V',
77 "print package version"),
78 ('fullname', None,
79 "print <package name>-<version>"),
80 ('author', None,
81 "print the author's name"),
82 ('author-email', None,
83 "print the author's email address"),
84 ('maintainer', None,
85 "print the maintainer's name"),
86 ('maintainer-email', None,
87 "print the maintainer's email address"),
88 ('contact', None,
Greg Wardd5d8a992000-05-23 01:42:17 +000089 "print the maintainer's name if known, else the author's"),
Greg Ward82715e12000-04-21 02:28:14 +000090 ('contact-email', None,
Greg Wardd5d8a992000-05-23 01:42:17 +000091 "print the maintainer's email address if known, else the author's"),
Greg Ward82715e12000-04-21 02:28:14 +000092 ('url', None,
93 "print the URL for this package"),
Greg Ward82715e12000-04-21 02:28:14 +000094 ('license', None,
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +000095 "print the license of the package"),
96 ('licence', None,
97 "alias for --license"),
Greg Ward82715e12000-04-21 02:28:14 +000098 ('description', None,
99 "print the package description"),
Greg Warde5a584e2000-04-26 02:26:55 +0000100 ('long-description', None,
101 "print the long package description"),
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000102 ('platforms', None,
103 "print the list of platforms"),
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +0000104 ('classifiers', None,
105 "print the list of classifiers"),
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000106 ('keywords', None,
107 "print the list of keywords"),
Fred Drakedb7b0022005-03-20 22:19:47 +0000108 ('provides', None,
109 "print the list of packages/modules provided"),
110 ('requires', None,
111 "print the list of packages/modules required"),
112 ('obsoletes', None,
113 "print the list of packages/modules made obsolete")
Greg Ward82715e12000-04-21 02:28:14 +0000114 ]
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000115 display_option_names = [translate_longopt(x[0]) for x in display_options]
Greg Ward82715e12000-04-21 02:28:14 +0000116
117 # negative options are options that exclude other options
Greg Wardfe6462c2000-04-04 01:40:52 +0000118 negative_opt = {'quiet': 'verbose'}
119
120
121 # -- Creation/initialization methods -------------------------------
Fred Drakeb94b8492001-12-06 20:51:35 +0000122
Greg Wardfe6462c2000-04-04 01:40:52 +0000123 def __init__ (self, attrs=None):
124 """Construct a new Distribution instance: initialize all the
Greg Ward8ff5a3f2000-06-02 00:44:53 +0000125 attributes of a Distribution, and then use 'attrs' (a dictionary
126 mapping attribute names to values) to assign some of those
127 attributes their "real" values. (Any attributes not mentioned in
128 'attrs' will be assigned to some null value: 0, None, an empty list
129 or dictionary, etc.) Most importantly, initialize the
130 'command_obj' attribute to the empty dictionary; this will be
131 filled in with real command objects by 'parse_command_line()'.
132 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000133
134 # Default values for our command-line options
135 self.verbose = 1
136 self.dry_run = 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000137 self.help = 0
Greg Ward82715e12000-04-21 02:28:14 +0000138 for attr in self.display_option_names:
139 setattr(self, attr, 0)
Greg Wardfe6462c2000-04-04 01:40:52 +0000140
Greg Ward82715e12000-04-21 02:28:14 +0000141 # Store the distribution meta-data (name, version, author, and so
142 # forth) in a separate object -- we're getting to have enough
143 # information here (and enough command-line options) that it's
144 # worth it. Also delegate 'get_XXX()' methods to the 'metadata'
145 # object in a sneaky and underhanded (but efficient!) way.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000146 self.metadata = DistributionMetadata()
Neil Schemenauera8aefe52001-09-03 15:47:21 +0000147 for basename in self.metadata._METHOD_BASENAMES:
Greg Ward4982f982000-04-22 02:52:44 +0000148 method_name = "get_" + basename
149 setattr(self, method_name, getattr(self.metadata, method_name))
Greg Wardfe6462c2000-04-04 01:40:52 +0000150
151 # 'cmdclass' maps command names to class objects, so we
152 # can 1) quickly figure out which class to instantiate when
153 # we need to create a new command object, and 2) have a way
Greg Ward82715e12000-04-21 02:28:14 +0000154 # for the setup script to override command classes
Greg Wardfe6462c2000-04-04 01:40:52 +0000155 self.cmdclass = {}
156
Fred Draked04573f2004-08-03 16:37:40 +0000157 # 'command_packages' is a list of packages in which commands
158 # are searched for. The factory for command 'foo' is expected
159 # to be named 'foo' in the module 'foo' in one of the packages
160 # named here. This list is searched from the left; an error
161 # is raised if no named package provides the command being
162 # searched for. (Always access using get_command_packages().)
163 self.command_packages = None
164
Greg Ward9821bf42000-08-29 01:15:18 +0000165 # 'script_name' and 'script_args' are usually set to sys.argv[0]
166 # and sys.argv[1:], but they can be overridden when the caller is
167 # not necessarily a setup script run from the command-line.
168 self.script_name = None
169 self.script_args = None
170
Greg Wardd5d8a992000-05-23 01:42:17 +0000171 # 'command_options' is where we store command options between
172 # parsing them (from config files, the command-line, etc.) and when
173 # they are actually needed -- ie. when the command in question is
174 # instantiated. It is a dictionary of dictionaries of 2-tuples:
175 # command_options = { command_name : { option : (source, value) } }
Gregory P. Smith14263542000-05-12 00:41:33 +0000176 self.command_options = {}
177
Martin v. Löwis98da5622005-03-23 18:54:36 +0000178 # 'dist_files' is the list of (command, pyversion, file) that
179 # have been created by any dist commands run so far. This is
180 # filled regardless of whether the run is dry or not. pyversion
181 # gives sysconfig.get_python_version() if the dist file is
182 # specific to a Python version, 'any' if it is good for all
183 # Python versions on the target platform, and '' for a source
184 # file. pyversion should not be used to specify minimum or
185 # maximum required Python versions; use the metainfo for that
186 # instead.
Martin v. Löwis55f1bb82005-03-21 20:56:35 +0000187 self.dist_files = []
188
Greg Wardfe6462c2000-04-04 01:40:52 +0000189 # These options are really the business of various commands, rather
190 # than of the Distribution itself. We provide aliases for them in
191 # Distribution as a convenience to the developer.
Greg Wardfe6462c2000-04-04 01:40:52 +0000192 self.packages = None
Fred Drake0eb32a62004-06-11 21:50:33 +0000193 self.package_data = {}
Greg Wardfe6462c2000-04-04 01:40:52 +0000194 self.package_dir = None
195 self.py_modules = None
196 self.libraries = None
Greg Ward51def7d2000-05-27 01:36:14 +0000197 self.headers = None
Greg Wardfe6462c2000-04-04 01:40:52 +0000198 self.ext_modules = None
199 self.ext_package = None
200 self.include_dirs = None
201 self.extra_path = None
Gregory P. Smithb2e3bb32000-05-12 00:52:23 +0000202 self.scripts = None
Gregory P. Smith6a901dd2000-05-13 03:09:50 +0000203 self.data_files = None
Tarek Ziadé13f7c3b2009-01-09 00:15:45 +0000204 self.password = ''
Greg Wardfe6462c2000-04-04 01:40:52 +0000205
206 # And now initialize bookkeeping stuff that can't be supplied by
207 # the caller at all. 'command_obj' maps command names to
208 # Command instances -- that's how we enforce that every command
209 # class is a singleton.
210 self.command_obj = {}
211
212 # 'have_run' maps command names to boolean values; it keeps track
213 # of whether we have actually run a particular command, to make it
214 # cheap to "run" a command whenever we think we might need to -- if
215 # it's already been done, no need for expensive filesystem
216 # operations, we just check the 'have_run' dictionary and carry on.
217 # It's only safe to query 'have_run' for a command class that has
218 # been instantiated -- a false value will be inserted when the
219 # command object is created, and replaced with a true value when
Greg Ward612eb9f2000-07-27 02:13:20 +0000220 # the command is successfully run. Thus it's probably best to use
Greg Wardfe6462c2000-04-04 01:40:52 +0000221 # '.get()' rather than a straight lookup.
222 self.have_run = {}
223
224 # Now we'll use the attrs dictionary (ultimately, keyword args from
Greg Ward82715e12000-04-21 02:28:14 +0000225 # the setup script) to possibly override any or all of these
226 # distribution options.
227
Greg Wardfe6462c2000-04-04 01:40:52 +0000228 if attrs:
Greg Wardfe6462c2000-04-04 01:40:52 +0000229 # Pull out the set of command options and work on them
230 # specifically. Note that this order guarantees that aliased
231 # command options will override any supplied redundantly
232 # through the general options dictionary.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000233 options = attrs.get('options')
Tarek Ziadé4450dcf2008-12-29 22:38:38 +0000234 if options is not None:
Greg Wardfe6462c2000-04-04 01:40:52 +0000235 del attrs['options']
236 for (command, cmd_options) in options.items():
Greg Ward0e48cfd2000-05-26 01:00:15 +0000237 opt_dict = self.get_option_dict(command)
238 for (opt, val) in cmd_options.items():
239 opt_dict[opt] = ("setup script", val)
Greg Wardfe6462c2000-04-04 01:40:52 +0000240
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000241 if 'licence' in attrs:
Andrew M. Kuchlinga52b8522003-03-03 20:07:27 +0000242 attrs['license'] = attrs['licence']
243 del attrs['licence']
244 msg = "'licence' distribution option is deprecated; use 'license'"
245 if warnings is not None:
246 warnings.warn(msg)
247 else:
248 sys.stderr.write(msg + "\n")
249
Greg Wardfe6462c2000-04-04 01:40:52 +0000250 # Now work on the rest of the attributes. Any attribute that's
251 # not already defined is invalid!
Tarek Ziadéf11be752009-06-01 22:36:26 +0000252 for (key, val) in attrs.items():
Fred Drakedb7b0022005-03-20 22:19:47 +0000253 if hasattr(self.metadata, "set_" + key):
254 getattr(self.metadata, "set_" + key)(val)
255 elif hasattr(self.metadata, key):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000256 setattr(self.metadata, key, val)
257 elif hasattr(self, key):
258 setattr(self, key, val)
Anthony Baxter73cc8472004-10-13 13:22:34 +0000259 else:
Andrew M. Kuchlingff4ad9a2002-10-31 13:22:41 +0000260 msg = "Unknown distribution option: %s" % repr(key)
261 if warnings is not None:
262 warnings.warn(msg)
263 else:
264 sys.stderr.write(msg + "\n")
Greg Wardfe6462c2000-04-04 01:40:52 +0000265
Tarek Ziadéc7c71ff2009-10-27 23:12:01 +0000266 # no-user-cfg is handled before other command line args
267 # because other args override the config files, and this
268 # one is needed before we can load the config files.
269 # If attrs['script_args'] wasn't passed, assume false.
270 #
271 # This also make sure we just look at the global options
272 self.want_user_cfg = True
273
274 if self.script_args is not None:
275 for arg in self.script_args:
276 if not arg.startswith('-'):
277 break
278 if arg == '--no-user-cfg':
279 self.want_user_cfg = False
280 break
281
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000282 self.finalize_options()
Fred Drakeb94b8492001-12-06 20:51:35 +0000283
Tarek Ziadé188789d2009-05-16 18:37:32 +0000284 def get_option_dict(self, command):
Greg Ward0e48cfd2000-05-26 01:00:15 +0000285 """Get the option dictionary for a given command. If that
286 command's option dictionary hasn't been created yet, then create it
287 and return the new dictionary; otherwise, return the existing
288 option dictionary.
289 """
Greg Ward0e48cfd2000-05-26 01:00:15 +0000290 dict = self.command_options.get(command)
291 if dict is None:
292 dict = self.command_options[command] = {}
293 return dict
294
Tarek Ziadé188789d2009-05-16 18:37:32 +0000295 def dump_option_dicts(self, header=None, commands=None, indent=""):
Greg Wardc32d9a62000-05-28 23:53:06 +0000296 from pprint import pformat
297
298 if commands is None: # dump all command option dicts
Guido van Rossumd4ee1672007-10-15 01:27:53 +0000299 commands = sorted(self.command_options.keys())
Greg Wardc32d9a62000-05-28 23:53:06 +0000300
301 if header is not None:
Tarek Ziadéf11be752009-06-01 22:36:26 +0000302 self.announce(indent + header)
Greg Wardc32d9a62000-05-28 23:53:06 +0000303 indent = indent + " "
304
305 if not commands:
Tarek Ziadéf11be752009-06-01 22:36:26 +0000306 self.announce(indent + "no commands known yet")
Greg Wardc32d9a62000-05-28 23:53:06 +0000307 return
308
309 for cmd_name in commands:
310 opt_dict = self.command_options.get(cmd_name)
311 if opt_dict is None:
Tarek Ziadéf11be752009-06-01 22:36:26 +0000312 self.announce(indent +
313 "no option dict for '%s' command" % cmd_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000314 else:
Tarek Ziadéf11be752009-06-01 22:36:26 +0000315 self.announce(indent +
316 "option dict for '%s' command:" % cmd_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000317 out = pformat(opt_dict)
Tarek Ziadéf11be752009-06-01 22:36:26 +0000318 for line in out.split('\n'):
319 self.announce(indent + " " + line)
Greg Wardc32d9a62000-05-28 23:53:06 +0000320
Greg Wardd5d8a992000-05-23 01:42:17 +0000321 # -- Config file finding/parsing methods ---------------------------
322
Tarek Ziadé188789d2009-05-16 18:37:32 +0000323 def find_config_files(self):
Gregory P. Smith14263542000-05-12 00:41:33 +0000324 """Find as many configuration files as should be processed for this
325 platform, and return a list of filenames in the order in which they
326 should be parsed. The filenames returned are guaranteed to exist
327 (modulo nasty race conditions).
328
Andrew M. Kuchlingd303b612001-12-06 16:32:05 +0000329 There are three possible config files: distutils.cfg in the
330 Distutils installation directory (ie. where the top-level
331 Distutils __inst__.py file lives), a file in the user's home
332 directory named .pydistutils.cfg on Unix and pydistutils.cfg
Tarek Ziadéc7c71ff2009-10-27 23:12:01 +0000333 on Windows/Mac; and setup.cfg in the current directory.
334
335 The file in the user's home directory can be disabled with the
336 --no-user-cfg option.
Greg Wardd5d8a992000-05-23 01:42:17 +0000337 """
Gregory P. Smith14263542000-05-12 00:41:33 +0000338 files = []
Greg Wardacf3f6a2000-06-07 02:26:19 +0000339 check_environ()
Gregory P. Smith14263542000-05-12 00:41:33 +0000340
Greg Ward11696872000-06-07 02:29:03 +0000341 # Where to look for the system-wide Distutils config file
342 sys_dir = os.path.dirname(sys.modules['distutils'].__file__)
343
344 # Look for the system config file
345 sys_file = os.path.join(sys_dir, "distutils.cfg")
Greg Wardacf3f6a2000-06-07 02:26:19 +0000346 if os.path.isfile(sys_file):
347 files.append(sys_file)
Gregory P. Smith14263542000-05-12 00:41:33 +0000348
Greg Ward11696872000-06-07 02:29:03 +0000349 # What to call the per-user config file
350 if os.name == 'posix':
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000351 user_filename = ".pydistutils.cfg"
352 else:
353 user_filename = "pydistutils.cfg"
Greg Wardfa9ff762000-10-14 04:06:40 +0000354
Greg Ward11696872000-06-07 02:29:03 +0000355 # And look for the user config file
Tarek Ziadéc7c71ff2009-10-27 23:12:01 +0000356 if self.want_user_cfg:
357 user_file = os.path.join(os.path.expanduser('~'), user_filename)
358 if os.path.isfile(user_file):
359 files.append(user_file)
Gregory P. Smith14263542000-05-12 00:41:33 +0000360
Gregory P. Smith14263542000-05-12 00:41:33 +0000361 # All platforms support local setup.cfg
362 local_file = "setup.cfg"
363 if os.path.isfile(local_file):
364 files.append(local_file)
365
Tarek Ziadéc7c71ff2009-10-27 23:12:01 +0000366 if DEBUG:
367 self.announce("using config files: %s" % ', '.join(files))
368
Gregory P. Smith14263542000-05-12 00:41:33 +0000369 return files
370
Tarek Ziadé188789d2009-05-16 18:37:32 +0000371 def parse_config_files(self, filenames=None):
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000372 from configparser import ConfigParser
Gregory P. Smith14263542000-05-12 00:41:33 +0000373
374 if filenames is None:
375 filenames = self.find_config_files()
376
Tarek Ziadéf11be752009-06-01 22:36:26 +0000377 if DEBUG:
378 self.announce("Distribution.parse_config_files():")
Greg Ward47460772000-05-23 03:47:35 +0000379
Gregory P. Smith14263542000-05-12 00:41:33 +0000380 parser = ConfigParser()
Greg Wardd5d8a992000-05-23 01:42:17 +0000381 for filename in filenames:
Tarek Ziadéf11be752009-06-01 22:36:26 +0000382 if DEBUG:
Tarek Ziadé31d46072009-09-21 13:55:19 +0000383 self.announce(" reading %s" % filename)
Greg Wardd5d8a992000-05-23 01:42:17 +0000384 parser.read(filename)
385 for section in parser.sections():
386 options = parser.options(section)
Greg Ward0e48cfd2000-05-26 01:00:15 +0000387 opt_dict = self.get_option_dict(section)
Gregory P. Smith14263542000-05-12 00:41:33 +0000388
Greg Wardd5d8a992000-05-23 01:42:17 +0000389 for opt in options:
390 if opt != '__name__':
Greg Wardceb9e222000-09-25 01:23:52 +0000391 val = parser.get(section,opt)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000392 opt = opt.replace('-', '_')
Greg Wardceb9e222000-09-25 01:23:52 +0000393 opt_dict[opt] = (filename, val)
Gregory P. Smith14263542000-05-12 00:41:33 +0000394
Greg Ward47460772000-05-23 03:47:35 +0000395 # Make the ConfigParser forget everything (so we retain
Fred Drakef06116d2004-02-17 22:35:19 +0000396 # the original filenames that options come from)
Greg Ward47460772000-05-23 03:47:35 +0000397 parser.__init__()
Gregory P. Smith14263542000-05-12 00:41:33 +0000398
Greg Wardceb9e222000-09-25 01:23:52 +0000399 # If there was a "global" section in the config file, use it
400 # to set Distribution options.
401
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000402 if 'global' in self.command_options:
Greg Wardceb9e222000-09-25 01:23:52 +0000403 for (opt, (src, val)) in self.command_options['global'].items():
404 alias = self.negative_opt.get(opt)
405 try:
406 if alias:
407 setattr(self, alias, not strtobool(val))
408 elif opt in ('verbose', 'dry_run'): # ugh!
409 setattr(self, opt, strtobool(val))
Fred Draked04573f2004-08-03 16:37:40 +0000410 else:
411 setattr(self, opt, val)
Guido van Rossumb940e112007-01-10 16:19:56 +0000412 except ValueError as msg:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000413 raise DistutilsOptionError(msg)
Greg Wardceb9e222000-09-25 01:23:52 +0000414
Greg Wardd5d8a992000-05-23 01:42:17 +0000415 # -- Command-line parsing methods ----------------------------------
416
Tarek Ziadé188789d2009-05-16 18:37:32 +0000417 def parse_command_line(self):
Greg Ward9821bf42000-08-29 01:15:18 +0000418 """Parse the setup script's command line, taken from the
419 'script_args' instance attribute (which defaults to 'sys.argv[1:]'
420 -- see 'setup()' in core.py). This list is first processed for
421 "global options" -- options that set attributes of the Distribution
422 instance. Then, it is alternately scanned for Distutils commands
423 and options for that command. Each new command terminates the
424 options for the previous command. The allowed options for a
425 command are determined by the 'user_options' attribute of the
426 command class -- thus, we have to be able to load command classes
427 in order to parse the command line. Any error in that 'options'
428 attribute raises DistutilsGetoptError; any error on the
429 command-line raises DistutilsArgError. If no Distutils commands
430 were found on the command line, raises DistutilsArgError. Return
Greg Wardceb9e222000-09-25 01:23:52 +0000431 true if command-line was successfully parsed and we should carry
Greg Ward9821bf42000-08-29 01:15:18 +0000432 on with executing commands; false if no errors but we shouldn't
433 execute commands (currently, this only happens if user asks for
434 help).
Greg Wardd5d8a992000-05-23 01:42:17 +0000435 """
Andrew M. Kuchling3f819ec2001-01-15 16:09:35 +0000436 #
Fred Drake981a1782001-08-10 18:59:30 +0000437 # We now have enough information to show the Macintosh dialog
438 # that allows the user to interactively specify the "command line".
Andrew M. Kuchling3f819ec2001-01-15 16:09:35 +0000439 #
Fred Draked04573f2004-08-03 16:37:40 +0000440 toplevel_options = self._get_toplevel_options()
Fred Drakeb94b8492001-12-06 20:51:35 +0000441
Greg Wardfe6462c2000-04-04 01:40:52 +0000442 # We have to parse the command line a bit at a time -- global
443 # options, then the first command, then its options, and so on --
444 # because each command will be handled by a different class, and
Greg Wardd5d8a992000-05-23 01:42:17 +0000445 # the options that are valid for a particular class aren't known
446 # until we have loaded the command class, which doesn't happen
447 # until we know what the command is.
Greg Wardfe6462c2000-04-04 01:40:52 +0000448
449 self.commands = []
Fred Draked04573f2004-08-03 16:37:40 +0000450 parser = FancyGetopt(toplevel_options + self.display_options)
Greg Wardfd7b91e2000-09-26 01:52:25 +0000451 parser.set_negative_aliases(self.negative_opt)
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +0000452 parser.set_aliases({'licence': 'license'})
Greg Wardfd7b91e2000-09-26 01:52:25 +0000453 args = parser.getopt(args=self.script_args, object=self)
Greg Ward82715e12000-04-21 02:28:14 +0000454 option_order = parser.get_option_order()
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000455 log.set_verbosity(self.verbose)
Greg Wardfe6462c2000-04-04 01:40:52 +0000456
Greg Ward82715e12000-04-21 02:28:14 +0000457 # for display options we return immediately
458 if self.handle_display_options(option_order):
Greg Wardfe6462c2000-04-04 01:40:52 +0000459 return
Greg Wardfe6462c2000-04-04 01:40:52 +0000460 while args:
Greg Wardd5d8a992000-05-23 01:42:17 +0000461 args = self._parse_command_opts(parser, args)
462 if args is None: # user asked for help (and got it)
Greg Wardfe6462c2000-04-04 01:40:52 +0000463 return
Greg Wardfe6462c2000-04-04 01:40:52 +0000464
Greg Wardd5d8a992000-05-23 01:42:17 +0000465 # Handle the cases of --help as a "global" option, ie.
466 # "setup.py --help" and "setup.py --help command ...". For the
467 # former, we show global options (--verbose, --dry-run, etc.)
468 # and display-only options (--name, --version, etc.); for the
469 # latter, we omit the display-only options and show help for
470 # each command listed on the command line.
Greg Wardfe6462c2000-04-04 01:40:52 +0000471 if self.help:
Greg Wardd5d8a992000-05-23 01:42:17 +0000472 self._show_help(parser,
473 display_options=len(self.commands) == 0,
474 commands=self.commands)
Greg Wardfe6462c2000-04-04 01:40:52 +0000475 return
476
477 # Oops, no commands found -- an end-user error
478 if not self.commands:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000479 raise DistutilsArgError("no commands supplied")
Greg Wardfe6462c2000-04-04 01:40:52 +0000480
481 # All is well: return true
Collin Winter5b7e9d72007-08-30 03:52:21 +0000482 return True
Greg Wardfe6462c2000-04-04 01:40:52 +0000483
Tarek Ziadé188789d2009-05-16 18:37:32 +0000484 def _get_toplevel_options(self):
Fred Draked04573f2004-08-03 16:37:40 +0000485 """Return the non-display options recognized at the top level.
486
487 This includes options that are recognized *only* at the top
488 level as well as options recognized for commands.
489 """
490 return self.global_options + [
491 ("command-packages=", None,
492 "list of packages that provide distutils commands"),
493 ]
494
Tarek Ziadé188789d2009-05-16 18:37:32 +0000495 def _parse_command_opts(self, parser, args):
Greg Wardd5d8a992000-05-23 01:42:17 +0000496 """Parse the command-line options for a single command.
497 'parser' must be a FancyGetopt instance; 'args' must be the list
498 of arguments, starting with the current command (whose options
499 we are about to parse). Returns a new version of 'args' with
500 the next command at the front of the list; will be the empty
501 list if there are no more commands on the command line. Returns
502 None if the user asked for help on this command.
503 """
504 # late import because of mutual dependence between these modules
505 from distutils.cmd import Command
506
507 # Pull the current command from the head of the command line
508 command = args[0]
Greg Wardfd7b91e2000-09-26 01:52:25 +0000509 if not command_re.match(command):
Collin Winter5b7e9d72007-08-30 03:52:21 +0000510 raise SystemExit("invalid command name '%s'" % command)
Greg Wardfd7b91e2000-09-26 01:52:25 +0000511 self.commands.append(command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000512
513 # Dig up the command class that implements this command, so we
514 # 1) know that it's a valid command, and 2) know which options
515 # it takes.
516 try:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000517 cmd_class = self.get_command_class(command)
Guido van Rossumb940e112007-01-10 16:19:56 +0000518 except DistutilsModuleError as msg:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000519 raise DistutilsArgError(msg)
Greg Wardd5d8a992000-05-23 01:42:17 +0000520
521 # Require that the command class be derived from Command -- want
522 # to be sure that the basic "command" interface is implemented.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000523 if not issubclass(cmd_class, Command):
Collin Winter5b7e9d72007-08-30 03:52:21 +0000524 raise DistutilsClassError(
525 "command class %s must subclass Command" % cmd_class)
Greg Wardd5d8a992000-05-23 01:42:17 +0000526
527 # Also make sure that the command object provides a list of its
528 # known options.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000529 if not (hasattr(cmd_class, 'user_options') and
Guido van Rossum13257902007-06-07 23:15:56 +0000530 isinstance(cmd_class.user_options, list)):
Collin Winter5b7e9d72007-08-30 03:52:21 +0000531 raise DistutilsClassError(("command class %s must provide " +
Greg Wardd5d8a992000-05-23 01:42:17 +0000532 "'user_options' attribute (a list of tuples)") % \
Collin Winter5b7e9d72007-08-30 03:52:21 +0000533 cmd_class)
Greg Wardd5d8a992000-05-23 01:42:17 +0000534
535 # If the command class has a list of negative alias options,
536 # merge it in with the global negative aliases.
537 negative_opt = self.negative_opt
Greg Wardfd7b91e2000-09-26 01:52:25 +0000538 if hasattr(cmd_class, 'negative_opt'):
Antoine Pitrou56a00de2009-05-15 17:34:21 +0000539 negative_opt = negative_opt.copy()
Greg Wardfd7b91e2000-09-26 01:52:25 +0000540 negative_opt.update(cmd_class.negative_opt)
Greg Wardd5d8a992000-05-23 01:42:17 +0000541
Greg Wardfa9ff762000-10-14 04:06:40 +0000542 # Check for help_options in command class. They have a different
543 # format (tuple of four) so we need to preprocess them here.
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000544 if (hasattr(cmd_class, 'help_options') and
Guido van Rossum13257902007-06-07 23:15:56 +0000545 isinstance(cmd_class.help_options, list)):
Greg Ward2ff78872000-06-24 00:23:20 +0000546 help_options = fix_help_options(cmd_class.help_options)
547 else:
Greg Ward55fced32000-06-24 01:22:41 +0000548 help_options = []
Greg Ward2ff78872000-06-24 00:23:20 +0000549
Greg Ward9d17a7a2000-06-07 03:00:06 +0000550
Greg Wardd5d8a992000-05-23 01:42:17 +0000551 # All commands support the global options too, just by adding
552 # in 'global_options'.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000553 parser.set_option_table(self.global_options +
554 cmd_class.user_options +
555 help_options)
556 parser.set_negative_aliases(negative_opt)
557 (args, opts) = parser.getopt(args[1:])
Greg Ward47460772000-05-23 03:47:35 +0000558 if hasattr(opts, 'help') and opts.help:
Greg Wardd5d8a992000-05-23 01:42:17 +0000559 self._show_help(parser, display_options=0, commands=[cmd_class])
560 return
561
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000562 if (hasattr(cmd_class, 'help_options') and
Guido van Rossum13257902007-06-07 23:15:56 +0000563 isinstance(cmd_class.help_options, list)):
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000564 help_option_found=0
565 for (help_option, short, desc, func) in cmd_class.help_options:
566 if hasattr(opts, parser.get_attr_name(help_option)):
567 help_option_found=1
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000568 if hasattr(func, '__call__'):
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000569 func()
Greg Ward55fced32000-06-24 01:22:41 +0000570 else:
Fred Drake981a1782001-08-10 18:59:30 +0000571 raise DistutilsClassError(
Walter Dörwald70a6b492004-02-12 17:35:32 +0000572 "invalid help function %r for help option '%s': "
Fred Drake981a1782001-08-10 18:59:30 +0000573 "must be a callable object (function, etc.)"
Walter Dörwald70a6b492004-02-12 17:35:32 +0000574 % (func, help_option))
Greg Ward55fced32000-06-24 01:22:41 +0000575
Fred Drakeb94b8492001-12-06 20:51:35 +0000576 if help_option_found:
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000577 return
Greg Ward9d17a7a2000-06-07 03:00:06 +0000578
Greg Wardd5d8a992000-05-23 01:42:17 +0000579 # Put the options from the command-line into their official
580 # holding pen, the 'command_options' dictionary.
Greg Ward0e48cfd2000-05-26 01:00:15 +0000581 opt_dict = self.get_option_dict(command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000582 for (name, value) in vars(opts).items():
Greg Ward0e48cfd2000-05-26 01:00:15 +0000583 opt_dict[name] = ("command line", value)
Greg Wardd5d8a992000-05-23 01:42:17 +0000584
585 return args
586
Tarek Ziadé188789d2009-05-16 18:37:32 +0000587 def finalize_options(self):
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000588 """Set final values for all the options on the Distribution
589 instance, analogous to the .finalize_options() method of Command
590 objects.
591 """
Tarek Ziadéf11be752009-06-01 22:36:26 +0000592 for attr in ('keywords', 'platforms'):
593 value = getattr(self.metadata, attr)
594 if value is None:
595 continue
596 if isinstance(value, str):
597 value = [elm.strip() for elm in value.split(',')]
598 setattr(self.metadata, attr, value)
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000599
Tarek Ziadé188789d2009-05-16 18:37:32 +0000600 def _show_help(self, parser, global_options=1, display_options=1,
601 commands=[]):
Greg Wardd5d8a992000-05-23 01:42:17 +0000602 """Show help for the setup script command-line in the form of
603 several lists of command-line options. 'parser' should be a
604 FancyGetopt instance; do not expect it to be returned in the
605 same state, as its option table will be reset to make it
606 generate the correct help text.
607
608 If 'global_options' is true, lists the global options:
609 --verbose, --dry-run, etc. If 'display_options' is true, lists
610 the "display-only" options: --name, --version, etc. Finally,
611 lists per-command help for every command name or command class
612 in 'commands'.
613 """
614 # late import because of mutual dependence between these modules
Greg Ward9821bf42000-08-29 01:15:18 +0000615 from distutils.core import gen_usage
Greg Wardd5d8a992000-05-23 01:42:17 +0000616 from distutils.cmd import Command
617
618 if global_options:
Fred Draked04573f2004-08-03 16:37:40 +0000619 if display_options:
620 options = self._get_toplevel_options()
621 else:
622 options = self.global_options
623 parser.set_option_table(options)
Martin v. Löwis8ed338a2005-03-03 08:12:27 +0000624 parser.print_help(self.common_usage + "\nGlobal options:")
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000625 print('')
Greg Wardd5d8a992000-05-23 01:42:17 +0000626
627 if display_options:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000628 parser.set_option_table(self.display_options)
629 parser.print_help(
Greg Wardd5d8a992000-05-23 01:42:17 +0000630 "Information display options (just display " +
631 "information, ignore any commands)")
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000632 print('')
Greg Wardd5d8a992000-05-23 01:42:17 +0000633
634 for command in self.commands:
Guido van Rossum13257902007-06-07 23:15:56 +0000635 if isinstance(command, type) and issubclass(command, Command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000636 klass = command
637 else:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000638 klass = self.get_command_class(command)
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000639 if (hasattr(klass, 'help_options') and
Guido van Rossum13257902007-06-07 23:15:56 +0000640 isinstance(klass.help_options, list)):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000641 parser.set_option_table(klass.user_options +
642 fix_help_options(klass.help_options))
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000643 else:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000644 parser.set_option_table(klass.user_options)
645 parser.print_help("Options for '%s' command:" % klass.__name__)
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000646 print('')
Greg Wardd5d8a992000-05-23 01:42:17 +0000647
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000648 print(gen_usage(self.script_name))
Greg Wardd5d8a992000-05-23 01:42:17 +0000649
Tarek Ziadé188789d2009-05-16 18:37:32 +0000650 def handle_display_options(self, option_order):
Greg Ward82715e12000-04-21 02:28:14 +0000651 """If there were any non-global "display-only" options
Greg Wardd5d8a992000-05-23 01:42:17 +0000652 (--help-commands or the metadata display options) on the command
653 line, display the requested info and return true; else return
654 false.
655 """
Greg Ward9821bf42000-08-29 01:15:18 +0000656 from distutils.core import gen_usage
Greg Ward82715e12000-04-21 02:28:14 +0000657
658 # User just wants a list of commands -- we'll print it out and stop
659 # processing now (ie. if they ran "setup --help-commands foo bar",
660 # we ignore "foo bar").
661 if self.help_commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000662 self.print_commands()
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000663 print('')
664 print(gen_usage(self.script_name))
Greg Ward82715e12000-04-21 02:28:14 +0000665 return 1
666
667 # If user supplied any of the "display metadata" options, then
668 # display that metadata in the order in which the user supplied the
669 # metadata options.
670 any_display_options = 0
671 is_display_option = {}
672 for option in self.display_options:
673 is_display_option[option[0]] = 1
674
675 for (opt, val) in option_order:
676 if val and is_display_option.get(opt):
Greg Ward2f2b6c62000-09-25 01:58:07 +0000677 opt = translate_longopt(opt)
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000678 value = getattr(self.metadata, "get_"+opt)()
679 if opt in ['keywords', 'platforms']:
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000680 print(','.join(value))
Fred Drakedb7b0022005-03-20 22:19:47 +0000681 elif opt in ('classifiers', 'provides', 'requires',
682 'obsoletes'):
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000683 print('\n'.join(value))
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000684 else:
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000685 print(value)
Greg Ward82715e12000-04-21 02:28:14 +0000686 any_display_options = 1
687
688 return any_display_options
689
Tarek Ziadé188789d2009-05-16 18:37:32 +0000690 def print_command_list(self, commands, header, max_length):
Greg Wardfe6462c2000-04-04 01:40:52 +0000691 """Print a subset of the list of all commands -- used by
Greg Wardd5d8a992000-05-23 01:42:17 +0000692 'print_commands()'.
693 """
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000694 print(header + ":")
Greg Wardfe6462c2000-04-04 01:40:52 +0000695
696 for cmd in commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000697 klass = self.cmdclass.get(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000698 if not klass:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000699 klass = self.get_command_class(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000700 try:
701 description = klass.description
702 except AttributeError:
703 description = "(no description available)"
704
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000705 print(" %-*s %s" % (max_length, cmd, description))
Greg Wardfe6462c2000-04-04 01:40:52 +0000706
Tarek Ziadé188789d2009-05-16 18:37:32 +0000707 def print_commands(self):
Greg Wardd5d8a992000-05-23 01:42:17 +0000708 """Print out a help message listing all available commands with a
709 description of each. The list is divided into "standard commands"
710 (listed in distutils.command.__all__) and "extra commands"
711 (mentioned in self.cmdclass, but not a standard command). The
712 descriptions come from the command class attribute
713 'description'.
714 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000715 import distutils.command
716 std_commands = distutils.command.__all__
717 is_std = {}
718 for cmd in std_commands:
719 is_std[cmd] = 1
720
721 extra_commands = []
722 for cmd in self.cmdclass.keys():
723 if not is_std.get(cmd):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000724 extra_commands.append(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000725
726 max_length = 0
727 for cmd in (std_commands + extra_commands):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000728 if len(cmd) > max_length:
729 max_length = len(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000730
Greg Wardfd7b91e2000-09-26 01:52:25 +0000731 self.print_command_list(std_commands,
732 "Standard commands",
733 max_length)
Greg Wardfe6462c2000-04-04 01:40:52 +0000734 if extra_commands:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000735 print()
Greg Wardfd7b91e2000-09-26 01:52:25 +0000736 self.print_command_list(extra_commands,
737 "Extra commands",
738 max_length)
Greg Wardfe6462c2000-04-04 01:40:52 +0000739
Tarek Ziadé188789d2009-05-16 18:37:32 +0000740 def get_command_list(self):
Greg Wardf6fc8752000-11-11 02:47:11 +0000741 """Get a list of (command, description) tuples.
742 The list is divided into "standard commands" (listed in
743 distutils.command.__all__) and "extra commands" (mentioned in
744 self.cmdclass, but not a standard command). The descriptions come
745 from the command class attribute 'description'.
746 """
747 # Currently this is only used on Mac OS, for the Mac-only GUI
748 # Distutils interface (by Jack Jansen)
Greg Wardf6fc8752000-11-11 02:47:11 +0000749 import distutils.command
750 std_commands = distutils.command.__all__
751 is_std = {}
752 for cmd in std_commands:
753 is_std[cmd] = 1
754
755 extra_commands = []
756 for cmd in self.cmdclass.keys():
757 if not is_std.get(cmd):
758 extra_commands.append(cmd)
759
760 rv = []
761 for cmd in (std_commands + extra_commands):
762 klass = self.cmdclass.get(cmd)
763 if not klass:
764 klass = self.get_command_class(cmd)
765 try:
766 description = klass.description
767 except AttributeError:
768 description = "(no description available)"
769 rv.append((cmd, description))
770 return rv
Greg Wardfe6462c2000-04-04 01:40:52 +0000771
772 # -- Command class/object methods ----------------------------------
773
Tarek Ziadé188789d2009-05-16 18:37:32 +0000774 def get_command_packages(self):
Fred Draked04573f2004-08-03 16:37:40 +0000775 """Return a list of packages from which commands are loaded."""
776 pkgs = self.command_packages
Tarek Ziadéf11be752009-06-01 22:36:26 +0000777 if not isinstance(pkgs, list):
778 if pkgs is None:
779 pkgs = ''
780 pkgs = [pkg.strip() for pkg in pkgs.split(',') if pkg != '']
Fred Draked04573f2004-08-03 16:37:40 +0000781 if "distutils.command" not in pkgs:
782 pkgs.insert(0, "distutils.command")
783 self.command_packages = pkgs
784 return pkgs
785
Tarek Ziadé188789d2009-05-16 18:37:32 +0000786 def get_command_class(self, command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000787 """Return the class that implements the Distutils command named by
788 'command'. First we check the 'cmdclass' dictionary; if the
789 command is mentioned there, we fetch the class object from the
790 dictionary and return it. Otherwise we load the command module
791 ("distutils.command." + command) and fetch the command class from
792 the module. The loaded class is also stored in 'cmdclass'
793 to speed future calls to 'get_command_class()'.
Greg Wardfe6462c2000-04-04 01:40:52 +0000794
Gregory P. Smith14263542000-05-12 00:41:33 +0000795 Raises DistutilsModuleError if the expected module could not be
Greg Wardd5d8a992000-05-23 01:42:17 +0000796 found, or if that module does not define the expected class.
797 """
798 klass = self.cmdclass.get(command)
799 if klass:
800 return klass
Greg Wardfe6462c2000-04-04 01:40:52 +0000801
Fred Draked04573f2004-08-03 16:37:40 +0000802 for pkgname in self.get_command_packages():
803 module_name = "%s.%s" % (pkgname, command)
804 klass_name = command
Greg Wardfe6462c2000-04-04 01:40:52 +0000805
Fred Draked04573f2004-08-03 16:37:40 +0000806 try:
807 __import__ (module_name)
808 module = sys.modules[module_name]
809 except ImportError:
810 continue
Greg Wardfe6462c2000-04-04 01:40:52 +0000811
Fred Draked04573f2004-08-03 16:37:40 +0000812 try:
813 klass = getattr(module, klass_name)
814 except AttributeError:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000815 raise DistutilsModuleError(
816 "invalid command '%s' (no class '%s' in module '%s')"
817 % (command, klass_name, module_name))
Greg Wardfe6462c2000-04-04 01:40:52 +0000818
Fred Draked04573f2004-08-03 16:37:40 +0000819 self.cmdclass[command] = klass
820 return klass
821
822 raise DistutilsModuleError("invalid command '%s'" % command)
823
Tarek Ziadé188789d2009-05-16 18:37:32 +0000824 def get_command_obj(self, command, create=1):
Greg Wardd5d8a992000-05-23 01:42:17 +0000825 """Return the command object for 'command'. Normally this object
Greg Ward612eb9f2000-07-27 02:13:20 +0000826 is cached on a previous call to 'get_command_obj()'; if no command
Greg Wardd5d8a992000-05-23 01:42:17 +0000827 object for 'command' is in the cache, then we either create and
828 return it (if 'create' is true) or return None.
829 """
830 cmd_obj = self.command_obj.get(command)
Greg Wardfe6462c2000-04-04 01:40:52 +0000831 if not cmd_obj and create:
Greg Ward2bd3f422000-06-02 01:59:33 +0000832 if DEBUG:
Tarek Ziadéf11be752009-06-01 22:36:26 +0000833 self.announce("Distribution.get_command_obj(): " \
834 "creating '%s' command object" % command)
Greg Ward47460772000-05-23 03:47:35 +0000835
Greg Wardd5d8a992000-05-23 01:42:17 +0000836 klass = self.get_command_class(command)
Greg Ward47460772000-05-23 03:47:35 +0000837 cmd_obj = self.command_obj[command] = klass(self)
838 self.have_run[command] = 0
839
840 # Set any options that were supplied in config files
841 # or on the command line. (NB. support for error
842 # reporting is lame here: any errors aren't reported
843 # until 'finalize_options()' is called, which means
844 # we won't report the source of the error.)
845 options = self.command_options.get(command)
846 if options:
Greg Wardc32d9a62000-05-28 23:53:06 +0000847 self._set_command_options(cmd_obj, options)
Greg Wardfe6462c2000-04-04 01:40:52 +0000848
849 return cmd_obj
850
Tarek Ziadé188789d2009-05-16 18:37:32 +0000851 def _set_command_options(self, command_obj, option_dict=None):
Greg Wardc32d9a62000-05-28 23:53:06 +0000852 """Set the options for 'command_obj' from 'option_dict'. Basically
853 this means copying elements of a dictionary ('option_dict') to
854 attributes of an instance ('command').
855
Greg Wardceb9e222000-09-25 01:23:52 +0000856 'command_obj' must be a Command instance. If 'option_dict' is not
Greg Wardc32d9a62000-05-28 23:53:06 +0000857 supplied, uses the standard option dictionary for this command
858 (from 'self.command_options').
859 """
Greg Wardc32d9a62000-05-28 23:53:06 +0000860 command_name = command_obj.get_command_name()
861 if option_dict is None:
862 option_dict = self.get_option_dict(command_name)
863
Tarek Ziadéf11be752009-06-01 22:36:26 +0000864 if DEBUG:
865 self.announce(" setting options for '%s' command:" % command_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000866 for (option, (source, value)) in option_dict.items():
Tarek Ziadéf11be752009-06-01 22:36:26 +0000867 if DEBUG:
868 self.announce(" %s = %s (from %s)" % (option, value,
869 source))
Greg Wardceb9e222000-09-25 01:23:52 +0000870 try:
Amaury Forgeot d'Arc61cb0872008-07-26 20:09:45 +0000871 bool_opts = [translate_longopt(o)
872 for o in command_obj.boolean_options]
Greg Wardceb9e222000-09-25 01:23:52 +0000873 except AttributeError:
874 bool_opts = []
875 try:
876 neg_opt = command_obj.negative_opt
877 except AttributeError:
878 neg_opt = {}
879
880 try:
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000881 is_string = isinstance(value, str)
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000882 if option in neg_opt and is_string:
Greg Wardceb9e222000-09-25 01:23:52 +0000883 setattr(command_obj, neg_opt[option], not strtobool(value))
Greg Ward2c08cf02000-09-27 00:15:37 +0000884 elif option in bool_opts and is_string:
Greg Wardceb9e222000-09-25 01:23:52 +0000885 setattr(command_obj, option, strtobool(value))
886 elif hasattr(command_obj, option):
887 setattr(command_obj, option, value)
888 else:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000889 raise DistutilsOptionError(
890 "error in %s: command '%s' has no such option '%s'"
891 % (source, command_name, option))
Guido van Rossumb940e112007-01-10 16:19:56 +0000892 except ValueError as msg:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000893 raise DistutilsOptionError(msg)
Greg Wardc32d9a62000-05-28 23:53:06 +0000894
Tarek Ziadé188789d2009-05-16 18:37:32 +0000895 def reinitialize_command(self, command, reinit_subcommands=0):
Greg Wardc32d9a62000-05-28 23:53:06 +0000896 """Reinitializes a command to the state it was in when first
897 returned by 'get_command_obj()': ie., initialized but not yet
Greg Ward7d9c7052000-06-28 01:25:27 +0000898 finalized. This provides the opportunity to sneak option
Greg Wardc32d9a62000-05-28 23:53:06 +0000899 values in programmatically, overriding or supplementing
900 user-supplied values from the config files and command line.
901 You'll have to re-finalize the command object (by calling
902 'finalize_options()' or 'ensure_finalized()') before using it for
Fred Drakeb94b8492001-12-06 20:51:35 +0000903 real.
Greg Wardc32d9a62000-05-28 23:53:06 +0000904
Greg Wardf449ea52000-09-16 15:23:28 +0000905 'command' should be a command name (string) or command object. If
906 'reinit_subcommands' is true, also reinitializes the command's
907 sub-commands, as declared by the 'sub_commands' class attribute (if
908 it has one). See the "install" command for an example. Only
909 reinitializes the sub-commands that actually matter, ie. those
910 whose test predicates return true.
911
Greg Wardc32d9a62000-05-28 23:53:06 +0000912 Returns the reinitialized command object.
913 """
914 from distutils.cmd import Command
915 if not isinstance(command, Command):
916 command_name = command
917 command = self.get_command_obj(command_name)
918 else:
919 command_name = command.get_command_name()
920
921 if not command.finalized:
Greg Ward282c7a02000-06-01 01:09:47 +0000922 return command
Greg Wardc32d9a62000-05-28 23:53:06 +0000923 command.initialize_options()
924 command.finalized = 0
Greg Ward43955c92000-06-06 02:52:36 +0000925 self.have_run[command_name] = 0
Greg Wardc32d9a62000-05-28 23:53:06 +0000926 self._set_command_options(command)
Greg Wardf449ea52000-09-16 15:23:28 +0000927
Greg Wardf449ea52000-09-16 15:23:28 +0000928 if reinit_subcommands:
Greg Wardf449ea52000-09-16 15:23:28 +0000929 for sub in command.get_sub_commands():
Fred Drakeb94b8492001-12-06 20:51:35 +0000930 self.reinitialize_command(sub, reinit_subcommands)
Greg Wardf449ea52000-09-16 15:23:28 +0000931
Greg Wardc32d9a62000-05-28 23:53:06 +0000932 return command
933
Greg Wardfe6462c2000-04-04 01:40:52 +0000934 # -- Methods that operate on the Distribution ----------------------
935
Tarek Ziadé05bf01a2009-07-04 02:04:21 +0000936 def announce(self, msg, level=log.INFO):
937 log.log(level, msg)
Greg Wardfe6462c2000-04-04 01:40:52 +0000938
Tarek Ziadé188789d2009-05-16 18:37:32 +0000939 def run_commands(self):
Greg Ward82715e12000-04-21 02:28:14 +0000940 """Run each command that was seen on the setup script command line.
Greg Wardd5d8a992000-05-23 01:42:17 +0000941 Uses the list of commands found and cache of command objects
Greg Wardfd7b91e2000-09-26 01:52:25 +0000942 created by 'get_command_obj()'.
943 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000944 for cmd in self.commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000945 self.run_command(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000946
Greg Wardfe6462c2000-04-04 01:40:52 +0000947 # -- Methods that operate on its Commands --------------------------
948
Tarek Ziadé188789d2009-05-16 18:37:32 +0000949 def run_command(self, command):
Greg Wardfe6462c2000-04-04 01:40:52 +0000950 """Do whatever it takes to run a command (including nothing at all,
Greg Wardd5d8a992000-05-23 01:42:17 +0000951 if the command has already been run). Specifically: if we have
952 already created and run the command named by 'command', return
953 silently without doing anything. If the command named by 'command'
954 doesn't even have a command object yet, create one. Then invoke
955 'run()' on that command object (or an existing one).
956 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000957 # Already been here, done that? then return silently.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000958 if self.have_run.get(command):
Greg Wardfe6462c2000-04-04 01:40:52 +0000959 return
960
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000961 log.info("running %s", command)
Greg Wardfd7b91e2000-09-26 01:52:25 +0000962 cmd_obj = self.get_command_obj(command)
963 cmd_obj.ensure_finalized()
964 cmd_obj.run()
Greg Wardfe6462c2000-04-04 01:40:52 +0000965 self.have_run[command] = 1
966
967
Greg Wardfe6462c2000-04-04 01:40:52 +0000968 # -- Distribution query methods ------------------------------------
969
Tarek Ziadé188789d2009-05-16 18:37:32 +0000970 def has_pure_modules(self):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000971 return len(self.packages or self.py_modules or []) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000972
Tarek Ziadé188789d2009-05-16 18:37:32 +0000973 def has_ext_modules(self):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000974 return self.ext_modules and len(self.ext_modules) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000975
Tarek Ziadé188789d2009-05-16 18:37:32 +0000976 def has_c_libraries(self):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000977 return self.libraries and len(self.libraries) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000978
Tarek Ziadé188789d2009-05-16 18:37:32 +0000979 def has_modules(self):
Greg Wardfe6462c2000-04-04 01:40:52 +0000980 return self.has_pure_modules() or self.has_ext_modules()
981
Tarek Ziadé188789d2009-05-16 18:37:32 +0000982 def has_headers(self):
Greg Ward51def7d2000-05-27 01:36:14 +0000983 return self.headers and len(self.headers) > 0
984
Tarek Ziadé188789d2009-05-16 18:37:32 +0000985 def has_scripts(self):
Greg Ward44a61bb2000-05-20 15:06:48 +0000986 return self.scripts and len(self.scripts) > 0
987
Tarek Ziadé188789d2009-05-16 18:37:32 +0000988 def has_data_files(self):
Greg Ward44a61bb2000-05-20 15:06:48 +0000989 return self.data_files and len(self.data_files) > 0
990
Tarek Ziadé188789d2009-05-16 18:37:32 +0000991 def is_pure(self):
Greg Wardfe6462c2000-04-04 01:40:52 +0000992 return (self.has_pure_modules() and
993 not self.has_ext_modules() and
994 not self.has_c_libraries())
995
Greg Ward82715e12000-04-21 02:28:14 +0000996 # -- Metadata query methods ----------------------------------------
997
998 # If you're looking for 'get_name()', 'get_version()', and so forth,
999 # they are defined in a sneaky way: the constructor binds self.get_XXX
1000 # to self.metadata.get_XXX. The actual code is in the
1001 # DistributionMetadata class, below.
1002
Greg Ward82715e12000-04-21 02:28:14 +00001003class DistributionMetadata:
1004 """Dummy class to hold the distribution meta-data: name, version,
Greg Wardfd7b91e2000-09-26 01:52:25 +00001005 author, and so forth.
1006 """
Greg Ward82715e12000-04-21 02:28:14 +00001007
Neil Schemenauera8aefe52001-09-03 15:47:21 +00001008 _METHOD_BASENAMES = ("name", "version", "author", "author_email",
1009 "maintainer", "maintainer_email", "url",
1010 "license", "description", "long_description",
1011 "keywords", "platforms", "fullname", "contact",
Andrew M. Kuchlinga52b8522003-03-03 20:07:27 +00001012 "contact_email", "license", "classifiers",
Fred Drakedb7b0022005-03-20 22:19:47 +00001013 "download_url",
1014 # PEP 314
1015 "provides", "requires", "obsoletes",
1016 )
Neil Schemenauera8aefe52001-09-03 15:47:21 +00001017
Tarek Ziadéb88a4962009-12-08 09:45:25 +00001018 def __init__(self, path=None):
1019 if path is not None:
1020 self.read_pkg_file(open(path))
1021 else:
1022 self.name = None
1023 self.version = None
1024 self.author = None
1025 self.author_email = None
1026 self.maintainer = None
1027 self.maintainer_email = None
1028 self.url = None
1029 self.license = None
1030 self.description = None
1031 self.long_description = None
1032 self.keywords = None
1033 self.platforms = None
1034 self.classifiers = None
1035 self.download_url = None
1036 # PEP 314
1037 self.provides = None
1038 self.requires = None
1039 self.obsoletes = None
1040
1041 def read_pkg_file(self, file):
1042 """Reads the metadata values from a file object."""
1043 msg = message_from_file(file)
1044
1045 def _read_field(name):
1046 value = msg[name]
1047 if value == 'UNKNOWN':
1048 return None
1049 return value
1050
1051 def _read_list(name):
1052 values = msg.get_all(name, None)
1053 if values == []:
1054 return None
1055 return values
1056
1057 metadata_version = msg['metadata-version']
1058 self.name = _read_field('name')
1059 self.version = _read_field('version')
1060 self.description = _read_field('summary')
1061 # we are filling author only.
1062 self.author = _read_field('author')
Greg Ward82715e12000-04-21 02:28:14 +00001063 self.maintainer = None
Tarek Ziadéb88a4962009-12-08 09:45:25 +00001064 self.author_email = _read_field('author-email')
Greg Ward82715e12000-04-21 02:28:14 +00001065 self.maintainer_email = None
Tarek Ziadéb88a4962009-12-08 09:45:25 +00001066 self.url = _read_field('home-page')
1067 self.license = _read_field('license')
1068
1069 if 'download-url' in msg:
1070 self.download_url = _read_field('download-url')
1071 else:
1072 self.download_url = None
1073
1074 self.long_description = _read_field('description')
1075 self.description = _read_field('summary')
1076
1077 if 'keywords' in msg:
1078 self.keywords = _read_field('keywords').split(',')
1079
1080 self.platforms = _read_list('platform')
1081 self.classifiers = _read_list('classifier')
1082
1083 # PEP 314 - these fields only exist in 1.1
1084 if metadata_version == '1.1':
1085 self.requires = _read_list('requires')
1086 self.provides = _read_list('provides')
1087 self.obsoletes = _read_list('obsoletes')
1088 else:
1089 self.requires = None
1090 self.provides = None
1091 self.obsoletes = None
Fred Drakeb94b8492001-12-06 20:51:35 +00001092
Tarek Ziadé188789d2009-05-16 18:37:32 +00001093 def write_pkg_info(self, base_dir):
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001094 """Write the PKG-INFO file into the release tree.
1095 """
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001096 pkg_info = open( os.path.join(base_dir, 'PKG-INFO'), 'w')
Fred Drakedb7b0022005-03-20 22:19:47 +00001097 self.write_pkg_file(pkg_info)
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001098 pkg_info.close()
Fred Drakeb94b8492001-12-06 20:51:35 +00001099
Tarek Ziadé188789d2009-05-16 18:37:32 +00001100 def write_pkg_file(self, file):
Fred Drakedb7b0022005-03-20 22:19:47 +00001101 """Write the PKG-INFO format data to a file object.
1102 """
1103 version = '1.0'
1104 if self.provides or self.requires or self.obsoletes:
1105 version = '1.1'
1106
1107 file.write('Metadata-Version: %s\n' % version)
1108 file.write('Name: %s\n' % self.get_name() )
1109 file.write('Version: %s\n' % self.get_version() )
1110 file.write('Summary: %s\n' % self.get_description() )
1111 file.write('Home-page: %s\n' % self.get_url() )
1112 file.write('Author: %s\n' % self.get_contact() )
1113 file.write('Author-email: %s\n' % self.get_contact_email() )
1114 file.write('License: %s\n' % self.get_license() )
1115 if self.download_url:
1116 file.write('Download-URL: %s\n' % self.download_url)
1117
Tarek Ziadéf11be752009-06-01 22:36:26 +00001118 long_desc = rfc822_escape(self.get_long_description())
Fred Drakedb7b0022005-03-20 22:19:47 +00001119 file.write('Description: %s\n' % long_desc)
1120
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001121 keywords = ','.join(self.get_keywords())
Fred Drakedb7b0022005-03-20 22:19:47 +00001122 if keywords:
1123 file.write('Keywords: %s\n' % keywords )
1124
1125 self._write_list(file, 'Platform', self.get_platforms())
1126 self._write_list(file, 'Classifier', self.get_classifiers())
1127
1128 # PEP 314
1129 self._write_list(file, 'Requires', self.get_requires())
1130 self._write_list(file, 'Provides', self.get_provides())
1131 self._write_list(file, 'Obsoletes', self.get_obsoletes())
1132
Tarek Ziadé188789d2009-05-16 18:37:32 +00001133 def _write_list(self, file, name, values):
Fred Drakedb7b0022005-03-20 22:19:47 +00001134 for value in values:
1135 file.write('%s: %s\n' % (name, value))
1136
Greg Ward82715e12000-04-21 02:28:14 +00001137 # -- Metadata query methods ----------------------------------------
1138
Tarek Ziadé188789d2009-05-16 18:37:32 +00001139 def get_name(self):
Greg Wardfe6462c2000-04-04 01:40:52 +00001140 return self.name or "UNKNOWN"
1141
Greg Ward82715e12000-04-21 02:28:14 +00001142 def get_version(self):
Thomas Hellerbcd89752001-12-06 20:44:19 +00001143 return self.version or "0.0.0"
Greg Wardfe6462c2000-04-04 01:40:52 +00001144
Tarek Ziadé188789d2009-05-16 18:37:32 +00001145 def get_fullname(self):
Greg Ward82715e12000-04-21 02:28:14 +00001146 return "%s-%s" % (self.get_name(), self.get_version())
1147
1148 def get_author(self):
1149 return self.author or "UNKNOWN"
1150
1151 def get_author_email(self):
1152 return self.author_email or "UNKNOWN"
1153
1154 def get_maintainer(self):
1155 return self.maintainer or "UNKNOWN"
1156
1157 def get_maintainer_email(self):
1158 return self.maintainer_email or "UNKNOWN"
1159
1160 def get_contact(self):
Tarek Ziadé188789d2009-05-16 18:37:32 +00001161 return self.maintainer or self.author or "UNKNOWN"
Greg Ward82715e12000-04-21 02:28:14 +00001162
1163 def get_contact_email(self):
Tarek Ziadé188789d2009-05-16 18:37:32 +00001164 return self.maintainer_email or self.author_email or "UNKNOWN"
Greg Ward82715e12000-04-21 02:28:14 +00001165
1166 def get_url(self):
1167 return self.url or "UNKNOWN"
1168
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +00001169 def get_license(self):
1170 return self.license or "UNKNOWN"
1171 get_licence = get_license
Fred Drakeb94b8492001-12-06 20:51:35 +00001172
Greg Ward82715e12000-04-21 02:28:14 +00001173 def get_description(self):
1174 return self.description or "UNKNOWN"
Greg Warde5a584e2000-04-26 02:26:55 +00001175
1176 def get_long_description(self):
1177 return self.long_description or "UNKNOWN"
1178
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001179 def get_keywords(self):
1180 return self.keywords or []
1181
1182 def get_platforms(self):
1183 return self.platforms or ["UNKNOWN"]
1184
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +00001185 def get_classifiers(self):
1186 return self.classifiers or []
1187
Andrew M. Kuchling188d85f2003-02-19 14:16:01 +00001188 def get_download_url(self):
1189 return self.download_url or "UNKNOWN"
1190
Fred Drakedb7b0022005-03-20 22:19:47 +00001191 # PEP 314
Fred Drakedb7b0022005-03-20 22:19:47 +00001192 def get_requires(self):
1193 return self.requires or []
1194
1195 def set_requires(self, value):
1196 import distutils.versionpredicate
1197 for v in value:
1198 distutils.versionpredicate.VersionPredicate(v)
1199 self.requires = value
1200
1201 def get_provides(self):
1202 return self.provides or []
1203
1204 def set_provides(self, value):
1205 value = [v.strip() for v in value]
1206 for v in value:
1207 import distutils.versionpredicate
Fred Drake227e8ff2005-03-21 06:36:32 +00001208 distutils.versionpredicate.split_provision(v)
Fred Drakedb7b0022005-03-20 22:19:47 +00001209 self.provides = value
1210
1211 def get_obsoletes(self):
1212 return self.obsoletes or []
1213
1214 def set_obsoletes(self, value):
1215 import distutils.versionpredicate
1216 for v in value:
1217 distutils.versionpredicate.VersionPredicate(v)
1218 self.obsoletes = value
1219
Tarek Ziadé188789d2009-05-16 18:37:32 +00001220def fix_help_options(options):
Greg Ward2ff78872000-06-24 00:23:20 +00001221 """Convert a 4-tuple 'help_options' list as found in various command
1222 classes to the 3-tuple form required by FancyGetopt.
1223 """
1224 new_options = []
1225 for help_tuple in options:
1226 new_options.append(help_tuple[0:3])
1227 return new_options