blob: 65c1ce912ed3c72c1a6f9c4f28a25f7c7efccbfc [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
Andrew M. Kuchlingff4ad9a2002-10-31 13:22:41 +000010
11try:
12 import warnings
Andrew M. Kuchlingccf4e422002-10-31 13:39:33 +000013except ImportError:
Andrew M. Kuchlingff4ad9a2002-10-31 13:22:41 +000014 warnings = None
15
Greg Wardfe6462c2000-04-04 01:40:52 +000016from distutils.errors import *
Greg Ward2f2b6c62000-09-25 01:58:07 +000017from distutils.fancy_getopt import FancyGetopt, translate_longopt
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +000018from distutils.util import check_environ, strtobool, rfc822_escape
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000019from distutils import log
Jeremy Hyltonfcd73532002-09-11 16:31:53 +000020from distutils.debug import DEBUG
Greg Wardfe6462c2000-04-04 01:40:52 +000021
22# Regex to define acceptable Distutils command names. This is not *quite*
23# the same as a Python NAME -- I don't allow leading underscores. The fact
24# that they're very similar is no coincidence; the default naming scheme is
25# to look for a Python module named after the command.
26command_re = re.compile (r'^[a-zA-Z]([a-zA-Z0-9_]*)$')
27
28
29class Distribution:
Greg Ward8ff5a3f2000-06-02 00:44:53 +000030 """The core of the Distutils. Most of the work hiding behind 'setup'
31 is really done within a Distribution instance, which farms the work out
32 to the Distutils commands specified on the command line.
Greg Wardfe6462c2000-04-04 01:40:52 +000033
Greg Ward8ff5a3f2000-06-02 00:44:53 +000034 Setup scripts will almost never instantiate Distribution directly,
35 unless the 'setup()' function is totally inadequate to their needs.
36 However, it is conceivable that a setup script might wish to subclass
37 Distribution for some specialized purpose, and then pass the subclass
38 to 'setup()' as the 'distclass' keyword argument. If so, it is
39 necessary to respect the expectations that 'setup' has of Distribution.
40 See the code for 'setup()', in core.py, for details.
41 """
Greg Wardfe6462c2000-04-04 01:40:52 +000042
43
44 # 'global_options' describes the command-line options that may be
Greg Ward82715e12000-04-21 02:28:14 +000045 # supplied to the setup script prior to any actual commands.
46 # Eg. "./setup.py -n" or "./setup.py --quiet" both take advantage of
Greg Wardfe6462c2000-04-04 01:40:52 +000047 # these global options. This list should be kept to a bare minimum,
48 # since every global option is also valid as a command option -- and we
49 # don't want to pollute the commands with too many options that they
50 # have minimal control over.
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000051 # The fourth entry for verbose means that it can be repeated.
52 global_options = [('verbose', 'v', "run verbosely (default)", 1),
Greg Wardd5d8a992000-05-23 01:42:17 +000053 ('quiet', 'q', "run quietly (turns verbosity off)"),
54 ('dry-run', 'n', "don't actually do anything"),
55 ('help', 'h', "show detailed help message"),
Greg Wardfe6462c2000-04-04 01:40:52 +000056 ]
Greg Ward82715e12000-04-21 02:28:14 +000057
Martin v. Löwis8ed338a2005-03-03 08:12:27 +000058 # 'common_usage' is a short (2-3 line) string describing the common
59 # usage of the setup script.
60 common_usage = """\
61Common commands: (see '--help-commands' for more)
62
63 setup.py build will build the package underneath 'build/'
64 setup.py install will install the package
65"""
66
Greg Ward82715e12000-04-21 02:28:14 +000067 # options that are not propagated to the commands
68 display_options = [
69 ('help-commands', None,
70 "list all available commands"),
71 ('name', None,
72 "print package name"),
73 ('version', 'V',
74 "print package version"),
75 ('fullname', None,
76 "print <package name>-<version>"),
77 ('author', None,
78 "print the author's name"),
79 ('author-email', None,
80 "print the author's email address"),
81 ('maintainer', None,
82 "print the maintainer's name"),
83 ('maintainer-email', None,
84 "print the maintainer's email address"),
85 ('contact', None,
Greg Wardd5d8a992000-05-23 01:42:17 +000086 "print the maintainer's name if known, else the author's"),
Greg Ward82715e12000-04-21 02:28:14 +000087 ('contact-email', None,
Greg Wardd5d8a992000-05-23 01:42:17 +000088 "print the maintainer's email address if known, else the author's"),
Greg Ward82715e12000-04-21 02:28:14 +000089 ('url', None,
90 "print the URL for this package"),
Greg Ward82715e12000-04-21 02:28:14 +000091 ('license', None,
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +000092 "print the license of the package"),
93 ('licence', None,
94 "alias for --license"),
Greg Ward82715e12000-04-21 02:28:14 +000095 ('description', None,
96 "print the package description"),
Greg Warde5a584e2000-04-26 02:26:55 +000097 ('long-description', None,
98 "print the long package description"),
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +000099 ('platforms', None,
100 "print the list of platforms"),
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +0000101 ('classifiers', None,
102 "print the list of classifiers"),
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000103 ('keywords', None,
104 "print the list of keywords"),
Fred Drakedb7b0022005-03-20 22:19:47 +0000105 ('provides', None,
106 "print the list of packages/modules provided"),
107 ('requires', None,
108 "print the list of packages/modules required"),
109 ('obsoletes', None,
110 "print the list of packages/modules made obsolete")
Greg Ward82715e12000-04-21 02:28:14 +0000111 ]
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000112 display_option_names = [translate_longopt(x[0]) for x in display_options]
Greg Ward82715e12000-04-21 02:28:14 +0000113
114 # negative options are options that exclude other options
Greg Wardfe6462c2000-04-04 01:40:52 +0000115 negative_opt = {'quiet': 'verbose'}
116
117
118 # -- Creation/initialization methods -------------------------------
Fred Drakeb94b8492001-12-06 20:51:35 +0000119
Greg Wardfe6462c2000-04-04 01:40:52 +0000120 def __init__ (self, attrs=None):
121 """Construct a new Distribution instance: initialize all the
Greg Ward8ff5a3f2000-06-02 00:44:53 +0000122 attributes of a Distribution, and then use 'attrs' (a dictionary
123 mapping attribute names to values) to assign some of those
124 attributes their "real" values. (Any attributes not mentioned in
125 'attrs' will be assigned to some null value: 0, None, an empty list
126 or dictionary, etc.) Most importantly, initialize the
127 'command_obj' attribute to the empty dictionary; this will be
128 filled in with real command objects by 'parse_command_line()'.
129 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000130
131 # Default values for our command-line options
132 self.verbose = 1
133 self.dry_run = 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000134 self.help = 0
Greg Ward82715e12000-04-21 02:28:14 +0000135 for attr in self.display_option_names:
136 setattr(self, attr, 0)
Greg Wardfe6462c2000-04-04 01:40:52 +0000137
Greg Ward82715e12000-04-21 02:28:14 +0000138 # Store the distribution meta-data (name, version, author, and so
139 # forth) in a separate object -- we're getting to have enough
140 # information here (and enough command-line options) that it's
141 # worth it. Also delegate 'get_XXX()' methods to the 'metadata'
142 # object in a sneaky and underhanded (but efficient!) way.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000143 self.metadata = DistributionMetadata()
Neil Schemenauera8aefe52001-09-03 15:47:21 +0000144 for basename in self.metadata._METHOD_BASENAMES:
Greg Ward4982f982000-04-22 02:52:44 +0000145 method_name = "get_" + basename
146 setattr(self, method_name, getattr(self.metadata, method_name))
Greg Wardfe6462c2000-04-04 01:40:52 +0000147
148 # 'cmdclass' maps command names to class objects, so we
149 # can 1) quickly figure out which class to instantiate when
150 # we need to create a new command object, and 2) have a way
Greg Ward82715e12000-04-21 02:28:14 +0000151 # for the setup script to override command classes
Greg Wardfe6462c2000-04-04 01:40:52 +0000152 self.cmdclass = {}
153
Fred Draked04573f2004-08-03 16:37:40 +0000154 # 'command_packages' is a list of packages in which commands
155 # are searched for. The factory for command 'foo' is expected
156 # to be named 'foo' in the module 'foo' in one of the packages
157 # named here. This list is searched from the left; an error
158 # is raised if no named package provides the command being
159 # searched for. (Always access using get_command_packages().)
160 self.command_packages = None
161
Greg Ward9821bf42000-08-29 01:15:18 +0000162 # 'script_name' and 'script_args' are usually set to sys.argv[0]
163 # and sys.argv[1:], but they can be overridden when the caller is
164 # not necessarily a setup script run from the command-line.
165 self.script_name = None
166 self.script_args = None
167
Greg Wardd5d8a992000-05-23 01:42:17 +0000168 # 'command_options' is where we store command options between
169 # parsing them (from config files, the command-line, etc.) and when
170 # they are actually needed -- ie. when the command in question is
171 # instantiated. It is a dictionary of dictionaries of 2-tuples:
172 # command_options = { command_name : { option : (source, value) } }
Gregory P. Smith14263542000-05-12 00:41:33 +0000173 self.command_options = {}
174
Martin v. Löwis98da5622005-03-23 18:54:36 +0000175 # 'dist_files' is the list of (command, pyversion, file) that
176 # have been created by any dist commands run so far. This is
177 # filled regardless of whether the run is dry or not. pyversion
178 # gives sysconfig.get_python_version() if the dist file is
179 # specific to a Python version, 'any' if it is good for all
180 # Python versions on the target platform, and '' for a source
181 # file. pyversion should not be used to specify minimum or
182 # maximum required Python versions; use the metainfo for that
183 # instead.
Martin v. Löwis55f1bb82005-03-21 20:56:35 +0000184 self.dist_files = []
185
Greg Wardfe6462c2000-04-04 01:40:52 +0000186 # These options are really the business of various commands, rather
187 # than of the Distribution itself. We provide aliases for them in
188 # Distribution as a convenience to the developer.
Greg Wardfe6462c2000-04-04 01:40:52 +0000189 self.packages = None
Fred Drake0eb32a62004-06-11 21:50:33 +0000190 self.package_data = {}
Greg Wardfe6462c2000-04-04 01:40:52 +0000191 self.package_dir = None
192 self.py_modules = None
193 self.libraries = None
Greg Ward51def7d2000-05-27 01:36:14 +0000194 self.headers = None
Greg Wardfe6462c2000-04-04 01:40:52 +0000195 self.ext_modules = None
196 self.ext_package = None
197 self.include_dirs = None
198 self.extra_path = None
Gregory P. Smithb2e3bb32000-05-12 00:52:23 +0000199 self.scripts = None
Gregory P. Smith6a901dd2000-05-13 03:09:50 +0000200 self.data_files = None
Tarek Ziadé13f7c3b2009-01-09 00:15:45 +0000201 self.password = ''
Greg Wardfe6462c2000-04-04 01:40:52 +0000202
203 # And now initialize bookkeeping stuff that can't be supplied by
204 # the caller at all. 'command_obj' maps command names to
205 # Command instances -- that's how we enforce that every command
206 # class is a singleton.
207 self.command_obj = {}
208
209 # 'have_run' maps command names to boolean values; it keeps track
210 # of whether we have actually run a particular command, to make it
211 # cheap to "run" a command whenever we think we might need to -- if
212 # it's already been done, no need for expensive filesystem
213 # operations, we just check the 'have_run' dictionary and carry on.
214 # It's only safe to query 'have_run' for a command class that has
215 # been instantiated -- a false value will be inserted when the
216 # command object is created, and replaced with a true value when
Greg Ward612eb9f2000-07-27 02:13:20 +0000217 # the command is successfully run. Thus it's probably best to use
Greg Wardfe6462c2000-04-04 01:40:52 +0000218 # '.get()' rather than a straight lookup.
219 self.have_run = {}
220
221 # Now we'll use the attrs dictionary (ultimately, keyword args from
Greg Ward82715e12000-04-21 02:28:14 +0000222 # the setup script) to possibly override any or all of these
223 # distribution options.
224
Greg Wardfe6462c2000-04-04 01:40:52 +0000225 if attrs:
Greg Wardfe6462c2000-04-04 01:40:52 +0000226 # Pull out the set of command options and work on them
227 # specifically. Note that this order guarantees that aliased
228 # command options will override any supplied redundantly
229 # through the general options dictionary.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000230 options = attrs.get('options')
Tarek Ziadé4450dcf2008-12-29 22:38:38 +0000231 if options is not None:
Greg Wardfe6462c2000-04-04 01:40:52 +0000232 del attrs['options']
233 for (command, cmd_options) in options.items():
Greg Ward0e48cfd2000-05-26 01:00:15 +0000234 opt_dict = self.get_option_dict(command)
235 for (opt, val) in cmd_options.items():
236 opt_dict[opt] = ("setup script", val)
Greg Wardfe6462c2000-04-04 01:40:52 +0000237
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000238 if 'licence' in attrs:
Andrew M. Kuchlinga52b8522003-03-03 20:07:27 +0000239 attrs['license'] = attrs['licence']
240 del attrs['licence']
241 msg = "'licence' distribution option is deprecated; use 'license'"
242 if warnings is not None:
243 warnings.warn(msg)
244 else:
245 sys.stderr.write(msg + "\n")
246
Greg Wardfe6462c2000-04-04 01:40:52 +0000247 # Now work on the rest of the attributes. Any attribute that's
248 # not already defined is invalid!
249 for (key,val) in attrs.items():
Fred Drakedb7b0022005-03-20 22:19:47 +0000250 if hasattr(self.metadata, "set_" + key):
251 getattr(self.metadata, "set_" + key)(val)
252 elif hasattr(self.metadata, key):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000253 setattr(self.metadata, key, val)
254 elif hasattr(self, key):
255 setattr(self, key, val)
Anthony Baxter73cc8472004-10-13 13:22:34 +0000256 else:
Andrew M. Kuchlingff4ad9a2002-10-31 13:22:41 +0000257 msg = "Unknown distribution option: %s" % repr(key)
258 if warnings is not None:
259 warnings.warn(msg)
260 else:
261 sys.stderr.write(msg + "\n")
Greg Wardfe6462c2000-04-04 01:40:52 +0000262
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000263 self.finalize_options()
Fred Drakeb94b8492001-12-06 20:51:35 +0000264
Tarek Ziadé188789d2009-05-16 18:37:32 +0000265 def get_option_dict(self, command):
Greg Ward0e48cfd2000-05-26 01:00:15 +0000266 """Get the option dictionary for a given command. If that
267 command's option dictionary hasn't been created yet, then create it
268 and return the new dictionary; otherwise, return the existing
269 option dictionary.
270 """
Greg Ward0e48cfd2000-05-26 01:00:15 +0000271 dict = self.command_options.get(command)
272 if dict is None:
273 dict = self.command_options[command] = {}
274 return dict
275
Tarek Ziadé188789d2009-05-16 18:37:32 +0000276 def dump_option_dicts(self, header=None, commands=None, indent=""):
Greg Wardc32d9a62000-05-28 23:53:06 +0000277 from pprint import pformat
278
279 if commands is None: # dump all command option dicts
Guido van Rossumd4ee1672007-10-15 01:27:53 +0000280 commands = sorted(self.command_options.keys())
Greg Wardc32d9a62000-05-28 23:53:06 +0000281
282 if header is not None:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000283 print(indent + header)
Greg Wardc32d9a62000-05-28 23:53:06 +0000284 indent = indent + " "
285
286 if not commands:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000287 print(indent + "no commands known yet")
Greg Wardc32d9a62000-05-28 23:53:06 +0000288 return
289
290 for cmd_name in commands:
291 opt_dict = self.command_options.get(cmd_name)
292 if opt_dict is None:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000293 print(indent + "no option dict for '%s' command" % cmd_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000294 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000295 print(indent + "option dict for '%s' command:" % cmd_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000296 out = pformat(opt_dict)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000297 for line in out.split("\n"):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000298 print(indent + " " + line)
Greg Wardc32d9a62000-05-28 23:53:06 +0000299
Greg Wardd5d8a992000-05-23 01:42:17 +0000300 # -- Config file finding/parsing methods ---------------------------
301
Tarek Ziadé188789d2009-05-16 18:37:32 +0000302 def find_config_files(self):
Gregory P. Smith14263542000-05-12 00:41:33 +0000303 """Find as many configuration files as should be processed for this
304 platform, and return a list of filenames in the order in which they
305 should be parsed. The filenames returned are guaranteed to exist
306 (modulo nasty race conditions).
307
Andrew M. Kuchlingd303b612001-12-06 16:32:05 +0000308 There are three possible config files: distutils.cfg in the
309 Distutils installation directory (ie. where the top-level
310 Distutils __inst__.py file lives), a file in the user's home
311 directory named .pydistutils.cfg on Unix and pydistutils.cfg
312 on Windows/Mac, and setup.cfg in the current directory.
Greg Wardd5d8a992000-05-23 01:42:17 +0000313 """
Gregory P. Smith14263542000-05-12 00:41:33 +0000314 files = []
Greg Wardacf3f6a2000-06-07 02:26:19 +0000315 check_environ()
Gregory P. Smith14263542000-05-12 00:41:33 +0000316
Greg Ward11696872000-06-07 02:29:03 +0000317 # Where to look for the system-wide Distutils config file
318 sys_dir = os.path.dirname(sys.modules['distutils'].__file__)
319
320 # Look for the system config file
321 sys_file = os.path.join(sys_dir, "distutils.cfg")
Greg Wardacf3f6a2000-06-07 02:26:19 +0000322 if os.path.isfile(sys_file):
323 files.append(sys_file)
Gregory P. Smith14263542000-05-12 00:41:33 +0000324
Greg Ward11696872000-06-07 02:29:03 +0000325 # What to call the per-user config file
326 if os.name == 'posix':
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000327 user_filename = ".pydistutils.cfg"
328 else:
329 user_filename = "pydistutils.cfg"
Greg Wardfa9ff762000-10-14 04:06:40 +0000330
Greg Ward11696872000-06-07 02:29:03 +0000331 # And look for the user config file
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000332 user_file = os.path.join(os.path.expanduser('~'), user_filename)
333 if os.path.isfile(user_file):
334 files.append(user_file)
Gregory P. Smith14263542000-05-12 00:41:33 +0000335
Gregory P. Smith14263542000-05-12 00:41:33 +0000336 # All platforms support local setup.cfg
337 local_file = "setup.cfg"
338 if os.path.isfile(local_file):
339 files.append(local_file)
340
341 return files
342
Tarek Ziadé188789d2009-05-16 18:37:32 +0000343 def parse_config_files(self, filenames=None):
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000344 from configparser import ConfigParser
Gregory P. Smith14263542000-05-12 00:41:33 +0000345
346 if filenames is None:
347 filenames = self.find_config_files()
348
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000349 if DEBUG: print("Distribution.parse_config_files():")
Greg Ward47460772000-05-23 03:47:35 +0000350
Gregory P. Smith14263542000-05-12 00:41:33 +0000351 parser = ConfigParser()
Greg Wardd5d8a992000-05-23 01:42:17 +0000352 for filename in filenames:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000353 if DEBUG: print(" reading", filename)
Greg Wardd5d8a992000-05-23 01:42:17 +0000354 parser.read(filename)
355 for section in parser.sections():
356 options = parser.options(section)
Greg Ward0e48cfd2000-05-26 01:00:15 +0000357 opt_dict = self.get_option_dict(section)
Gregory P. Smith14263542000-05-12 00:41:33 +0000358
Greg Wardd5d8a992000-05-23 01:42:17 +0000359 for opt in options:
360 if opt != '__name__':
Greg Wardceb9e222000-09-25 01:23:52 +0000361 val = parser.get(section,opt)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000362 opt = opt.replace('-', '_')
Greg Wardceb9e222000-09-25 01:23:52 +0000363 opt_dict[opt] = (filename, val)
Gregory P. Smith14263542000-05-12 00:41:33 +0000364
Greg Ward47460772000-05-23 03:47:35 +0000365 # Make the ConfigParser forget everything (so we retain
Fred Drakef06116d2004-02-17 22:35:19 +0000366 # the original filenames that options come from)
Greg Ward47460772000-05-23 03:47:35 +0000367 parser.__init__()
Gregory P. Smith14263542000-05-12 00:41:33 +0000368
Greg Wardceb9e222000-09-25 01:23:52 +0000369 # If there was a "global" section in the config file, use it
370 # to set Distribution options.
371
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000372 if 'global' in self.command_options:
Greg Wardceb9e222000-09-25 01:23:52 +0000373 for (opt, (src, val)) in self.command_options['global'].items():
374 alias = self.negative_opt.get(opt)
375 try:
376 if alias:
377 setattr(self, alias, not strtobool(val))
378 elif opt in ('verbose', 'dry_run'): # ugh!
379 setattr(self, opt, strtobool(val))
Fred Draked04573f2004-08-03 16:37:40 +0000380 else:
381 setattr(self, opt, val)
Guido van Rossumb940e112007-01-10 16:19:56 +0000382 except ValueError as msg:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000383 raise DistutilsOptionError(msg)
Greg Wardceb9e222000-09-25 01:23:52 +0000384
Greg Wardd5d8a992000-05-23 01:42:17 +0000385 # -- Command-line parsing methods ----------------------------------
386
Tarek Ziadé188789d2009-05-16 18:37:32 +0000387 def parse_command_line(self):
Greg Ward9821bf42000-08-29 01:15:18 +0000388 """Parse the setup script's command line, taken from the
389 'script_args' instance attribute (which defaults to 'sys.argv[1:]'
390 -- see 'setup()' in core.py). This list is first processed for
391 "global options" -- options that set attributes of the Distribution
392 instance. Then, it is alternately scanned for Distutils commands
393 and options for that command. Each new command terminates the
394 options for the previous command. The allowed options for a
395 command are determined by the 'user_options' attribute of the
396 command class -- thus, we have to be able to load command classes
397 in order to parse the command line. Any error in that 'options'
398 attribute raises DistutilsGetoptError; any error on the
399 command-line raises DistutilsArgError. If no Distutils commands
400 were found on the command line, raises DistutilsArgError. Return
Greg Wardceb9e222000-09-25 01:23:52 +0000401 true if command-line was successfully parsed and we should carry
Greg Ward9821bf42000-08-29 01:15:18 +0000402 on with executing commands; false if no errors but we shouldn't
403 execute commands (currently, this only happens if user asks for
404 help).
Greg Wardd5d8a992000-05-23 01:42:17 +0000405 """
Andrew M. Kuchling3f819ec2001-01-15 16:09:35 +0000406 #
Fred Drake981a1782001-08-10 18:59:30 +0000407 # We now have enough information to show the Macintosh dialog
408 # that allows the user to interactively specify the "command line".
Andrew M. Kuchling3f819ec2001-01-15 16:09:35 +0000409 #
Fred Draked04573f2004-08-03 16:37:40 +0000410 toplevel_options = self._get_toplevel_options()
Fred Drakeb94b8492001-12-06 20:51:35 +0000411
Greg Wardfe6462c2000-04-04 01:40:52 +0000412 # We have to parse the command line a bit at a time -- global
413 # options, then the first command, then its options, and so on --
414 # because each command will be handled by a different class, and
Greg Wardd5d8a992000-05-23 01:42:17 +0000415 # the options that are valid for a particular class aren't known
416 # until we have loaded the command class, which doesn't happen
417 # until we know what the command is.
Greg Wardfe6462c2000-04-04 01:40:52 +0000418
419 self.commands = []
Fred Draked04573f2004-08-03 16:37:40 +0000420 parser = FancyGetopt(toplevel_options + self.display_options)
Greg Wardfd7b91e2000-09-26 01:52:25 +0000421 parser.set_negative_aliases(self.negative_opt)
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +0000422 parser.set_aliases({'licence': 'license'})
Greg Wardfd7b91e2000-09-26 01:52:25 +0000423 args = parser.getopt(args=self.script_args, object=self)
Greg Ward82715e12000-04-21 02:28:14 +0000424 option_order = parser.get_option_order()
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000425 log.set_verbosity(self.verbose)
Greg Wardfe6462c2000-04-04 01:40:52 +0000426
Greg Ward82715e12000-04-21 02:28:14 +0000427 # for display options we return immediately
428 if self.handle_display_options(option_order):
Greg Wardfe6462c2000-04-04 01:40:52 +0000429 return
Greg Wardfe6462c2000-04-04 01:40:52 +0000430 while args:
Greg Wardd5d8a992000-05-23 01:42:17 +0000431 args = self._parse_command_opts(parser, args)
432 if args is None: # user asked for help (and got it)
Greg Wardfe6462c2000-04-04 01:40:52 +0000433 return
Greg Wardfe6462c2000-04-04 01:40:52 +0000434
Greg Wardd5d8a992000-05-23 01:42:17 +0000435 # Handle the cases of --help as a "global" option, ie.
436 # "setup.py --help" and "setup.py --help command ...". For the
437 # former, we show global options (--verbose, --dry-run, etc.)
438 # and display-only options (--name, --version, etc.); for the
439 # latter, we omit the display-only options and show help for
440 # each command listed on the command line.
Greg Wardfe6462c2000-04-04 01:40:52 +0000441 if self.help:
Greg Wardd5d8a992000-05-23 01:42:17 +0000442 self._show_help(parser,
443 display_options=len(self.commands) == 0,
444 commands=self.commands)
Greg Wardfe6462c2000-04-04 01:40:52 +0000445 return
446
447 # Oops, no commands found -- an end-user error
448 if not self.commands:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000449 raise DistutilsArgError("no commands supplied")
Greg Wardfe6462c2000-04-04 01:40:52 +0000450
451 # All is well: return true
Collin Winter5b7e9d72007-08-30 03:52:21 +0000452 return True
Greg Wardfe6462c2000-04-04 01:40:52 +0000453
Tarek Ziadé188789d2009-05-16 18:37:32 +0000454 def _get_toplevel_options(self):
Fred Draked04573f2004-08-03 16:37:40 +0000455 """Return the non-display options recognized at the top level.
456
457 This includes options that are recognized *only* at the top
458 level as well as options recognized for commands.
459 """
460 return self.global_options + [
461 ("command-packages=", None,
462 "list of packages that provide distutils commands"),
463 ]
464
Tarek Ziadé188789d2009-05-16 18:37:32 +0000465 def _parse_command_opts(self, parser, args):
Greg Wardd5d8a992000-05-23 01:42:17 +0000466 """Parse the command-line options for a single command.
467 'parser' must be a FancyGetopt instance; 'args' must be the list
468 of arguments, starting with the current command (whose options
469 we are about to parse). Returns a new version of 'args' with
470 the next command at the front of the list; will be the empty
471 list if there are no more commands on the command line. Returns
472 None if the user asked for help on this command.
473 """
474 # late import because of mutual dependence between these modules
475 from distutils.cmd import Command
476
477 # Pull the current command from the head of the command line
478 command = args[0]
Greg Wardfd7b91e2000-09-26 01:52:25 +0000479 if not command_re.match(command):
Collin Winter5b7e9d72007-08-30 03:52:21 +0000480 raise SystemExit("invalid command name '%s'" % command)
Greg Wardfd7b91e2000-09-26 01:52:25 +0000481 self.commands.append(command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000482
483 # Dig up the command class that implements this command, so we
484 # 1) know that it's a valid command, and 2) know which options
485 # it takes.
486 try:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000487 cmd_class = self.get_command_class(command)
Guido van Rossumb940e112007-01-10 16:19:56 +0000488 except DistutilsModuleError as msg:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000489 raise DistutilsArgError(msg)
Greg Wardd5d8a992000-05-23 01:42:17 +0000490
491 # Require that the command class be derived from Command -- want
492 # to be sure that the basic "command" interface is implemented.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000493 if not issubclass(cmd_class, Command):
Collin Winter5b7e9d72007-08-30 03:52:21 +0000494 raise DistutilsClassError(
495 "command class %s must subclass Command" % cmd_class)
Greg Wardd5d8a992000-05-23 01:42:17 +0000496
497 # Also make sure that the command object provides a list of its
498 # known options.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000499 if not (hasattr(cmd_class, 'user_options') and
Guido van Rossum13257902007-06-07 23:15:56 +0000500 isinstance(cmd_class.user_options, list)):
Collin Winter5b7e9d72007-08-30 03:52:21 +0000501 raise DistutilsClassError(("command class %s must provide " +
Greg Wardd5d8a992000-05-23 01:42:17 +0000502 "'user_options' attribute (a list of tuples)") % \
Collin Winter5b7e9d72007-08-30 03:52:21 +0000503 cmd_class)
Greg Wardd5d8a992000-05-23 01:42:17 +0000504
505 # If the command class has a list of negative alias options,
506 # merge it in with the global negative aliases.
507 negative_opt = self.negative_opt
Greg Wardfd7b91e2000-09-26 01:52:25 +0000508 if hasattr(cmd_class, 'negative_opt'):
Antoine Pitrou56a00de2009-05-15 17:34:21 +0000509 negative_opt = negative_opt.copy()
Greg Wardfd7b91e2000-09-26 01:52:25 +0000510 negative_opt.update(cmd_class.negative_opt)
Greg Wardd5d8a992000-05-23 01:42:17 +0000511
Greg Wardfa9ff762000-10-14 04:06:40 +0000512 # Check for help_options in command class. They have a different
513 # format (tuple of four) so we need to preprocess them here.
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000514 if (hasattr(cmd_class, 'help_options') and
Guido van Rossum13257902007-06-07 23:15:56 +0000515 isinstance(cmd_class.help_options, list)):
Greg Ward2ff78872000-06-24 00:23:20 +0000516 help_options = fix_help_options(cmd_class.help_options)
517 else:
Greg Ward55fced32000-06-24 01:22:41 +0000518 help_options = []
Greg Ward2ff78872000-06-24 00:23:20 +0000519
Greg Ward9d17a7a2000-06-07 03:00:06 +0000520
Greg Wardd5d8a992000-05-23 01:42:17 +0000521 # All commands support the global options too, just by adding
522 # in 'global_options'.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000523 parser.set_option_table(self.global_options +
524 cmd_class.user_options +
525 help_options)
526 parser.set_negative_aliases(negative_opt)
527 (args, opts) = parser.getopt(args[1:])
Greg Ward47460772000-05-23 03:47:35 +0000528 if hasattr(opts, 'help') and opts.help:
Greg Wardd5d8a992000-05-23 01:42:17 +0000529 self._show_help(parser, display_options=0, commands=[cmd_class])
530 return
531
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000532 if (hasattr(cmd_class, 'help_options') and
Guido van Rossum13257902007-06-07 23:15:56 +0000533 isinstance(cmd_class.help_options, list)):
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000534 help_option_found=0
535 for (help_option, short, desc, func) in cmd_class.help_options:
536 if hasattr(opts, parser.get_attr_name(help_option)):
537 help_option_found=1
Greg Wardfa9ff762000-10-14 04:06:40 +0000538 #print "showing help for option %s of command %s" % \
Greg Ward2ff78872000-06-24 00:23:20 +0000539 # (help_option[0],cmd_class)
Greg Ward55fced32000-06-24 01:22:41 +0000540
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000541 if hasattr(func, '__call__'):
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000542 func()
Greg Ward55fced32000-06-24 01:22:41 +0000543 else:
Fred Drake981a1782001-08-10 18:59:30 +0000544 raise DistutilsClassError(
Walter Dörwald70a6b492004-02-12 17:35:32 +0000545 "invalid help function %r for help option '%s': "
Fred Drake981a1782001-08-10 18:59:30 +0000546 "must be a callable object (function, etc.)"
Walter Dörwald70a6b492004-02-12 17:35:32 +0000547 % (func, help_option))
Greg Ward55fced32000-06-24 01:22:41 +0000548
Fred Drakeb94b8492001-12-06 20:51:35 +0000549 if help_option_found:
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000550 return
Greg Ward9d17a7a2000-06-07 03:00:06 +0000551
Greg Wardd5d8a992000-05-23 01:42:17 +0000552 # Put the options from the command-line into their official
553 # holding pen, the 'command_options' dictionary.
Greg Ward0e48cfd2000-05-26 01:00:15 +0000554 opt_dict = self.get_option_dict(command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000555 for (name, value) in vars(opts).items():
Greg Ward0e48cfd2000-05-26 01:00:15 +0000556 opt_dict[name] = ("command line", value)
Greg Wardd5d8a992000-05-23 01:42:17 +0000557
558 return args
559
Tarek Ziadé188789d2009-05-16 18:37:32 +0000560 def finalize_options(self):
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000561 """Set final values for all the options on the Distribution
562 instance, analogous to the .finalize_options() method of Command
563 objects.
564 """
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000565 keywords = self.metadata.keywords
566 if keywords is not None:
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000567 if isinstance(keywords, str):
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000568 keywordlist = keywords.split(',')
569 self.metadata.keywords = [x.strip() for x in keywordlist]
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000570
571 platforms = self.metadata.platforms
572 if platforms is not None:
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000573 if isinstance(platforms, str):
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000574 platformlist = platforms.split(',')
575 self.metadata.platforms = [x.strip() for x in platformlist]
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000576
Tarek Ziadé188789d2009-05-16 18:37:32 +0000577 def _show_help(self, parser, global_options=1, display_options=1,
578 commands=[]):
Greg Wardd5d8a992000-05-23 01:42:17 +0000579 """Show help for the setup script command-line in the form of
580 several lists of command-line options. 'parser' should be a
581 FancyGetopt instance; do not expect it to be returned in the
582 same state, as its option table will be reset to make it
583 generate the correct help text.
584
585 If 'global_options' is true, lists the global options:
586 --verbose, --dry-run, etc. If 'display_options' is true, lists
587 the "display-only" options: --name, --version, etc. Finally,
588 lists per-command help for every command name or command class
589 in 'commands'.
590 """
591 # late import because of mutual dependence between these modules
Greg Ward9821bf42000-08-29 01:15:18 +0000592 from distutils.core import gen_usage
Greg Wardd5d8a992000-05-23 01:42:17 +0000593 from distutils.cmd import Command
594
595 if global_options:
Fred Draked04573f2004-08-03 16:37:40 +0000596 if display_options:
597 options = self._get_toplevel_options()
598 else:
599 options = self.global_options
600 parser.set_option_table(options)
Martin v. Löwis8ed338a2005-03-03 08:12:27 +0000601 parser.print_help(self.common_usage + "\nGlobal options:")
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000602 print()
Greg Wardd5d8a992000-05-23 01:42:17 +0000603
604 if display_options:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000605 parser.set_option_table(self.display_options)
606 parser.print_help(
Greg Wardd5d8a992000-05-23 01:42:17 +0000607 "Information display options (just display " +
608 "information, ignore any commands)")
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000609 print()
Greg Wardd5d8a992000-05-23 01:42:17 +0000610
611 for command in self.commands:
Guido van Rossum13257902007-06-07 23:15:56 +0000612 if isinstance(command, type) and issubclass(command, Command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000613 klass = command
614 else:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000615 klass = self.get_command_class(command)
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000616 if (hasattr(klass, 'help_options') and
Guido van Rossum13257902007-06-07 23:15:56 +0000617 isinstance(klass.help_options, list)):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000618 parser.set_option_table(klass.user_options +
619 fix_help_options(klass.help_options))
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000620 else:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000621 parser.set_option_table(klass.user_options)
622 parser.print_help("Options for '%s' command:" % klass.__name__)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000623 print()
Greg Wardd5d8a992000-05-23 01:42:17 +0000624
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000625 print(gen_usage(self.script_name))
Greg Wardd5d8a992000-05-23 01:42:17 +0000626 return
627
Tarek Ziadé188789d2009-05-16 18:37:32 +0000628 def handle_display_options(self, option_order):
Greg Ward82715e12000-04-21 02:28:14 +0000629 """If there were any non-global "display-only" options
Greg Wardd5d8a992000-05-23 01:42:17 +0000630 (--help-commands or the metadata display options) on the command
631 line, display the requested info and return true; else return
632 false.
633 """
Greg Ward9821bf42000-08-29 01:15:18 +0000634 from distutils.core import gen_usage
Greg Ward82715e12000-04-21 02:28:14 +0000635
636 # User just wants a list of commands -- we'll print it out and stop
637 # processing now (ie. if they ran "setup --help-commands foo bar",
638 # we ignore "foo bar").
639 if self.help_commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000640 self.print_commands()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000641 print()
642 print(gen_usage(self.script_name))
Greg Ward82715e12000-04-21 02:28:14 +0000643 return 1
644
645 # If user supplied any of the "display metadata" options, then
646 # display that metadata in the order in which the user supplied the
647 # metadata options.
648 any_display_options = 0
649 is_display_option = {}
650 for option in self.display_options:
651 is_display_option[option[0]] = 1
652
653 for (opt, val) in option_order:
654 if val and is_display_option.get(opt):
Greg Ward2f2b6c62000-09-25 01:58:07 +0000655 opt = translate_longopt(opt)
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000656 value = getattr(self.metadata, "get_"+opt)()
657 if opt in ['keywords', 'platforms']:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000658 print(','.join(value))
Fred Drakedb7b0022005-03-20 22:19:47 +0000659 elif opt in ('classifiers', 'provides', 'requires',
660 'obsoletes'):
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000661 print('\n'.join(value))
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000662 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000663 print(value)
Greg Ward82715e12000-04-21 02:28:14 +0000664 any_display_options = 1
665
666 return any_display_options
667
Tarek Ziadé188789d2009-05-16 18:37:32 +0000668 def print_command_list(self, commands, header, max_length):
Greg Wardfe6462c2000-04-04 01:40:52 +0000669 """Print a subset of the list of all commands -- used by
Greg Wardd5d8a992000-05-23 01:42:17 +0000670 'print_commands()'.
671 """
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000672 print(header + ":")
Greg Wardfe6462c2000-04-04 01:40:52 +0000673
674 for cmd in commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000675 klass = self.cmdclass.get(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000676 if not klass:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000677 klass = self.get_command_class(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000678 try:
679 description = klass.description
680 except AttributeError:
681 description = "(no description available)"
682
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000683 print(" %-*s %s" % (max_length, cmd, description))
Greg Wardfe6462c2000-04-04 01:40:52 +0000684
Tarek Ziadé188789d2009-05-16 18:37:32 +0000685 def print_commands(self):
Greg Wardd5d8a992000-05-23 01:42:17 +0000686 """Print out a help message listing all available commands with a
687 description of each. The list is divided into "standard commands"
688 (listed in distutils.command.__all__) and "extra commands"
689 (mentioned in self.cmdclass, but not a standard command). The
690 descriptions come from the command class attribute
691 'description'.
692 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000693 import distutils.command
694 std_commands = distutils.command.__all__
695 is_std = {}
696 for cmd in std_commands:
697 is_std[cmd] = 1
698
699 extra_commands = []
700 for cmd in self.cmdclass.keys():
701 if not is_std.get(cmd):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000702 extra_commands.append(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000703
704 max_length = 0
705 for cmd in (std_commands + extra_commands):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000706 if len(cmd) > max_length:
707 max_length = len(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000708
Greg Wardfd7b91e2000-09-26 01:52:25 +0000709 self.print_command_list(std_commands,
710 "Standard commands",
711 max_length)
Greg Wardfe6462c2000-04-04 01:40:52 +0000712 if extra_commands:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000713 print()
Greg Wardfd7b91e2000-09-26 01:52:25 +0000714 self.print_command_list(extra_commands,
715 "Extra commands",
716 max_length)
Greg Wardfe6462c2000-04-04 01:40:52 +0000717
Tarek Ziadé188789d2009-05-16 18:37:32 +0000718 def get_command_list(self):
Greg Wardf6fc8752000-11-11 02:47:11 +0000719 """Get a list of (command, description) tuples.
720 The list is divided into "standard commands" (listed in
721 distutils.command.__all__) and "extra commands" (mentioned in
722 self.cmdclass, but not a standard command). The descriptions come
723 from the command class attribute 'description'.
724 """
725 # Currently this is only used on Mac OS, for the Mac-only GUI
726 # Distutils interface (by Jack Jansen)
Greg Wardf6fc8752000-11-11 02:47:11 +0000727 import distutils.command
728 std_commands = distutils.command.__all__
729 is_std = {}
730 for cmd in std_commands:
731 is_std[cmd] = 1
732
733 extra_commands = []
734 for cmd in self.cmdclass.keys():
735 if not is_std.get(cmd):
736 extra_commands.append(cmd)
737
738 rv = []
739 for cmd in (std_commands + extra_commands):
740 klass = self.cmdclass.get(cmd)
741 if not klass:
742 klass = self.get_command_class(cmd)
743 try:
744 description = klass.description
745 except AttributeError:
746 description = "(no description available)"
747 rv.append((cmd, description))
748 return rv
Greg Wardfe6462c2000-04-04 01:40:52 +0000749
750 # -- Command class/object methods ----------------------------------
751
Tarek Ziadé188789d2009-05-16 18:37:32 +0000752 def get_command_packages(self):
Fred Draked04573f2004-08-03 16:37:40 +0000753 """Return a list of packages from which commands are loaded."""
754 pkgs = self.command_packages
755 if not isinstance(pkgs, type([])):
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000756 pkgs = (pkgs or "").split(",")
Fred Draked04573f2004-08-03 16:37:40 +0000757 for i in range(len(pkgs)):
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000758 pkgs[i] = pkgs[i].strip()
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000759 pkgs = [p for p in pkgs if p]
Fred Draked04573f2004-08-03 16:37:40 +0000760 if "distutils.command" not in pkgs:
761 pkgs.insert(0, "distutils.command")
762 self.command_packages = pkgs
763 return pkgs
764
Tarek Ziadé188789d2009-05-16 18:37:32 +0000765 def get_command_class(self, command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000766 """Return the class that implements the Distutils command named by
767 'command'. First we check the 'cmdclass' dictionary; if the
768 command is mentioned there, we fetch the class object from the
769 dictionary and return it. Otherwise we load the command module
770 ("distutils.command." + command) and fetch the command class from
771 the module. The loaded class is also stored in 'cmdclass'
772 to speed future calls to 'get_command_class()'.
Greg Wardfe6462c2000-04-04 01:40:52 +0000773
Gregory P. Smith14263542000-05-12 00:41:33 +0000774 Raises DistutilsModuleError if the expected module could not be
Greg Wardd5d8a992000-05-23 01:42:17 +0000775 found, or if that module does not define the expected class.
776 """
777 klass = self.cmdclass.get(command)
778 if klass:
779 return klass
Greg Wardfe6462c2000-04-04 01:40:52 +0000780
Fred Draked04573f2004-08-03 16:37:40 +0000781 for pkgname in self.get_command_packages():
782 module_name = "%s.%s" % (pkgname, command)
783 klass_name = command
Greg Wardfe6462c2000-04-04 01:40:52 +0000784
Fred Draked04573f2004-08-03 16:37:40 +0000785 try:
786 __import__ (module_name)
787 module = sys.modules[module_name]
788 except ImportError:
789 continue
Greg Wardfe6462c2000-04-04 01:40:52 +0000790
Fred Draked04573f2004-08-03 16:37:40 +0000791 try:
792 klass = getattr(module, klass_name)
793 except AttributeError:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000794 raise DistutilsModuleError(
795 "invalid command '%s' (no class '%s' in module '%s')"
796 % (command, klass_name, module_name))
Greg Wardfe6462c2000-04-04 01:40:52 +0000797
Fred Draked04573f2004-08-03 16:37:40 +0000798 self.cmdclass[command] = klass
799 return klass
800
801 raise DistutilsModuleError("invalid command '%s'" % command)
802
Tarek Ziadé188789d2009-05-16 18:37:32 +0000803 def get_command_obj(self, command, create=1):
Greg Wardd5d8a992000-05-23 01:42:17 +0000804 """Return the command object for 'command'. Normally this object
Greg Ward612eb9f2000-07-27 02:13:20 +0000805 is cached on a previous call to 'get_command_obj()'; if no command
Greg Wardd5d8a992000-05-23 01:42:17 +0000806 object for 'command' is in the cache, then we either create and
807 return it (if 'create' is true) or return None.
808 """
809 cmd_obj = self.command_obj.get(command)
Greg Wardfe6462c2000-04-04 01:40:52 +0000810 if not cmd_obj and create:
Greg Ward2bd3f422000-06-02 01:59:33 +0000811 if DEBUG:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000812 print("Distribution.get_command_obj(): " \
813 "creating '%s' command object" % command)
Greg Ward47460772000-05-23 03:47:35 +0000814
Greg Wardd5d8a992000-05-23 01:42:17 +0000815 klass = self.get_command_class(command)
Greg Ward47460772000-05-23 03:47:35 +0000816 cmd_obj = self.command_obj[command] = klass(self)
817 self.have_run[command] = 0
818
819 # Set any options that were supplied in config files
820 # or on the command line. (NB. support for error
821 # reporting is lame here: any errors aren't reported
822 # until 'finalize_options()' is called, which means
823 # we won't report the source of the error.)
824 options = self.command_options.get(command)
825 if options:
Greg Wardc32d9a62000-05-28 23:53:06 +0000826 self._set_command_options(cmd_obj, options)
Greg Wardfe6462c2000-04-04 01:40:52 +0000827
828 return cmd_obj
829
Tarek Ziadé188789d2009-05-16 18:37:32 +0000830 def _set_command_options(self, command_obj, option_dict=None):
Greg Wardc32d9a62000-05-28 23:53:06 +0000831 """Set the options for 'command_obj' from 'option_dict'. Basically
832 this means copying elements of a dictionary ('option_dict') to
833 attributes of an instance ('command').
834
Greg Wardceb9e222000-09-25 01:23:52 +0000835 'command_obj' must be a Command instance. If 'option_dict' is not
Greg Wardc32d9a62000-05-28 23:53:06 +0000836 supplied, uses the standard option dictionary for this command
837 (from 'self.command_options').
838 """
Greg Wardc32d9a62000-05-28 23:53:06 +0000839 command_name = command_obj.get_command_name()
840 if option_dict is None:
841 option_dict = self.get_option_dict(command_name)
842
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000843 if DEBUG: print(" setting options for '%s' command:" % command_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000844 for (option, (source, value)) in option_dict.items():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000845 if DEBUG: print(" %s = %s (from %s)" % (option, value, source))
Greg Wardceb9e222000-09-25 01:23:52 +0000846 try:
Amaury Forgeot d'Arc61cb0872008-07-26 20:09:45 +0000847 bool_opts = [translate_longopt(o)
848 for o in command_obj.boolean_options]
Greg Wardceb9e222000-09-25 01:23:52 +0000849 except AttributeError:
850 bool_opts = []
851 try:
852 neg_opt = command_obj.negative_opt
853 except AttributeError:
854 neg_opt = {}
855
856 try:
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000857 is_string = isinstance(value, str)
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000858 if option in neg_opt and is_string:
Greg Wardceb9e222000-09-25 01:23:52 +0000859 setattr(command_obj, neg_opt[option], not strtobool(value))
Greg Ward2c08cf02000-09-27 00:15:37 +0000860 elif option in bool_opts and is_string:
Greg Wardceb9e222000-09-25 01:23:52 +0000861 setattr(command_obj, option, strtobool(value))
862 elif hasattr(command_obj, option):
863 setattr(command_obj, option, value)
864 else:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000865 raise DistutilsOptionError(
866 "error in %s: command '%s' has no such option '%s'"
867 % (source, command_name, option))
Guido van Rossumb940e112007-01-10 16:19:56 +0000868 except ValueError as msg:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000869 raise DistutilsOptionError(msg)
Greg Wardc32d9a62000-05-28 23:53:06 +0000870
Tarek Ziadé188789d2009-05-16 18:37:32 +0000871 def reinitialize_command(self, command, reinit_subcommands=0):
Greg Wardc32d9a62000-05-28 23:53:06 +0000872 """Reinitializes a command to the state it was in when first
873 returned by 'get_command_obj()': ie., initialized but not yet
Greg Ward7d9c7052000-06-28 01:25:27 +0000874 finalized. This provides the opportunity to sneak option
Greg Wardc32d9a62000-05-28 23:53:06 +0000875 values in programmatically, overriding or supplementing
876 user-supplied values from the config files and command line.
877 You'll have to re-finalize the command object (by calling
878 'finalize_options()' or 'ensure_finalized()') before using it for
Fred Drakeb94b8492001-12-06 20:51:35 +0000879 real.
Greg Wardc32d9a62000-05-28 23:53:06 +0000880
Greg Wardf449ea52000-09-16 15:23:28 +0000881 'command' should be a command name (string) or command object. If
882 'reinit_subcommands' is true, also reinitializes the command's
883 sub-commands, as declared by the 'sub_commands' class attribute (if
884 it has one). See the "install" command for an example. Only
885 reinitializes the sub-commands that actually matter, ie. those
886 whose test predicates return true.
887
Greg Wardc32d9a62000-05-28 23:53:06 +0000888 Returns the reinitialized command object.
889 """
890 from distutils.cmd import Command
891 if not isinstance(command, Command):
892 command_name = command
893 command = self.get_command_obj(command_name)
894 else:
895 command_name = command.get_command_name()
896
897 if not command.finalized:
Greg Ward282c7a02000-06-01 01:09:47 +0000898 return command
Greg Wardc32d9a62000-05-28 23:53:06 +0000899 command.initialize_options()
900 command.finalized = 0
Greg Ward43955c92000-06-06 02:52:36 +0000901 self.have_run[command_name] = 0
Greg Wardc32d9a62000-05-28 23:53:06 +0000902 self._set_command_options(command)
Greg Wardf449ea52000-09-16 15:23:28 +0000903
Greg Wardf449ea52000-09-16 15:23:28 +0000904 if reinit_subcommands:
Greg Wardf449ea52000-09-16 15:23:28 +0000905 for sub in command.get_sub_commands():
Fred Drakeb94b8492001-12-06 20:51:35 +0000906 self.reinitialize_command(sub, reinit_subcommands)
Greg Wardf449ea52000-09-16 15:23:28 +0000907
Greg Wardc32d9a62000-05-28 23:53:06 +0000908 return command
909
Greg Wardfe6462c2000-04-04 01:40:52 +0000910 # -- Methods that operate on the Distribution ----------------------
911
Tarek Ziadé188789d2009-05-16 18:37:32 +0000912 def announce(self, msg, level=1):
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000913 log.debug(msg)
Greg Wardfe6462c2000-04-04 01:40:52 +0000914
Tarek Ziadé188789d2009-05-16 18:37:32 +0000915 def run_commands(self):
Greg Ward82715e12000-04-21 02:28:14 +0000916 """Run each command that was seen on the setup script command line.
Greg Wardd5d8a992000-05-23 01:42:17 +0000917 Uses the list of commands found and cache of command objects
Greg Wardfd7b91e2000-09-26 01:52:25 +0000918 created by 'get_command_obj()'.
919 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000920 for cmd in self.commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000921 self.run_command(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000922
Greg Wardfe6462c2000-04-04 01:40:52 +0000923 # -- Methods that operate on its Commands --------------------------
924
Tarek Ziadé188789d2009-05-16 18:37:32 +0000925 def run_command(self, command):
Greg Wardfe6462c2000-04-04 01:40:52 +0000926 """Do whatever it takes to run a command (including nothing at all,
Greg Wardd5d8a992000-05-23 01:42:17 +0000927 if the command has already been run). Specifically: if we have
928 already created and run the command named by 'command', return
929 silently without doing anything. If the command named by 'command'
930 doesn't even have a command object yet, create one. Then invoke
931 'run()' on that command object (or an existing one).
932 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000933 # Already been here, done that? then return silently.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000934 if self.have_run.get(command):
Greg Wardfe6462c2000-04-04 01:40:52 +0000935 return
936
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000937 log.info("running %s", command)
Greg Wardfd7b91e2000-09-26 01:52:25 +0000938 cmd_obj = self.get_command_obj(command)
939 cmd_obj.ensure_finalized()
940 cmd_obj.run()
Greg Wardfe6462c2000-04-04 01:40:52 +0000941 self.have_run[command] = 1
942
943
Greg Wardfe6462c2000-04-04 01:40:52 +0000944 # -- Distribution query methods ------------------------------------
945
Tarek Ziadé188789d2009-05-16 18:37:32 +0000946 def has_pure_modules(self):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000947 return len(self.packages or self.py_modules or []) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000948
Tarek Ziadé188789d2009-05-16 18:37:32 +0000949 def has_ext_modules(self):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000950 return self.ext_modules and len(self.ext_modules) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000951
Tarek Ziadé188789d2009-05-16 18:37:32 +0000952 def has_c_libraries(self):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000953 return self.libraries and len(self.libraries) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000954
Tarek Ziadé188789d2009-05-16 18:37:32 +0000955 def has_modules(self):
Greg Wardfe6462c2000-04-04 01:40:52 +0000956 return self.has_pure_modules() or self.has_ext_modules()
957
Tarek Ziadé188789d2009-05-16 18:37:32 +0000958 def has_headers(self):
Greg Ward51def7d2000-05-27 01:36:14 +0000959 return self.headers and len(self.headers) > 0
960
Tarek Ziadé188789d2009-05-16 18:37:32 +0000961 def has_scripts(self):
Greg Ward44a61bb2000-05-20 15:06:48 +0000962 return self.scripts and len(self.scripts) > 0
963
Tarek Ziadé188789d2009-05-16 18:37:32 +0000964 def has_data_files(self):
Greg Ward44a61bb2000-05-20 15:06:48 +0000965 return self.data_files and len(self.data_files) > 0
966
Tarek Ziadé188789d2009-05-16 18:37:32 +0000967 def is_pure(self):
Greg Wardfe6462c2000-04-04 01:40:52 +0000968 return (self.has_pure_modules() and
969 not self.has_ext_modules() and
970 not self.has_c_libraries())
971
Greg Ward82715e12000-04-21 02:28:14 +0000972 # -- Metadata query methods ----------------------------------------
973
974 # If you're looking for 'get_name()', 'get_version()', and so forth,
975 # they are defined in a sneaky way: the constructor binds self.get_XXX
976 # to self.metadata.get_XXX. The actual code is in the
977 # DistributionMetadata class, below.
978
Greg Ward82715e12000-04-21 02:28:14 +0000979class DistributionMetadata:
980 """Dummy class to hold the distribution meta-data: name, version,
Greg Wardfd7b91e2000-09-26 01:52:25 +0000981 author, and so forth.
982 """
Greg Ward82715e12000-04-21 02:28:14 +0000983
Neil Schemenauera8aefe52001-09-03 15:47:21 +0000984 _METHOD_BASENAMES = ("name", "version", "author", "author_email",
985 "maintainer", "maintainer_email", "url",
986 "license", "description", "long_description",
987 "keywords", "platforms", "fullname", "contact",
Andrew M. Kuchlinga52b8522003-03-03 20:07:27 +0000988 "contact_email", "license", "classifiers",
Fred Drakedb7b0022005-03-20 22:19:47 +0000989 "download_url",
990 # PEP 314
991 "provides", "requires", "obsoletes",
992 )
Neil Schemenauera8aefe52001-09-03 15:47:21 +0000993
Greg Ward82715e12000-04-21 02:28:14 +0000994 def __init__ (self):
995 self.name = None
996 self.version = None
997 self.author = None
998 self.author_email = None
999 self.maintainer = None
1000 self.maintainer_email = None
1001 self.url = None
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +00001002 self.license = None
Greg Ward82715e12000-04-21 02:28:14 +00001003 self.description = None
Greg Warde5a584e2000-04-26 02:26:55 +00001004 self.long_description = None
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001005 self.keywords = None
1006 self.platforms = None
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +00001007 self.classifiers = None
Andrew M. Kuchling188d85f2003-02-19 14:16:01 +00001008 self.download_url = None
Fred Drakedb7b0022005-03-20 22:19:47 +00001009 # PEP 314
1010 self.provides = None
1011 self.requires = None
1012 self.obsoletes = None
Fred Drakeb94b8492001-12-06 20:51:35 +00001013
Tarek Ziadé188789d2009-05-16 18:37:32 +00001014 def write_pkg_info(self, base_dir):
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001015 """Write the PKG-INFO file into the release tree.
1016 """
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001017 pkg_info = open( os.path.join(base_dir, 'PKG-INFO'), 'w')
Fred Drakedb7b0022005-03-20 22:19:47 +00001018 self.write_pkg_file(pkg_info)
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001019 pkg_info.close()
Fred Drakeb94b8492001-12-06 20:51:35 +00001020
Tarek Ziadé188789d2009-05-16 18:37:32 +00001021 def write_pkg_file(self, file):
Fred Drakedb7b0022005-03-20 22:19:47 +00001022 """Write the PKG-INFO format data to a file object.
1023 """
1024 version = '1.0'
1025 if self.provides or self.requires or self.obsoletes:
1026 version = '1.1'
1027
1028 file.write('Metadata-Version: %s\n' % version)
1029 file.write('Name: %s\n' % self.get_name() )
1030 file.write('Version: %s\n' % self.get_version() )
1031 file.write('Summary: %s\n' % self.get_description() )
1032 file.write('Home-page: %s\n' % self.get_url() )
1033 file.write('Author: %s\n' % self.get_contact() )
1034 file.write('Author-email: %s\n' % self.get_contact_email() )
1035 file.write('License: %s\n' % self.get_license() )
1036 if self.download_url:
1037 file.write('Download-URL: %s\n' % self.download_url)
1038
1039 long_desc = rfc822_escape( self.get_long_description() )
1040 file.write('Description: %s\n' % long_desc)
1041
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001042 keywords = ','.join(self.get_keywords())
Fred Drakedb7b0022005-03-20 22:19:47 +00001043 if keywords:
1044 file.write('Keywords: %s\n' % keywords )
1045
1046 self._write_list(file, 'Platform', self.get_platforms())
1047 self._write_list(file, 'Classifier', self.get_classifiers())
1048
1049 # PEP 314
1050 self._write_list(file, 'Requires', self.get_requires())
1051 self._write_list(file, 'Provides', self.get_provides())
1052 self._write_list(file, 'Obsoletes', self.get_obsoletes())
1053
Tarek Ziadé188789d2009-05-16 18:37:32 +00001054 def _write_list(self, file, name, values):
Fred Drakedb7b0022005-03-20 22:19:47 +00001055 for value in values:
1056 file.write('%s: %s\n' % (name, value))
1057
Greg Ward82715e12000-04-21 02:28:14 +00001058 # -- Metadata query methods ----------------------------------------
1059
Tarek Ziadé188789d2009-05-16 18:37:32 +00001060 def get_name(self):
Greg Wardfe6462c2000-04-04 01:40:52 +00001061 return self.name or "UNKNOWN"
1062
Greg Ward82715e12000-04-21 02:28:14 +00001063 def get_version(self):
Thomas Hellerbcd89752001-12-06 20:44:19 +00001064 return self.version or "0.0.0"
Greg Wardfe6462c2000-04-04 01:40:52 +00001065
Tarek Ziadé188789d2009-05-16 18:37:32 +00001066 def get_fullname(self):
Greg Ward82715e12000-04-21 02:28:14 +00001067 return "%s-%s" % (self.get_name(), self.get_version())
1068
1069 def get_author(self):
1070 return self.author or "UNKNOWN"
1071
1072 def get_author_email(self):
1073 return self.author_email or "UNKNOWN"
1074
1075 def get_maintainer(self):
1076 return self.maintainer or "UNKNOWN"
1077
1078 def get_maintainer_email(self):
1079 return self.maintainer_email or "UNKNOWN"
1080
1081 def get_contact(self):
Tarek Ziadé188789d2009-05-16 18:37:32 +00001082 return self.maintainer or self.author or "UNKNOWN"
Greg Ward82715e12000-04-21 02:28:14 +00001083
1084 def get_contact_email(self):
Tarek Ziadé188789d2009-05-16 18:37:32 +00001085 return self.maintainer_email or self.author_email or "UNKNOWN"
Greg Ward82715e12000-04-21 02:28:14 +00001086
1087 def get_url(self):
1088 return self.url or "UNKNOWN"
1089
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +00001090 def get_license(self):
1091 return self.license or "UNKNOWN"
1092 get_licence = get_license
Fred Drakeb94b8492001-12-06 20:51:35 +00001093
Greg Ward82715e12000-04-21 02:28:14 +00001094 def get_description(self):
1095 return self.description or "UNKNOWN"
Greg Warde5a584e2000-04-26 02:26:55 +00001096
1097 def get_long_description(self):
1098 return self.long_description or "UNKNOWN"
1099
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001100 def get_keywords(self):
1101 return self.keywords or []
1102
1103 def get_platforms(self):
1104 return self.platforms or ["UNKNOWN"]
1105
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +00001106 def get_classifiers(self):
1107 return self.classifiers or []
1108
Andrew M. Kuchling188d85f2003-02-19 14:16:01 +00001109 def get_download_url(self):
1110 return self.download_url or "UNKNOWN"
1111
Fred Drakedb7b0022005-03-20 22:19:47 +00001112 # PEP 314
Fred Drakedb7b0022005-03-20 22:19:47 +00001113 def get_requires(self):
1114 return self.requires or []
1115
1116 def set_requires(self, value):
1117 import distutils.versionpredicate
1118 for v in value:
1119 distutils.versionpredicate.VersionPredicate(v)
1120 self.requires = value
1121
1122 def get_provides(self):
1123 return self.provides or []
1124
1125 def set_provides(self, value):
1126 value = [v.strip() for v in value]
1127 for v in value:
1128 import distutils.versionpredicate
Fred Drake227e8ff2005-03-21 06:36:32 +00001129 distutils.versionpredicate.split_provision(v)
Fred Drakedb7b0022005-03-20 22:19:47 +00001130 self.provides = value
1131
1132 def get_obsoletes(self):
1133 return self.obsoletes or []
1134
1135 def set_obsoletes(self, value):
1136 import distutils.versionpredicate
1137 for v in value:
1138 distutils.versionpredicate.VersionPredicate(v)
1139 self.obsoletes = value
1140
Tarek Ziadé188789d2009-05-16 18:37:32 +00001141def fix_help_options(options):
Greg Ward2ff78872000-06-24 00:23:20 +00001142 """Convert a 4-tuple 'help_options' list as found in various command
1143 classes to the 3-tuple form required by FancyGetopt.
1144 """
1145 new_options = []
1146 for help_tuple in options:
1147 new_options.append(help_tuple[0:3])
1148 return new_options