blob: 7eb04bc3f59814355325f5fbb87e2dd75e1ecfff [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
Neal Norwitz9d72bb42007-04-17 08:48:32 +00007import sys, os, re
Jason R. Coombs3492e392013-11-10 18:15:03 -05008from email import message_from_file
Andrew M. Kuchlingff4ad9a2002-10-31 13:22:41 +00009
10try:
11 import warnings
Andrew M. Kuchlingccf4e422002-10-31 13:39:33 +000012except ImportError:
Andrew M. Kuchlingff4ad9a2002-10-31 13:22:41 +000013 warnings = None
14
Tarek Ziadé36797272010-07-22 12:50:05 +000015from distutils.errors import *
Greg Ward2f2b6c62000-09-25 01:58:07 +000016from distutils.fancy_getopt import FancyGetopt, translate_longopt
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +000017from distutils.util import check_environ, strtobool, rfc822_escape
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000018from distutils import log
Jeremy Hyltonfcd73532002-09-11 16:31:53 +000019from distutils.debug import DEBUG
Greg Wardfe6462c2000-04-04 01:40:52 +000020
21# Regex to define acceptable Distutils command names. This is not *quite*
22# the same as a Python NAME -- I don't allow leading underscores. The fact
23# that they're very similar is no coincidence; the default naming scheme is
24# to look for a Python module named after the command.
25command_re = re.compile (r'^[a-zA-Z]([a-zA-Z0-9_]*)$')
26
27
28class Distribution:
Greg Ward8ff5a3f2000-06-02 00:44:53 +000029 """The core of the Distutils. Most of the work hiding behind 'setup'
30 is really done within a Distribution instance, which farms the work out
31 to the Distutils commands specified on the command line.
Greg Wardfe6462c2000-04-04 01:40:52 +000032
Greg Ward8ff5a3f2000-06-02 00:44:53 +000033 Setup scripts will almost never instantiate Distribution directly,
34 unless the 'setup()' function is totally inadequate to their needs.
35 However, it is conceivable that a setup script might wish to subclass
36 Distribution for some specialized purpose, and then pass the subclass
37 to 'setup()' as the 'distclass' keyword argument. If so, it is
38 necessary to respect the expectations that 'setup' has of Distribution.
39 See the code for 'setup()', in core.py, for details.
40 """
Greg Wardfe6462c2000-04-04 01:40:52 +000041
42
43 # 'global_options' describes the command-line options that may be
Greg Ward82715e12000-04-21 02:28:14 +000044 # supplied to the setup script prior to any actual commands.
45 # Eg. "./setup.py -n" or "./setup.py --quiet" both take advantage of
Greg Wardfe6462c2000-04-04 01:40:52 +000046 # these global options. This list should be kept to a bare minimum,
47 # since every global option is also valid as a command option -- and we
48 # don't want to pollute the commands with too many options that they
49 # have minimal control over.
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000050 # The fourth entry for verbose means that it can be repeated.
51 global_options = [('verbose', 'v', "run verbosely (default)", 1),
Greg Wardd5d8a992000-05-23 01:42:17 +000052 ('quiet', 'q', "run quietly (turns verbosity off)"),
53 ('dry-run', 'n', "don't actually do anything"),
54 ('help', 'h', "show detailed help message"),
Andrew Kuchling2a1838b2013-11-10 18:11:00 -050055 ('no-user-cfg', None,
56 'ignore pydistutils.cfg in your home directory'),
57 ]
Greg Ward82715e12000-04-21 02:28:14 +000058
Martin v. Löwis8ed338a2005-03-03 08:12:27 +000059 # 'common_usage' is a short (2-3 line) string describing the common
60 # usage of the setup script.
61 common_usage = """\
62Common commands: (see '--help-commands' for more)
63
64 setup.py build will build the package underneath 'build/'
65 setup.py install will install the package
66"""
67
Greg Ward82715e12000-04-21 02:28:14 +000068 # options that are not propagated to the commands
69 display_options = [
70 ('help-commands', None,
71 "list all available commands"),
72 ('name', None,
73 "print package name"),
74 ('version', 'V',
75 "print package version"),
76 ('fullname', None,
77 "print <package name>-<version>"),
78 ('author', None,
79 "print the author's name"),
80 ('author-email', None,
81 "print the author's email address"),
82 ('maintainer', None,
83 "print the maintainer's name"),
84 ('maintainer-email', None,
85 "print the maintainer's email address"),
86 ('contact', None,
Greg Wardd5d8a992000-05-23 01:42:17 +000087 "print the maintainer's name if known, else the author's"),
Greg Ward82715e12000-04-21 02:28:14 +000088 ('contact-email', None,
Greg Wardd5d8a992000-05-23 01:42:17 +000089 "print the maintainer's email address if known, else the author's"),
Greg Ward82715e12000-04-21 02:28:14 +000090 ('url', None,
91 "print the URL for this package"),
Greg Ward82715e12000-04-21 02:28:14 +000092 ('license', None,
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +000093 "print the license of the package"),
94 ('licence', None,
95 "alias for --license"),
Greg Ward82715e12000-04-21 02:28:14 +000096 ('description', None,
97 "print the package description"),
Greg Warde5a584e2000-04-26 02:26:55 +000098 ('long-description', None,
99 "print the long package description"),
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000100 ('platforms', None,
101 "print the list of platforms"),
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +0000102 ('classifiers', None,
103 "print the list of classifiers"),
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000104 ('keywords', None,
105 "print the list of keywords"),
Fred Drakedb7b0022005-03-20 22:19:47 +0000106 ('provides', None,
107 "print the list of packages/modules provided"),
108 ('requires', None,
109 "print the list of packages/modules required"),
110 ('obsoletes', None,
111 "print the list of packages/modules made obsolete")
Greg Ward82715e12000-04-21 02:28:14 +0000112 ]
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000113 display_option_names = [translate_longopt(x[0]) for x in display_options]
Greg Ward82715e12000-04-21 02:28:14 +0000114
115 # negative options are options that exclude other options
Greg Wardfe6462c2000-04-04 01:40:52 +0000116 negative_opt = {'quiet': 'verbose'}
117
118
119 # -- Creation/initialization methods -------------------------------
Fred Drakeb94b8492001-12-06 20:51:35 +0000120
Greg Wardfe6462c2000-04-04 01:40:52 +0000121 def __init__ (self, attrs=None):
122 """Construct a new Distribution instance: initialize all the
Greg Ward8ff5a3f2000-06-02 00:44:53 +0000123 attributes of a Distribution, and then use 'attrs' (a dictionary
124 mapping attribute names to values) to assign some of those
125 attributes their "real" values. (Any attributes not mentioned in
126 'attrs' will be assigned to some null value: 0, None, an empty list
127 or dictionary, etc.) Most importantly, initialize the
128 'command_obj' attribute to the empty dictionary; this will be
129 filled in with real command objects by 'parse_command_line()'.
130 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000131
132 # Default values for our command-line options
133 self.verbose = 1
134 self.dry_run = 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000135 self.help = 0
Greg Ward82715e12000-04-21 02:28:14 +0000136 for attr in self.display_option_names:
137 setattr(self, attr, 0)
Greg Wardfe6462c2000-04-04 01:40:52 +0000138
Greg Ward82715e12000-04-21 02:28:14 +0000139 # Store the distribution meta-data (name, version, author, and so
140 # forth) in a separate object -- we're getting to have enough
141 # information here (and enough command-line options) that it's
142 # worth it. Also delegate 'get_XXX()' methods to the 'metadata'
143 # object in a sneaky and underhanded (but efficient!) way.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000144 self.metadata = DistributionMetadata()
Neil Schemenauera8aefe52001-09-03 15:47:21 +0000145 for basename in self.metadata._METHOD_BASENAMES:
Greg Ward4982f982000-04-22 02:52:44 +0000146 method_name = "get_" + basename
147 setattr(self, method_name, getattr(self.metadata, method_name))
Greg Wardfe6462c2000-04-04 01:40:52 +0000148
149 # 'cmdclass' maps command names to class objects, so we
150 # can 1) quickly figure out which class to instantiate when
151 # we need to create a new command object, and 2) have a way
Greg Ward82715e12000-04-21 02:28:14 +0000152 # for the setup script to override command classes
Greg Wardfe6462c2000-04-04 01:40:52 +0000153 self.cmdclass = {}
154
Fred Draked04573f2004-08-03 16:37:40 +0000155 # 'command_packages' is a list of packages in which commands
156 # are searched for. The factory for command 'foo' is expected
157 # to be named 'foo' in the module 'foo' in one of the packages
158 # named here. This list is searched from the left; an error
159 # is raised if no named package provides the command being
160 # searched for. (Always access using get_command_packages().)
161 self.command_packages = None
162
Greg Ward9821bf42000-08-29 01:15:18 +0000163 # 'script_name' and 'script_args' are usually set to sys.argv[0]
164 # and sys.argv[1:], but they can be overridden when the caller is
165 # not necessarily a setup script run from the command-line.
166 self.script_name = None
167 self.script_args = None
168
Greg Wardd5d8a992000-05-23 01:42:17 +0000169 # 'command_options' is where we store command options between
170 # parsing them (from config files, the command-line, etc.) and when
171 # they are actually needed -- ie. when the command in question is
172 # instantiated. It is a dictionary of dictionaries of 2-tuples:
173 # command_options = { command_name : { option : (source, value) } }
Gregory P. Smith14263542000-05-12 00:41:33 +0000174 self.command_options = {}
175
Martin v. Löwis98da5622005-03-23 18:54:36 +0000176 # 'dist_files' is the list of (command, pyversion, file) that
177 # have been created by any dist commands run so far. This is
178 # filled regardless of whether the run is dry or not. pyversion
179 # gives sysconfig.get_python_version() if the dist file is
180 # specific to a Python version, 'any' if it is good for all
181 # Python versions on the target platform, and '' for a source
182 # file. pyversion should not be used to specify minimum or
183 # maximum required Python versions; use the metainfo for that
184 # instead.
Martin v. Löwis55f1bb82005-03-21 20:56:35 +0000185 self.dist_files = []
186
Greg Wardfe6462c2000-04-04 01:40:52 +0000187 # These options are really the business of various commands, rather
188 # than of the Distribution itself. We provide aliases for them in
189 # Distribution as a convenience to the developer.
Greg Wardfe6462c2000-04-04 01:40:52 +0000190 self.packages = None
Fred Drake0eb32a62004-06-11 21:50:33 +0000191 self.package_data = {}
Greg Wardfe6462c2000-04-04 01:40:52 +0000192 self.package_dir = None
193 self.py_modules = None
194 self.libraries = None
Greg Ward51def7d2000-05-27 01:36:14 +0000195 self.headers = None
Greg Wardfe6462c2000-04-04 01:40:52 +0000196 self.ext_modules = None
197 self.ext_package = None
198 self.include_dirs = None
199 self.extra_path = None
Gregory P. Smithb2e3bb32000-05-12 00:52:23 +0000200 self.scripts = None
Gregory P. Smith6a901dd2000-05-13 03:09:50 +0000201 self.data_files = None
Tarek Ziadé13f7c3b2009-01-09 00:15:45 +0000202 self.password = ''
Greg Wardfe6462c2000-04-04 01:40:52 +0000203
204 # And now initialize bookkeeping stuff that can't be supplied by
205 # the caller at all. 'command_obj' maps command names to
206 # Command instances -- that's how we enforce that every command
207 # class is a singleton.
208 self.command_obj = {}
209
210 # 'have_run' maps command names to boolean values; it keeps track
211 # of whether we have actually run a particular command, to make it
212 # cheap to "run" a command whenever we think we might need to -- if
213 # it's already been done, no need for expensive filesystem
214 # operations, we just check the 'have_run' dictionary and carry on.
215 # It's only safe to query 'have_run' for a command class that has
216 # been instantiated -- a false value will be inserted when the
217 # command object is created, and replaced with a true value when
Greg Ward612eb9f2000-07-27 02:13:20 +0000218 # the command is successfully run. Thus it's probably best to use
Greg Wardfe6462c2000-04-04 01:40:52 +0000219 # '.get()' rather than a straight lookup.
220 self.have_run = {}
221
222 # Now we'll use the attrs dictionary (ultimately, keyword args from
Greg Ward82715e12000-04-21 02:28:14 +0000223 # the setup script) to possibly override any or all of these
224 # distribution options.
225
Greg Wardfe6462c2000-04-04 01:40:52 +0000226 if attrs:
Greg Wardfe6462c2000-04-04 01:40:52 +0000227 # Pull out the set of command options and work on them
228 # specifically. Note that this order guarantees that aliased
229 # command options will override any supplied redundantly
230 # through the general options dictionary.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000231 options = attrs.get('options')
Tarek Ziadé4450dcf2008-12-29 22:38:38 +0000232 if options is not None:
Greg Wardfe6462c2000-04-04 01:40:52 +0000233 del attrs['options']
234 for (command, cmd_options) in options.items():
Greg Ward0e48cfd2000-05-26 01:00:15 +0000235 opt_dict = self.get_option_dict(command)
236 for (opt, val) in cmd_options.items():
237 opt_dict[opt] = ("setup script", val)
Greg Wardfe6462c2000-04-04 01:40:52 +0000238
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000239 if 'licence' in attrs:
Andrew M. Kuchlinga52b8522003-03-03 20:07:27 +0000240 attrs['license'] = attrs['licence']
241 del attrs['licence']
242 msg = "'licence' distribution option is deprecated; use 'license'"
243 if warnings is not None:
244 warnings.warn(msg)
245 else:
246 sys.stderr.write(msg + "\n")
247
Greg Wardfe6462c2000-04-04 01:40:52 +0000248 # Now work on the rest of the attributes. Any attribute that's
249 # not already defined is invalid!
Tarek Ziadéf11be752009-06-01 22:36:26 +0000250 for (key, val) in attrs.items():
Fred Drakedb7b0022005-03-20 22:19:47 +0000251 if hasattr(self.metadata, "set_" + key):
252 getattr(self.metadata, "set_" + key)(val)
253 elif hasattr(self.metadata, key):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000254 setattr(self.metadata, key, val)
255 elif hasattr(self, key):
256 setattr(self, key, val)
Anthony Baxter73cc8472004-10-13 13:22:34 +0000257 else:
Andrew M. Kuchlingff4ad9a2002-10-31 13:22:41 +0000258 msg = "Unknown distribution option: %s" % repr(key)
259 if warnings is not None:
260 warnings.warn(msg)
261 else:
262 sys.stderr.write(msg + "\n")
Greg Wardfe6462c2000-04-04 01:40:52 +0000263
Andrew Kuchling2a1838b2013-11-10 18:11:00 -0500264 # no-user-cfg is handled before other command line args
265 # because other args override the config files, and this
266 # one is needed before we can load the config files.
267 # If attrs['script_args'] wasn't passed, assume false.
268 #
269 # This also make sure we just look at the global options
270 self.want_user_cfg = True
271
272 if self.script_args is not None:
273 for arg in self.script_args:
274 if not arg.startswith('-'):
275 break
276 if arg == '--no-user-cfg':
277 self.want_user_cfg = False
278 break
279
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000280 self.finalize_options()
Fred Drakeb94b8492001-12-06 20:51:35 +0000281
Tarek Ziadé188789d2009-05-16 18:37:32 +0000282 def get_option_dict(self, command):
Greg Ward0e48cfd2000-05-26 01:00:15 +0000283 """Get the option dictionary for a given command. If that
284 command's option dictionary hasn't been created yet, then create it
285 and return the new dictionary; otherwise, return the existing
286 option dictionary.
287 """
Greg Ward0e48cfd2000-05-26 01:00:15 +0000288 dict = self.command_options.get(command)
289 if dict is None:
290 dict = self.command_options[command] = {}
291 return dict
292
Tarek Ziadé188789d2009-05-16 18:37:32 +0000293 def dump_option_dicts(self, header=None, commands=None, indent=""):
Greg Wardc32d9a62000-05-28 23:53:06 +0000294 from pprint import pformat
295
296 if commands is None: # dump all command option dicts
Guido van Rossumd4ee1672007-10-15 01:27:53 +0000297 commands = sorted(self.command_options.keys())
Greg Wardc32d9a62000-05-28 23:53:06 +0000298
299 if header is not None:
Tarek Ziadéf11be752009-06-01 22:36:26 +0000300 self.announce(indent + header)
Greg Wardc32d9a62000-05-28 23:53:06 +0000301 indent = indent + " "
302
303 if not commands:
Tarek Ziadéf11be752009-06-01 22:36:26 +0000304 self.announce(indent + "no commands known yet")
Greg Wardc32d9a62000-05-28 23:53:06 +0000305 return
306
307 for cmd_name in commands:
308 opt_dict = self.command_options.get(cmd_name)
309 if opt_dict is None:
Tarek Ziadéf11be752009-06-01 22:36:26 +0000310 self.announce(indent +
311 "no option dict for '%s' command" % cmd_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000312 else:
Tarek Ziadéf11be752009-06-01 22:36:26 +0000313 self.announce(indent +
314 "option dict for '%s' command:" % cmd_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000315 out = pformat(opt_dict)
Tarek Ziadéf11be752009-06-01 22:36:26 +0000316 for line in out.split('\n'):
317 self.announce(indent + " " + line)
Greg Wardc32d9a62000-05-28 23:53:06 +0000318
Greg Wardd5d8a992000-05-23 01:42:17 +0000319 # -- Config file finding/parsing methods ---------------------------
320
Tarek Ziadé188789d2009-05-16 18:37:32 +0000321 def find_config_files(self):
Gregory P. Smith14263542000-05-12 00:41:33 +0000322 """Find as many configuration files as should be processed for this
323 platform, and return a list of filenames in the order in which they
324 should be parsed. The filenames returned are guaranteed to exist
325 (modulo nasty race conditions).
326
Andrew M. Kuchlingd303b612001-12-06 16:32:05 +0000327 There are three possible config files: distutils.cfg in the
328 Distutils installation directory (ie. where the top-level
329 Distutils __inst__.py file lives), a file in the user's home
330 directory named .pydistutils.cfg on Unix and pydistutils.cfg
Andrew Kuchling2a1838b2013-11-10 18:11:00 -0500331 on Windows/Mac; and setup.cfg in the current directory.
332
333 The file in the user's home directory can be disabled with the
334 --no-user-cfg option.
Greg Wardd5d8a992000-05-23 01:42:17 +0000335 """
Gregory P. Smith14263542000-05-12 00:41:33 +0000336 files = []
Greg Wardacf3f6a2000-06-07 02:26:19 +0000337 check_environ()
Gregory P. Smith14263542000-05-12 00:41:33 +0000338
Greg Ward11696872000-06-07 02:29:03 +0000339 # Where to look for the system-wide Distutils config file
340 sys_dir = os.path.dirname(sys.modules['distutils'].__file__)
341
342 # Look for the system config file
343 sys_file = os.path.join(sys_dir, "distutils.cfg")
Greg Wardacf3f6a2000-06-07 02:26:19 +0000344 if os.path.isfile(sys_file):
345 files.append(sys_file)
Gregory P. Smith14263542000-05-12 00:41:33 +0000346
Greg Ward11696872000-06-07 02:29:03 +0000347 # What to call the per-user config file
348 if os.name == 'posix':
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000349 user_filename = ".pydistutils.cfg"
350 else:
351 user_filename = "pydistutils.cfg"
Greg Wardfa9ff762000-10-14 04:06:40 +0000352
Greg Ward11696872000-06-07 02:29:03 +0000353 # And look for the user config file
Andrew Kuchling2a1838b2013-11-10 18:11:00 -0500354 if self.want_user_cfg:
355 user_file = os.path.join(os.path.expanduser('~'), user_filename)
356 if os.path.isfile(user_file):
357 files.append(user_file)
Gregory P. Smith14263542000-05-12 00:41:33 +0000358
Gregory P. Smith14263542000-05-12 00:41:33 +0000359 # All platforms support local setup.cfg
360 local_file = "setup.cfg"
361 if os.path.isfile(local_file):
362 files.append(local_file)
363
Andrew Kuchling2a1838b2013-11-10 18:11:00 -0500364 if DEBUG:
365 self.announce("using config files: %s" % ', '.join(files))
366
Gregory P. Smith14263542000-05-12 00:41:33 +0000367 return files
368
Tarek Ziadé188789d2009-05-16 18:37:32 +0000369 def parse_config_files(self, filenames=None):
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000370 from configparser import ConfigParser
Gregory P. Smith14263542000-05-12 00:41:33 +0000371
Georg Brandl521ed522013-05-12 12:36:07 +0200372 # Ignore install directory options if we have a venv
373 if sys.prefix != sys.base_prefix:
374 ignore_options = [
375 'install-base', 'install-platbase', 'install-lib',
376 'install-platlib', 'install-purelib', 'install-headers',
377 'install-scripts', 'install-data', 'prefix', 'exec-prefix',
378 'home', 'user', 'root']
379 else:
380 ignore_options = []
381
382 ignore_options = frozenset(ignore_options)
383
Gregory P. Smith14263542000-05-12 00:41:33 +0000384 if filenames is None:
385 filenames = self.find_config_files()
386
Tarek Ziadéf11be752009-06-01 22:36:26 +0000387 if DEBUG:
388 self.announce("Distribution.parse_config_files():")
Greg Ward47460772000-05-23 03:47:35 +0000389
Gregory P. Smith14263542000-05-12 00:41:33 +0000390 parser = ConfigParser()
Greg Wardd5d8a992000-05-23 01:42:17 +0000391 for filename in filenames:
Tarek Ziadéf11be752009-06-01 22:36:26 +0000392 if DEBUG:
Tarek Ziadé31d46072009-09-21 13:55:19 +0000393 self.announce(" reading %s" % filename)
Greg Wardd5d8a992000-05-23 01:42:17 +0000394 parser.read(filename)
395 for section in parser.sections():
396 options = parser.options(section)
Greg Ward0e48cfd2000-05-26 01:00:15 +0000397 opt_dict = self.get_option_dict(section)
Gregory P. Smith14263542000-05-12 00:41:33 +0000398
Greg Wardd5d8a992000-05-23 01:42:17 +0000399 for opt in options:
Georg Brandl521ed522013-05-12 12:36:07 +0200400 if opt != '__name__' and opt not in ignore_options:
Greg Wardceb9e222000-09-25 01:23:52 +0000401 val = parser.get(section,opt)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000402 opt = opt.replace('-', '_')
Greg Wardceb9e222000-09-25 01:23:52 +0000403 opt_dict[opt] = (filename, val)
Gregory P. Smith14263542000-05-12 00:41:33 +0000404
Greg Ward47460772000-05-23 03:47:35 +0000405 # Make the ConfigParser forget everything (so we retain
Fred Drakef06116d2004-02-17 22:35:19 +0000406 # the original filenames that options come from)
Greg Ward47460772000-05-23 03:47:35 +0000407 parser.__init__()
Gregory P. Smith14263542000-05-12 00:41:33 +0000408
Greg Wardceb9e222000-09-25 01:23:52 +0000409 # If there was a "global" section in the config file, use it
410 # to set Distribution options.
411
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000412 if 'global' in self.command_options:
Greg Wardceb9e222000-09-25 01:23:52 +0000413 for (opt, (src, val)) in self.command_options['global'].items():
414 alias = self.negative_opt.get(opt)
415 try:
416 if alias:
417 setattr(self, alias, not strtobool(val))
418 elif opt in ('verbose', 'dry_run'): # ugh!
419 setattr(self, opt, strtobool(val))
Fred Draked04573f2004-08-03 16:37:40 +0000420 else:
421 setattr(self, opt, val)
Guido van Rossumb940e112007-01-10 16:19:56 +0000422 except ValueError as msg:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000423 raise DistutilsOptionError(msg)
Greg Wardceb9e222000-09-25 01:23:52 +0000424
Greg Wardd5d8a992000-05-23 01:42:17 +0000425 # -- Command-line parsing methods ----------------------------------
426
Tarek Ziadé188789d2009-05-16 18:37:32 +0000427 def parse_command_line(self):
Greg Ward9821bf42000-08-29 01:15:18 +0000428 """Parse the setup script's command line, taken from the
429 'script_args' instance attribute (which defaults to 'sys.argv[1:]'
430 -- see 'setup()' in core.py). This list is first processed for
431 "global options" -- options that set attributes of the Distribution
432 instance. Then, it is alternately scanned for Distutils commands
433 and options for that command. Each new command terminates the
434 options for the previous command. The allowed options for a
435 command are determined by the 'user_options' attribute of the
436 command class -- thus, we have to be able to load command classes
437 in order to parse the command line. Any error in that 'options'
438 attribute raises DistutilsGetoptError; any error on the
439 command-line raises DistutilsArgError. If no Distutils commands
440 were found on the command line, raises DistutilsArgError. Return
Greg Wardceb9e222000-09-25 01:23:52 +0000441 true if command-line was successfully parsed and we should carry
Greg Ward9821bf42000-08-29 01:15:18 +0000442 on with executing commands; false if no errors but we shouldn't
443 execute commands (currently, this only happens if user asks for
444 help).
Greg Wardd5d8a992000-05-23 01:42:17 +0000445 """
Andrew M. Kuchling3f819ec2001-01-15 16:09:35 +0000446 #
Fred Drake981a1782001-08-10 18:59:30 +0000447 # We now have enough information to show the Macintosh dialog
448 # that allows the user to interactively specify the "command line".
Andrew M. Kuchling3f819ec2001-01-15 16:09:35 +0000449 #
Fred Draked04573f2004-08-03 16:37:40 +0000450 toplevel_options = self._get_toplevel_options()
Fred Drakeb94b8492001-12-06 20:51:35 +0000451
Greg Wardfe6462c2000-04-04 01:40:52 +0000452 # We have to parse the command line a bit at a time -- global
453 # options, then the first command, then its options, and so on --
454 # because each command will be handled by a different class, and
Greg Wardd5d8a992000-05-23 01:42:17 +0000455 # the options that are valid for a particular class aren't known
456 # until we have loaded the command class, which doesn't happen
457 # until we know what the command is.
Greg Wardfe6462c2000-04-04 01:40:52 +0000458
459 self.commands = []
Fred Draked04573f2004-08-03 16:37:40 +0000460 parser = FancyGetopt(toplevel_options + self.display_options)
Greg Wardfd7b91e2000-09-26 01:52:25 +0000461 parser.set_negative_aliases(self.negative_opt)
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +0000462 parser.set_aliases({'licence': 'license'})
Greg Wardfd7b91e2000-09-26 01:52:25 +0000463 args = parser.getopt(args=self.script_args, object=self)
Greg Ward82715e12000-04-21 02:28:14 +0000464 option_order = parser.get_option_order()
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000465 log.set_verbosity(self.verbose)
Greg Wardfe6462c2000-04-04 01:40:52 +0000466
Greg Ward82715e12000-04-21 02:28:14 +0000467 # for display options we return immediately
468 if self.handle_display_options(option_order):
Greg Wardfe6462c2000-04-04 01:40:52 +0000469 return
Greg Wardfe6462c2000-04-04 01:40:52 +0000470 while args:
Greg Wardd5d8a992000-05-23 01:42:17 +0000471 args = self._parse_command_opts(parser, args)
472 if args is None: # user asked for help (and got it)
Greg Wardfe6462c2000-04-04 01:40:52 +0000473 return
Greg Wardfe6462c2000-04-04 01:40:52 +0000474
Greg Wardd5d8a992000-05-23 01:42:17 +0000475 # Handle the cases of --help as a "global" option, ie.
476 # "setup.py --help" and "setup.py --help command ...". For the
477 # former, we show global options (--verbose, --dry-run, etc.)
478 # and display-only options (--name, --version, etc.); for the
479 # latter, we omit the display-only options and show help for
480 # each command listed on the command line.
Greg Wardfe6462c2000-04-04 01:40:52 +0000481 if self.help:
Greg Wardd5d8a992000-05-23 01:42:17 +0000482 self._show_help(parser,
483 display_options=len(self.commands) == 0,
484 commands=self.commands)
Greg Wardfe6462c2000-04-04 01:40:52 +0000485 return
486
487 # Oops, no commands found -- an end-user error
488 if not self.commands:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000489 raise DistutilsArgError("no commands supplied")
Greg Wardfe6462c2000-04-04 01:40:52 +0000490
491 # All is well: return true
Collin Winter5b7e9d72007-08-30 03:52:21 +0000492 return True
Greg Wardfe6462c2000-04-04 01:40:52 +0000493
Tarek Ziadé188789d2009-05-16 18:37:32 +0000494 def _get_toplevel_options(self):
Fred Draked04573f2004-08-03 16:37:40 +0000495 """Return the non-display options recognized at the top level.
496
497 This includes options that are recognized *only* at the top
498 level as well as options recognized for commands.
499 """
500 return self.global_options + [
501 ("command-packages=", None,
502 "list of packages that provide distutils commands"),
503 ]
504
Tarek Ziadé188789d2009-05-16 18:37:32 +0000505 def _parse_command_opts(self, parser, args):
Greg Wardd5d8a992000-05-23 01:42:17 +0000506 """Parse the command-line options for a single command.
507 'parser' must be a FancyGetopt instance; 'args' must be the list
508 of arguments, starting with the current command (whose options
509 we are about to parse). Returns a new version of 'args' with
510 the next command at the front of the list; will be the empty
511 list if there are no more commands on the command line. Returns
512 None if the user asked for help on this command.
513 """
514 # late import because of mutual dependence between these modules
515 from distutils.cmd import Command
516
517 # Pull the current command from the head of the command line
518 command = args[0]
Greg Wardfd7b91e2000-09-26 01:52:25 +0000519 if not command_re.match(command):
Collin Winter5b7e9d72007-08-30 03:52:21 +0000520 raise SystemExit("invalid command name '%s'" % command)
Greg Wardfd7b91e2000-09-26 01:52:25 +0000521 self.commands.append(command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000522
523 # Dig up the command class that implements this command, so we
524 # 1) know that it's a valid command, and 2) know which options
525 # it takes.
526 try:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000527 cmd_class = self.get_command_class(command)
Guido van Rossumb940e112007-01-10 16:19:56 +0000528 except DistutilsModuleError as msg:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000529 raise DistutilsArgError(msg)
Greg Wardd5d8a992000-05-23 01:42:17 +0000530
531 # Require that the command class be derived from Command -- want
532 # to be sure that the basic "command" interface is implemented.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000533 if not issubclass(cmd_class, Command):
Collin Winter5b7e9d72007-08-30 03:52:21 +0000534 raise DistutilsClassError(
535 "command class %s must subclass Command" % cmd_class)
Greg Wardd5d8a992000-05-23 01:42:17 +0000536
537 # Also make sure that the command object provides a list of its
538 # known options.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000539 if not (hasattr(cmd_class, 'user_options') and
Guido van Rossum13257902007-06-07 23:15:56 +0000540 isinstance(cmd_class.user_options, list)):
Collin Winter5b7e9d72007-08-30 03:52:21 +0000541 raise DistutilsClassError(("command class %s must provide " +
Greg Wardd5d8a992000-05-23 01:42:17 +0000542 "'user_options' attribute (a list of tuples)") % \
Collin Winter5b7e9d72007-08-30 03:52:21 +0000543 cmd_class)
Greg Wardd5d8a992000-05-23 01:42:17 +0000544
545 # If the command class has a list of negative alias options,
546 # merge it in with the global negative aliases.
547 negative_opt = self.negative_opt
Greg Wardfd7b91e2000-09-26 01:52:25 +0000548 if hasattr(cmd_class, 'negative_opt'):
Antoine Pitrou56a00de2009-05-15 17:34:21 +0000549 negative_opt = negative_opt.copy()
Greg Wardfd7b91e2000-09-26 01:52:25 +0000550 negative_opt.update(cmd_class.negative_opt)
Greg Wardd5d8a992000-05-23 01:42:17 +0000551
Greg Wardfa9ff762000-10-14 04:06:40 +0000552 # Check for help_options in command class. They have a different
553 # format (tuple of four) so we need to preprocess them here.
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000554 if (hasattr(cmd_class, 'help_options') and
Guido van Rossum13257902007-06-07 23:15:56 +0000555 isinstance(cmd_class.help_options, list)):
Greg Ward2ff78872000-06-24 00:23:20 +0000556 help_options = fix_help_options(cmd_class.help_options)
557 else:
Greg Ward55fced32000-06-24 01:22:41 +0000558 help_options = []
Greg Ward2ff78872000-06-24 00:23:20 +0000559
Greg Ward9d17a7a2000-06-07 03:00:06 +0000560
Greg Wardd5d8a992000-05-23 01:42:17 +0000561 # All commands support the global options too, just by adding
562 # in 'global_options'.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000563 parser.set_option_table(self.global_options +
564 cmd_class.user_options +
565 help_options)
566 parser.set_negative_aliases(negative_opt)
567 (args, opts) = parser.getopt(args[1:])
Greg Ward47460772000-05-23 03:47:35 +0000568 if hasattr(opts, 'help') and opts.help:
Greg Wardd5d8a992000-05-23 01:42:17 +0000569 self._show_help(parser, display_options=0, commands=[cmd_class])
570 return
571
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000572 if (hasattr(cmd_class, 'help_options') and
Guido van Rossum13257902007-06-07 23:15:56 +0000573 isinstance(cmd_class.help_options, list)):
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000574 help_option_found=0
575 for (help_option, short, desc, func) in cmd_class.help_options:
576 if hasattr(opts, parser.get_attr_name(help_option)):
577 help_option_found=1
Florent Xicluna5d1155c2011-10-28 14:45:05 +0200578 if callable(func):
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000579 func()
Greg Ward55fced32000-06-24 01:22:41 +0000580 else:
Fred Drake981a1782001-08-10 18:59:30 +0000581 raise DistutilsClassError(
Walter Dörwald70a6b492004-02-12 17:35:32 +0000582 "invalid help function %r for help option '%s': "
Fred Drake981a1782001-08-10 18:59:30 +0000583 "must be a callable object (function, etc.)"
Walter Dörwald70a6b492004-02-12 17:35:32 +0000584 % (func, help_option))
Greg Ward55fced32000-06-24 01:22:41 +0000585
Fred Drakeb94b8492001-12-06 20:51:35 +0000586 if help_option_found:
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000587 return
Greg Ward9d17a7a2000-06-07 03:00:06 +0000588
Greg Wardd5d8a992000-05-23 01:42:17 +0000589 # Put the options from the command-line into their official
590 # holding pen, the 'command_options' dictionary.
Greg Ward0e48cfd2000-05-26 01:00:15 +0000591 opt_dict = self.get_option_dict(command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000592 for (name, value) in vars(opts).items():
Greg Ward0e48cfd2000-05-26 01:00:15 +0000593 opt_dict[name] = ("command line", value)
Greg Wardd5d8a992000-05-23 01:42:17 +0000594
595 return args
596
Tarek Ziadé188789d2009-05-16 18:37:32 +0000597 def finalize_options(self):
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000598 """Set final values for all the options on the Distribution
599 instance, analogous to the .finalize_options() method of Command
600 objects.
601 """
Tarek Ziadéf11be752009-06-01 22:36:26 +0000602 for attr in ('keywords', 'platforms'):
603 value = getattr(self.metadata, attr)
604 if value is None:
605 continue
606 if isinstance(value, str):
607 value = [elm.strip() for elm in value.split(',')]
608 setattr(self.metadata, attr, value)
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000609
Tarek Ziadé188789d2009-05-16 18:37:32 +0000610 def _show_help(self, parser, global_options=1, display_options=1,
611 commands=[]):
Greg Wardd5d8a992000-05-23 01:42:17 +0000612 """Show help for the setup script command-line in the form of
613 several lists of command-line options. 'parser' should be a
614 FancyGetopt instance; do not expect it to be returned in the
615 same state, as its option table will be reset to make it
616 generate the correct help text.
617
618 If 'global_options' is true, lists the global options:
619 --verbose, --dry-run, etc. If 'display_options' is true, lists
620 the "display-only" options: --name, --version, etc. Finally,
621 lists per-command help for every command name or command class
622 in 'commands'.
623 """
624 # late import because of mutual dependence between these modules
Greg Ward9821bf42000-08-29 01:15:18 +0000625 from distutils.core import gen_usage
Greg Wardd5d8a992000-05-23 01:42:17 +0000626 from distutils.cmd import Command
627
628 if global_options:
Fred Draked04573f2004-08-03 16:37:40 +0000629 if display_options:
630 options = self._get_toplevel_options()
631 else:
632 options = self.global_options
633 parser.set_option_table(options)
Martin v. Löwis8ed338a2005-03-03 08:12:27 +0000634 parser.print_help(self.common_usage + "\nGlobal options:")
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000635 print('')
Greg Wardd5d8a992000-05-23 01:42:17 +0000636
637 if display_options:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000638 parser.set_option_table(self.display_options)
639 parser.print_help(
Greg Wardd5d8a992000-05-23 01:42:17 +0000640 "Information display options (just display " +
641 "information, ignore any commands)")
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000642 print('')
Greg Wardd5d8a992000-05-23 01:42:17 +0000643
644 for command in self.commands:
Guido van Rossum13257902007-06-07 23:15:56 +0000645 if isinstance(command, type) and issubclass(command, Command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000646 klass = command
647 else:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000648 klass = self.get_command_class(command)
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000649 if (hasattr(klass, 'help_options') and
Guido van Rossum13257902007-06-07 23:15:56 +0000650 isinstance(klass.help_options, list)):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000651 parser.set_option_table(klass.user_options +
652 fix_help_options(klass.help_options))
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000653 else:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000654 parser.set_option_table(klass.user_options)
655 parser.print_help("Options for '%s' command:" % klass.__name__)
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000656 print('')
Greg Wardd5d8a992000-05-23 01:42:17 +0000657
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000658 print(gen_usage(self.script_name))
Greg Wardd5d8a992000-05-23 01:42:17 +0000659
Tarek Ziadé188789d2009-05-16 18:37:32 +0000660 def handle_display_options(self, option_order):
Greg Ward82715e12000-04-21 02:28:14 +0000661 """If there were any non-global "display-only" options
Greg Wardd5d8a992000-05-23 01:42:17 +0000662 (--help-commands or the metadata display options) on the command
663 line, display the requested info and return true; else return
664 false.
665 """
Greg Ward9821bf42000-08-29 01:15:18 +0000666 from distutils.core import gen_usage
Greg Ward82715e12000-04-21 02:28:14 +0000667
668 # User just wants a list of commands -- we'll print it out and stop
669 # processing now (ie. if they ran "setup --help-commands foo bar",
670 # we ignore "foo bar").
671 if self.help_commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000672 self.print_commands()
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000673 print('')
674 print(gen_usage(self.script_name))
Greg Ward82715e12000-04-21 02:28:14 +0000675 return 1
676
677 # If user supplied any of the "display metadata" options, then
678 # display that metadata in the order in which the user supplied the
679 # metadata options.
680 any_display_options = 0
681 is_display_option = {}
682 for option in self.display_options:
683 is_display_option[option[0]] = 1
684
685 for (opt, val) in option_order:
686 if val and is_display_option.get(opt):
Greg Ward2f2b6c62000-09-25 01:58:07 +0000687 opt = translate_longopt(opt)
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000688 value = getattr(self.metadata, "get_"+opt)()
689 if opt in ['keywords', 'platforms']:
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000690 print(','.join(value))
Fred Drakedb7b0022005-03-20 22:19:47 +0000691 elif opt in ('classifiers', 'provides', 'requires',
692 'obsoletes'):
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000693 print('\n'.join(value))
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000694 else:
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000695 print(value)
Greg Ward82715e12000-04-21 02:28:14 +0000696 any_display_options = 1
697
698 return any_display_options
699
Tarek Ziadé188789d2009-05-16 18:37:32 +0000700 def print_command_list(self, commands, header, max_length):
Greg Wardfe6462c2000-04-04 01:40:52 +0000701 """Print a subset of the list of all commands -- used by
Greg Wardd5d8a992000-05-23 01:42:17 +0000702 'print_commands()'.
703 """
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000704 print(header + ":")
Greg Wardfe6462c2000-04-04 01:40:52 +0000705
706 for cmd in commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000707 klass = self.cmdclass.get(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000708 if not klass:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000709 klass = self.get_command_class(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000710 try:
711 description = klass.description
712 except AttributeError:
713 description = "(no description available)"
714
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000715 print(" %-*s %s" % (max_length, cmd, description))
Greg Wardfe6462c2000-04-04 01:40:52 +0000716
Tarek Ziadé188789d2009-05-16 18:37:32 +0000717 def print_commands(self):
Greg Wardd5d8a992000-05-23 01:42:17 +0000718 """Print out a help message listing all available commands with a
719 description of each. The list is divided into "standard commands"
720 (listed in distutils.command.__all__) and "extra commands"
721 (mentioned in self.cmdclass, but not a standard command). The
722 descriptions come from the command class attribute
723 'description'.
724 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000725 import distutils.command
726 std_commands = distutils.command.__all__
727 is_std = {}
728 for cmd in std_commands:
729 is_std[cmd] = 1
730
731 extra_commands = []
732 for cmd in self.cmdclass.keys():
733 if not is_std.get(cmd):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000734 extra_commands.append(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000735
736 max_length = 0
737 for cmd in (std_commands + extra_commands):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000738 if len(cmd) > max_length:
739 max_length = len(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000740
Greg Wardfd7b91e2000-09-26 01:52:25 +0000741 self.print_command_list(std_commands,
742 "Standard commands",
743 max_length)
Greg Wardfe6462c2000-04-04 01:40:52 +0000744 if extra_commands:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000745 print()
Greg Wardfd7b91e2000-09-26 01:52:25 +0000746 self.print_command_list(extra_commands,
747 "Extra commands",
748 max_length)
Greg Wardfe6462c2000-04-04 01:40:52 +0000749
Tarek Ziadé188789d2009-05-16 18:37:32 +0000750 def get_command_list(self):
Greg Wardf6fc8752000-11-11 02:47:11 +0000751 """Get a list of (command, description) tuples.
752 The list is divided into "standard commands" (listed in
753 distutils.command.__all__) and "extra commands" (mentioned in
754 self.cmdclass, but not a standard command). The descriptions come
755 from the command class attribute 'description'.
756 """
757 # Currently this is only used on Mac OS, for the Mac-only GUI
758 # Distutils interface (by Jack Jansen)
Greg Wardf6fc8752000-11-11 02:47:11 +0000759 import distutils.command
760 std_commands = distutils.command.__all__
761 is_std = {}
762 for cmd in std_commands:
763 is_std[cmd] = 1
764
765 extra_commands = []
766 for cmd in self.cmdclass.keys():
767 if not is_std.get(cmd):
768 extra_commands.append(cmd)
769
770 rv = []
771 for cmd in (std_commands + extra_commands):
772 klass = self.cmdclass.get(cmd)
773 if not klass:
774 klass = self.get_command_class(cmd)
775 try:
776 description = klass.description
777 except AttributeError:
778 description = "(no description available)"
779 rv.append((cmd, description))
780 return rv
Greg Wardfe6462c2000-04-04 01:40:52 +0000781
782 # -- Command class/object methods ----------------------------------
783
Tarek Ziadé188789d2009-05-16 18:37:32 +0000784 def get_command_packages(self):
Fred Draked04573f2004-08-03 16:37:40 +0000785 """Return a list of packages from which commands are loaded."""
786 pkgs = self.command_packages
Tarek Ziadéf11be752009-06-01 22:36:26 +0000787 if not isinstance(pkgs, list):
788 if pkgs is None:
789 pkgs = ''
790 pkgs = [pkg.strip() for pkg in pkgs.split(',') if pkg != '']
Fred Draked04573f2004-08-03 16:37:40 +0000791 if "distutils.command" not in pkgs:
792 pkgs.insert(0, "distutils.command")
793 self.command_packages = pkgs
794 return pkgs
795
Tarek Ziadé188789d2009-05-16 18:37:32 +0000796 def get_command_class(self, command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000797 """Return the class that implements the Distutils command named by
798 'command'. First we check the 'cmdclass' dictionary; if the
799 command is mentioned there, we fetch the class object from the
800 dictionary and return it. Otherwise we load the command module
801 ("distutils.command." + command) and fetch the command class from
802 the module. The loaded class is also stored in 'cmdclass'
803 to speed future calls to 'get_command_class()'.
Greg Wardfe6462c2000-04-04 01:40:52 +0000804
Gregory P. Smith14263542000-05-12 00:41:33 +0000805 Raises DistutilsModuleError if the expected module could not be
Greg Wardd5d8a992000-05-23 01:42:17 +0000806 found, or if that module does not define the expected class.
807 """
808 klass = self.cmdclass.get(command)
809 if klass:
810 return klass
Greg Wardfe6462c2000-04-04 01:40:52 +0000811
Fred Draked04573f2004-08-03 16:37:40 +0000812 for pkgname in self.get_command_packages():
813 module_name = "%s.%s" % (pkgname, command)
814 klass_name = command
Greg Wardfe6462c2000-04-04 01:40:52 +0000815
Fred Draked04573f2004-08-03 16:37:40 +0000816 try:
817 __import__ (module_name)
818 module = sys.modules[module_name]
819 except ImportError:
820 continue
Greg Wardfe6462c2000-04-04 01:40:52 +0000821
Fred Draked04573f2004-08-03 16:37:40 +0000822 try:
823 klass = getattr(module, klass_name)
824 except AttributeError:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000825 raise DistutilsModuleError(
826 "invalid command '%s' (no class '%s' in module '%s')"
827 % (command, klass_name, module_name))
Greg Wardfe6462c2000-04-04 01:40:52 +0000828
Fred Draked04573f2004-08-03 16:37:40 +0000829 self.cmdclass[command] = klass
830 return klass
831
832 raise DistutilsModuleError("invalid command '%s'" % command)
833
Tarek Ziadé188789d2009-05-16 18:37:32 +0000834 def get_command_obj(self, command, create=1):
Greg Wardd5d8a992000-05-23 01:42:17 +0000835 """Return the command object for 'command'. Normally this object
Greg Ward612eb9f2000-07-27 02:13:20 +0000836 is cached on a previous call to 'get_command_obj()'; if no command
Greg Wardd5d8a992000-05-23 01:42:17 +0000837 object for 'command' is in the cache, then we either create and
838 return it (if 'create' is true) or return None.
839 """
840 cmd_obj = self.command_obj.get(command)
Greg Wardfe6462c2000-04-04 01:40:52 +0000841 if not cmd_obj and create:
Greg Ward2bd3f422000-06-02 01:59:33 +0000842 if DEBUG:
Tarek Ziadéf11be752009-06-01 22:36:26 +0000843 self.announce("Distribution.get_command_obj(): " \
844 "creating '%s' command object" % command)
Greg Ward47460772000-05-23 03:47:35 +0000845
Greg Wardd5d8a992000-05-23 01:42:17 +0000846 klass = self.get_command_class(command)
Greg Ward47460772000-05-23 03:47:35 +0000847 cmd_obj = self.command_obj[command] = klass(self)
848 self.have_run[command] = 0
849
850 # Set any options that were supplied in config files
851 # or on the command line. (NB. support for error
852 # reporting is lame here: any errors aren't reported
853 # until 'finalize_options()' is called, which means
854 # we won't report the source of the error.)
855 options = self.command_options.get(command)
856 if options:
Greg Wardc32d9a62000-05-28 23:53:06 +0000857 self._set_command_options(cmd_obj, options)
Greg Wardfe6462c2000-04-04 01:40:52 +0000858
859 return cmd_obj
860
Tarek Ziadé188789d2009-05-16 18:37:32 +0000861 def _set_command_options(self, command_obj, option_dict=None):
Greg Wardc32d9a62000-05-28 23:53:06 +0000862 """Set the options for 'command_obj' from 'option_dict'. Basically
863 this means copying elements of a dictionary ('option_dict') to
864 attributes of an instance ('command').
865
Greg Wardceb9e222000-09-25 01:23:52 +0000866 'command_obj' must be a Command instance. If 'option_dict' is not
Greg Wardc32d9a62000-05-28 23:53:06 +0000867 supplied, uses the standard option dictionary for this command
868 (from 'self.command_options').
869 """
Greg Wardc32d9a62000-05-28 23:53:06 +0000870 command_name = command_obj.get_command_name()
871 if option_dict is None:
872 option_dict = self.get_option_dict(command_name)
873
Tarek Ziadéf11be752009-06-01 22:36:26 +0000874 if DEBUG:
875 self.announce(" setting options for '%s' command:" % command_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000876 for (option, (source, value)) in option_dict.items():
Tarek Ziadéf11be752009-06-01 22:36:26 +0000877 if DEBUG:
878 self.announce(" %s = %s (from %s)" % (option, value,
879 source))
Greg Wardceb9e222000-09-25 01:23:52 +0000880 try:
Amaury Forgeot d'Arc61cb0872008-07-26 20:09:45 +0000881 bool_opts = [translate_longopt(o)
882 for o in command_obj.boolean_options]
Greg Wardceb9e222000-09-25 01:23:52 +0000883 except AttributeError:
884 bool_opts = []
885 try:
886 neg_opt = command_obj.negative_opt
887 except AttributeError:
888 neg_opt = {}
889
890 try:
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000891 is_string = isinstance(value, str)
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000892 if option in neg_opt and is_string:
Greg Wardceb9e222000-09-25 01:23:52 +0000893 setattr(command_obj, neg_opt[option], not strtobool(value))
Greg Ward2c08cf02000-09-27 00:15:37 +0000894 elif option in bool_opts and is_string:
Greg Wardceb9e222000-09-25 01:23:52 +0000895 setattr(command_obj, option, strtobool(value))
896 elif hasattr(command_obj, option):
897 setattr(command_obj, option, value)
898 else:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000899 raise DistutilsOptionError(
900 "error in %s: command '%s' has no such option '%s'"
901 % (source, command_name, option))
Guido van Rossumb940e112007-01-10 16:19:56 +0000902 except ValueError as msg:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000903 raise DistutilsOptionError(msg)
Greg Wardc32d9a62000-05-28 23:53:06 +0000904
Tarek Ziadé188789d2009-05-16 18:37:32 +0000905 def reinitialize_command(self, command, reinit_subcommands=0):
Greg Wardc32d9a62000-05-28 23:53:06 +0000906 """Reinitializes a command to the state it was in when first
907 returned by 'get_command_obj()': ie., initialized but not yet
Greg Ward7d9c7052000-06-28 01:25:27 +0000908 finalized. This provides the opportunity to sneak option
Greg Wardc32d9a62000-05-28 23:53:06 +0000909 values in programmatically, overriding or supplementing
910 user-supplied values from the config files and command line.
911 You'll have to re-finalize the command object (by calling
912 'finalize_options()' or 'ensure_finalized()') before using it for
Fred Drakeb94b8492001-12-06 20:51:35 +0000913 real.
Greg Wardc32d9a62000-05-28 23:53:06 +0000914
Greg Wardf449ea52000-09-16 15:23:28 +0000915 'command' should be a command name (string) or command object. If
916 'reinit_subcommands' is true, also reinitializes the command's
917 sub-commands, as declared by the 'sub_commands' class attribute (if
918 it has one). See the "install" command for an example. Only
919 reinitializes the sub-commands that actually matter, ie. those
920 whose test predicates return true.
921
Greg Wardc32d9a62000-05-28 23:53:06 +0000922 Returns the reinitialized command object.
923 """
924 from distutils.cmd import Command
925 if not isinstance(command, Command):
926 command_name = command
927 command = self.get_command_obj(command_name)
928 else:
929 command_name = command.get_command_name()
930
931 if not command.finalized:
Greg Ward282c7a02000-06-01 01:09:47 +0000932 return command
Greg Wardc32d9a62000-05-28 23:53:06 +0000933 command.initialize_options()
934 command.finalized = 0
Greg Ward43955c92000-06-06 02:52:36 +0000935 self.have_run[command_name] = 0
Greg Wardc32d9a62000-05-28 23:53:06 +0000936 self._set_command_options(command)
Greg Wardf449ea52000-09-16 15:23:28 +0000937
Greg Wardf449ea52000-09-16 15:23:28 +0000938 if reinit_subcommands:
Greg Wardf449ea52000-09-16 15:23:28 +0000939 for sub in command.get_sub_commands():
Fred Drakeb94b8492001-12-06 20:51:35 +0000940 self.reinitialize_command(sub, reinit_subcommands)
Greg Wardf449ea52000-09-16 15:23:28 +0000941
Greg Wardc32d9a62000-05-28 23:53:06 +0000942 return command
943
Greg Wardfe6462c2000-04-04 01:40:52 +0000944 # -- Methods that operate on the Distribution ----------------------
945
Tarek Ziadé05bf01a2009-07-04 02:04:21 +0000946 def announce(self, msg, level=log.INFO):
947 log.log(level, msg)
Greg Wardfe6462c2000-04-04 01:40:52 +0000948
Tarek Ziadé188789d2009-05-16 18:37:32 +0000949 def run_commands(self):
Greg Ward82715e12000-04-21 02:28:14 +0000950 """Run each command that was seen on the setup script command line.
Greg Wardd5d8a992000-05-23 01:42:17 +0000951 Uses the list of commands found and cache of command objects
Greg Wardfd7b91e2000-09-26 01:52:25 +0000952 created by 'get_command_obj()'.
953 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000954 for cmd in self.commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000955 self.run_command(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000956
Greg Wardfe6462c2000-04-04 01:40:52 +0000957 # -- Methods that operate on its Commands --------------------------
958
Tarek Ziadé188789d2009-05-16 18:37:32 +0000959 def run_command(self, command):
Greg Wardfe6462c2000-04-04 01:40:52 +0000960 """Do whatever it takes to run a command (including nothing at all,
Greg Wardd5d8a992000-05-23 01:42:17 +0000961 if the command has already been run). Specifically: if we have
962 already created and run the command named by 'command', return
963 silently without doing anything. If the command named by 'command'
964 doesn't even have a command object yet, create one. Then invoke
965 'run()' on that command object (or an existing one).
966 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000967 # Already been here, done that? then return silently.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000968 if self.have_run.get(command):
Greg Wardfe6462c2000-04-04 01:40:52 +0000969 return
970
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000971 log.info("running %s", command)
Greg Wardfd7b91e2000-09-26 01:52:25 +0000972 cmd_obj = self.get_command_obj(command)
973 cmd_obj.ensure_finalized()
974 cmd_obj.run()
Greg Wardfe6462c2000-04-04 01:40:52 +0000975 self.have_run[command] = 1
976
977
Greg Wardfe6462c2000-04-04 01:40:52 +0000978 # -- Distribution query methods ------------------------------------
979
Tarek Ziadé188789d2009-05-16 18:37:32 +0000980 def has_pure_modules(self):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000981 return len(self.packages or self.py_modules or []) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000982
Tarek Ziadé188789d2009-05-16 18:37:32 +0000983 def has_ext_modules(self):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000984 return self.ext_modules and len(self.ext_modules) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000985
Tarek Ziadé188789d2009-05-16 18:37:32 +0000986 def has_c_libraries(self):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000987 return self.libraries and len(self.libraries) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000988
Tarek Ziadé188789d2009-05-16 18:37:32 +0000989 def has_modules(self):
Greg Wardfe6462c2000-04-04 01:40:52 +0000990 return self.has_pure_modules() or self.has_ext_modules()
991
Tarek Ziadé188789d2009-05-16 18:37:32 +0000992 def has_headers(self):
Greg Ward51def7d2000-05-27 01:36:14 +0000993 return self.headers and len(self.headers) > 0
994
Tarek Ziadé188789d2009-05-16 18:37:32 +0000995 def has_scripts(self):
Greg Ward44a61bb2000-05-20 15:06:48 +0000996 return self.scripts and len(self.scripts) > 0
997
Tarek Ziadé188789d2009-05-16 18:37:32 +0000998 def has_data_files(self):
Greg Ward44a61bb2000-05-20 15:06:48 +0000999 return self.data_files and len(self.data_files) > 0
1000
Tarek Ziadé188789d2009-05-16 18:37:32 +00001001 def is_pure(self):
Greg Wardfe6462c2000-04-04 01:40:52 +00001002 return (self.has_pure_modules() and
1003 not self.has_ext_modules() and
1004 not self.has_c_libraries())
1005
Greg Ward82715e12000-04-21 02:28:14 +00001006 # -- Metadata query methods ----------------------------------------
1007
1008 # If you're looking for 'get_name()', 'get_version()', and so forth,
1009 # they are defined in a sneaky way: the constructor binds self.get_XXX
1010 # to self.metadata.get_XXX. The actual code is in the
1011 # DistributionMetadata class, below.
1012
Greg Ward82715e12000-04-21 02:28:14 +00001013class DistributionMetadata:
1014 """Dummy class to hold the distribution meta-data: name, version,
Greg Wardfd7b91e2000-09-26 01:52:25 +00001015 author, and so forth.
1016 """
Greg Ward82715e12000-04-21 02:28:14 +00001017
Neil Schemenauera8aefe52001-09-03 15:47:21 +00001018 _METHOD_BASENAMES = ("name", "version", "author", "author_email",
1019 "maintainer", "maintainer_email", "url",
1020 "license", "description", "long_description",
1021 "keywords", "platforms", "fullname", "contact",
Andrew M. Kuchlinga52b8522003-03-03 20:07:27 +00001022 "contact_email", "license", "classifiers",
Fred Drakedb7b0022005-03-20 22:19:47 +00001023 "download_url",
1024 # PEP 314
1025 "provides", "requires", "obsoletes",
1026 )
Neil Schemenauera8aefe52001-09-03 15:47:21 +00001027
Jason R. Coombs3492e392013-11-10 18:15:03 -05001028 def __init__(self, path=None):
1029 if path is not None:
1030 self.read_pkg_file(open(path))
1031 else:
1032 self.name = None
1033 self.version = None
1034 self.author = None
1035 self.author_email = None
1036 self.maintainer = None
1037 self.maintainer_email = None
1038 self.url = None
1039 self.license = None
1040 self.description = None
1041 self.long_description = None
1042 self.keywords = None
1043 self.platforms = None
1044 self.classifiers = None
1045 self.download_url = None
1046 # PEP 314
1047 self.provides = None
1048 self.requires = None
1049 self.obsoletes = None
1050
1051 def read_pkg_file(self, file):
1052 """Reads the metadata values from a file object."""
1053 msg = message_from_file(file)
1054
1055 def _read_field(name):
1056 value = msg[name]
1057 if value == 'UNKNOWN':
1058 return None
1059 return value
1060
1061 def _read_list(name):
1062 values = msg.get_all(name, None)
1063 if values == []:
1064 return None
1065 return values
1066
1067 metadata_version = msg['metadata-version']
1068 self.name = _read_field('name')
1069 self.version = _read_field('version')
1070 self.description = _read_field('summary')
1071 # we are filling author only.
1072 self.author = _read_field('author')
Greg Ward82715e12000-04-21 02:28:14 +00001073 self.maintainer = None
Jason R. Coombs3492e392013-11-10 18:15:03 -05001074 self.author_email = _read_field('author-email')
Greg Ward82715e12000-04-21 02:28:14 +00001075 self.maintainer_email = None
Jason R. Coombs3492e392013-11-10 18:15:03 -05001076 self.url = _read_field('home-page')
1077 self.license = _read_field('license')
1078
1079 if 'download-url' in msg:
1080 self.download_url = _read_field('download-url')
1081 else:
1082 self.download_url = None
1083
1084 self.long_description = _read_field('description')
1085 self.description = _read_field('summary')
1086
1087 if 'keywords' in msg:
1088 self.keywords = _read_field('keywords').split(',')
1089
1090 self.platforms = _read_list('platform')
1091 self.classifiers = _read_list('classifier')
1092
1093 # PEP 314 - these fields only exist in 1.1
1094 if metadata_version == '1.1':
1095 self.requires = _read_list('requires')
1096 self.provides = _read_list('provides')
1097 self.obsoletes = _read_list('obsoletes')
1098 else:
1099 self.requires = None
1100 self.provides = None
1101 self.obsoletes = None
Fred Drakeb94b8492001-12-06 20:51:35 +00001102
Tarek Ziadé188789d2009-05-16 18:37:32 +00001103 def write_pkg_info(self, base_dir):
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001104 """Write the PKG-INFO file into the release tree.
1105 """
Victor Stinnera1bea6e2011-09-05 23:44:56 +02001106 with open(os.path.join(base_dir, 'PKG-INFO'), 'w',
1107 encoding='UTF-8') as pkg_info:
Éric Araujobee5cef2010-11-05 23:51:56 +00001108 self.write_pkg_file(pkg_info)
Fred Drakeb94b8492001-12-06 20:51:35 +00001109
Tarek Ziadé188789d2009-05-16 18:37:32 +00001110 def write_pkg_file(self, file):
Fred Drakedb7b0022005-03-20 22:19:47 +00001111 """Write the PKG-INFO format data to a file object.
1112 """
1113 version = '1.0'
Éric Araujo13e8c8e2011-09-10 01:51:40 +02001114 if (self.provides or self.requires or self.obsoletes or
1115 self.classifiers or self.download_url):
Fred Drakedb7b0022005-03-20 22:19:47 +00001116 version = '1.1'
1117
1118 file.write('Metadata-Version: %s\n' % version)
1119 file.write('Name: %s\n' % self.get_name() )
1120 file.write('Version: %s\n' % self.get_version() )
1121 file.write('Summary: %s\n' % self.get_description() )
1122 file.write('Home-page: %s\n' % self.get_url() )
1123 file.write('Author: %s\n' % self.get_contact() )
1124 file.write('Author-email: %s\n' % self.get_contact_email() )
1125 file.write('License: %s\n' % self.get_license() )
1126 if self.download_url:
1127 file.write('Download-URL: %s\n' % self.download_url)
1128
Tarek Ziadéf11be752009-06-01 22:36:26 +00001129 long_desc = rfc822_escape(self.get_long_description())
Fred Drakedb7b0022005-03-20 22:19:47 +00001130 file.write('Description: %s\n' % long_desc)
1131
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001132 keywords = ','.join(self.get_keywords())
Fred Drakedb7b0022005-03-20 22:19:47 +00001133 if keywords:
1134 file.write('Keywords: %s\n' % keywords )
1135
1136 self._write_list(file, 'Platform', self.get_platforms())
1137 self._write_list(file, 'Classifier', self.get_classifiers())
1138
1139 # PEP 314
1140 self._write_list(file, 'Requires', self.get_requires())
1141 self._write_list(file, 'Provides', self.get_provides())
1142 self._write_list(file, 'Obsoletes', self.get_obsoletes())
1143
Tarek Ziadé188789d2009-05-16 18:37:32 +00001144 def _write_list(self, file, name, values):
Fred Drakedb7b0022005-03-20 22:19:47 +00001145 for value in values:
1146 file.write('%s: %s\n' % (name, value))
1147
Greg Ward82715e12000-04-21 02:28:14 +00001148 # -- Metadata query methods ----------------------------------------
1149
Tarek Ziadé188789d2009-05-16 18:37:32 +00001150 def get_name(self):
Greg Wardfe6462c2000-04-04 01:40:52 +00001151 return self.name or "UNKNOWN"
1152
Greg Ward82715e12000-04-21 02:28:14 +00001153 def get_version(self):
Thomas Hellerbcd89752001-12-06 20:44:19 +00001154 return self.version or "0.0.0"
Greg Wardfe6462c2000-04-04 01:40:52 +00001155
Tarek Ziadé188789d2009-05-16 18:37:32 +00001156 def get_fullname(self):
Greg Ward82715e12000-04-21 02:28:14 +00001157 return "%s-%s" % (self.get_name(), self.get_version())
1158
1159 def get_author(self):
1160 return self.author or "UNKNOWN"
1161
1162 def get_author_email(self):
1163 return self.author_email or "UNKNOWN"
1164
1165 def get_maintainer(self):
1166 return self.maintainer or "UNKNOWN"
1167
1168 def get_maintainer_email(self):
1169 return self.maintainer_email or "UNKNOWN"
1170
1171 def get_contact(self):
Tarek Ziadé188789d2009-05-16 18:37:32 +00001172 return self.maintainer or self.author or "UNKNOWN"
Greg Ward82715e12000-04-21 02:28:14 +00001173
1174 def get_contact_email(self):
Tarek Ziadé188789d2009-05-16 18:37:32 +00001175 return self.maintainer_email or self.author_email or "UNKNOWN"
Greg Ward82715e12000-04-21 02:28:14 +00001176
1177 def get_url(self):
1178 return self.url or "UNKNOWN"
1179
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +00001180 def get_license(self):
1181 return self.license or "UNKNOWN"
1182 get_licence = get_license
Fred Drakeb94b8492001-12-06 20:51:35 +00001183
Greg Ward82715e12000-04-21 02:28:14 +00001184 def get_description(self):
1185 return self.description or "UNKNOWN"
Greg Warde5a584e2000-04-26 02:26:55 +00001186
1187 def get_long_description(self):
1188 return self.long_description or "UNKNOWN"
1189
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001190 def get_keywords(self):
1191 return self.keywords or []
1192
1193 def get_platforms(self):
1194 return self.platforms or ["UNKNOWN"]
1195
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +00001196 def get_classifiers(self):
1197 return self.classifiers or []
1198
Andrew M. Kuchling188d85f2003-02-19 14:16:01 +00001199 def get_download_url(self):
1200 return self.download_url or "UNKNOWN"
1201
Fred Drakedb7b0022005-03-20 22:19:47 +00001202 # PEP 314
Fred Drakedb7b0022005-03-20 22:19:47 +00001203 def get_requires(self):
1204 return self.requires or []
1205
1206 def set_requires(self, value):
1207 import distutils.versionpredicate
1208 for v in value:
1209 distutils.versionpredicate.VersionPredicate(v)
1210 self.requires = value
1211
1212 def get_provides(self):
1213 return self.provides or []
1214
1215 def set_provides(self, value):
1216 value = [v.strip() for v in value]
1217 for v in value:
1218 import distutils.versionpredicate
Fred Drake227e8ff2005-03-21 06:36:32 +00001219 distutils.versionpredicate.split_provision(v)
Fred Drakedb7b0022005-03-20 22:19:47 +00001220 self.provides = value
1221
1222 def get_obsoletes(self):
1223 return self.obsoletes or []
1224
1225 def set_obsoletes(self, value):
1226 import distutils.versionpredicate
1227 for v in value:
1228 distutils.versionpredicate.VersionPredicate(v)
1229 self.obsoletes = value
1230
Tarek Ziadé188789d2009-05-16 18:37:32 +00001231def fix_help_options(options):
Greg Ward2ff78872000-06-24 00:23:20 +00001232 """Convert a 4-tuple 'help_options' list as found in various command
1233 classes to the 3-tuple form required by FancyGetopt.
1234 """
1235 new_options = []
1236 for help_tuple in options:
1237 new_options.append(help_tuple[0:3])
1238 return new_options