blob: f49afcce135342d03442d71c23c05c98a3724b96 [file] [log] [blame]
Greg Wardfe6462c2000-04-04 01:40:52 +00001"""distutils.dist
2
3Provides the Distribution class, which represents the module distribution
Greg Ward8ff5a3f2000-06-02 00:44:53 +00004being built/installed/distributed.
5"""
Greg Wardfe6462c2000-04-04 01:40:52 +00006
Greg Wardfe6462c2000-04-04 01:40:52 +00007__revision__ = "$Id$"
8
Tarek Ziadéc01cbc42009-06-01 22:22:13 +00009import sys, os, re
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
Marc-André Lemburgb339b2a2008-09-03 11:13:56 +000022# Encoding used for the PKG-INFO files
23PKG_INFO_ENCODING = 'utf-8'
24
Greg Wardfe6462c2000-04-04 01:40:52 +000025# Regex to define acceptable Distutils command names. This is not *quite*
26# the same as a Python NAME -- I don't allow leading underscores. The fact
27# that they're very similar is no coincidence; the default naming scheme is
28# to look for a Python module named after the command.
29command_re = re.compile (r'^[a-zA-Z]([a-zA-Z0-9_]*)$')
30
31
32class Distribution:
Greg Ward8ff5a3f2000-06-02 00:44:53 +000033 """The core of the Distutils. Most of the work hiding behind 'setup'
34 is really done within a Distribution instance, which farms the work out
35 to the Distutils commands specified on the command line.
Greg Wardfe6462c2000-04-04 01:40:52 +000036
Greg Ward8ff5a3f2000-06-02 00:44:53 +000037 Setup scripts will almost never instantiate Distribution directly,
38 unless the 'setup()' function is totally inadequate to their needs.
39 However, it is conceivable that a setup script might wish to subclass
40 Distribution for some specialized purpose, and then pass the subclass
41 to 'setup()' as the 'distclass' keyword argument. If so, it is
42 necessary to respect the expectations that 'setup' has of Distribution.
43 See the code for 'setup()', in core.py, for details.
44 """
Greg Wardfe6462c2000-04-04 01:40:52 +000045
46
47 # 'global_options' describes the command-line options that may be
Greg Ward82715e12000-04-21 02:28:14 +000048 # supplied to the setup script prior to any actual commands.
49 # Eg. "./setup.py -n" or "./setup.py --quiet" both take advantage of
Greg Wardfe6462c2000-04-04 01:40:52 +000050 # these global options. This list should be kept to a bare minimum,
51 # since every global option is also valid as a command option -- and we
52 # don't want to pollute the commands with too many options that they
53 # have minimal control over.
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000054 # The fourth entry for verbose means that it can be repeated.
55 global_options = [('verbose', 'v', "run verbosely (default)", 1),
Greg Wardd5d8a992000-05-23 01:42:17 +000056 ('quiet', 'q', "run quietly (turns verbosity off)"),
57 ('dry-run', 'n', "don't actually do anything"),
58 ('help', 'h', "show detailed help message"),
Greg Wardfe6462c2000-04-04 01:40:52 +000059 ]
Greg Ward82715e12000-04-21 02:28:14 +000060
Martin v. Löwis8ed338a2005-03-03 08:12:27 +000061 # 'common_usage' is a short (2-3 line) string describing the common
62 # usage of the setup script.
63 common_usage = """\
64Common commands: (see '--help-commands' for more)
65
66 setup.py build will build the package underneath 'build/'
67 setup.py install will install the package
68"""
69
Greg Ward82715e12000-04-21 02:28:14 +000070 # options that are not propagated to the commands
71 display_options = [
72 ('help-commands', None,
73 "list all available commands"),
74 ('name', None,
75 "print package name"),
76 ('version', 'V',
77 "print package version"),
78 ('fullname', None,
79 "print <package name>-<version>"),
80 ('author', None,
81 "print the author's name"),
82 ('author-email', None,
83 "print the author's email address"),
84 ('maintainer', None,
85 "print the maintainer's name"),
86 ('maintainer-email', None,
87 "print the maintainer's email address"),
88 ('contact', None,
Greg Wardd5d8a992000-05-23 01:42:17 +000089 "print the maintainer's name if known, else the author's"),
Greg Ward82715e12000-04-21 02:28:14 +000090 ('contact-email', None,
Greg Wardd5d8a992000-05-23 01:42:17 +000091 "print the maintainer's email address if known, else the author's"),
Greg Ward82715e12000-04-21 02:28:14 +000092 ('url', None,
93 "print the URL for this package"),
Greg Ward82715e12000-04-21 02:28:14 +000094 ('license', None,
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +000095 "print the license of the package"),
96 ('licence', None,
97 "alias for --license"),
Greg Ward82715e12000-04-21 02:28:14 +000098 ('description', None,
99 "print the package description"),
Greg Warde5a584e2000-04-26 02:26:55 +0000100 ('long-description', None,
101 "print the long package description"),
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000102 ('platforms', None,
103 "print the list of platforms"),
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +0000104 ('classifiers', None,
105 "print the list of classifiers"),
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000106 ('keywords', None,
107 "print the list of keywords"),
Fred Drakedb7b0022005-03-20 22:19:47 +0000108 ('provides', None,
109 "print the list of packages/modules provided"),
110 ('requires', None,
111 "print the list of packages/modules required"),
112 ('obsoletes', None,
113 "print the list of packages/modules made obsolete")
Greg Ward82715e12000-04-21 02:28:14 +0000114 ]
Greg Ward2f2b6c62000-09-25 01:58:07 +0000115 display_option_names = map(lambda x: translate_longopt(x[0]),
116 display_options)
Greg Ward82715e12000-04-21 02:28:14 +0000117
118 # negative options are options that exclude other options
Greg Wardfe6462c2000-04-04 01:40:52 +0000119 negative_opt = {'quiet': 'verbose'}
120
121
122 # -- Creation/initialization methods -------------------------------
Fred Drakeb94b8492001-12-06 20:51:35 +0000123
Greg Wardfe6462c2000-04-04 01:40:52 +0000124 def __init__ (self, attrs=None):
125 """Construct a new Distribution instance: initialize all the
Greg Ward8ff5a3f2000-06-02 00:44:53 +0000126 attributes of a Distribution, and then use 'attrs' (a dictionary
127 mapping attribute names to values) to assign some of those
128 attributes their "real" values. (Any attributes not mentioned in
129 'attrs' will be assigned to some null value: 0, None, an empty list
130 or dictionary, etc.) Most importantly, initialize the
131 'command_obj' attribute to the empty dictionary; this will be
132 filled in with real command objects by 'parse_command_line()'.
133 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000134
135 # Default values for our command-line options
136 self.verbose = 1
137 self.dry_run = 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000138 self.help = 0
Greg Ward82715e12000-04-21 02:28:14 +0000139 for attr in self.display_option_names:
140 setattr(self, attr, 0)
Greg Wardfe6462c2000-04-04 01:40:52 +0000141
Greg Ward82715e12000-04-21 02:28:14 +0000142 # Store the distribution meta-data (name, version, author, and so
143 # forth) in a separate object -- we're getting to have enough
144 # information here (and enough command-line options) that it's
145 # worth it. Also delegate 'get_XXX()' methods to the 'metadata'
146 # object in a sneaky and underhanded (but efficient!) way.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000147 self.metadata = DistributionMetadata()
Neil Schemenauera8aefe52001-09-03 15:47:21 +0000148 for basename in self.metadata._METHOD_BASENAMES:
Greg Ward4982f982000-04-22 02:52:44 +0000149 method_name = "get_" + basename
150 setattr(self, method_name, getattr(self.metadata, method_name))
Greg Wardfe6462c2000-04-04 01:40:52 +0000151
152 # 'cmdclass' maps command names to class objects, so we
153 # can 1) quickly figure out which class to instantiate when
154 # we need to create a new command object, and 2) have a way
Greg Ward82715e12000-04-21 02:28:14 +0000155 # for the setup script to override command classes
Greg Wardfe6462c2000-04-04 01:40:52 +0000156 self.cmdclass = {}
157
Fred Draked04573f2004-08-03 16:37:40 +0000158 # 'command_packages' is a list of packages in which commands
159 # are searched for. The factory for command 'foo' is expected
160 # to be named 'foo' in the module 'foo' in one of the packages
161 # named here. This list is searched from the left; an error
162 # is raised if no named package provides the command being
163 # searched for. (Always access using get_command_packages().)
164 self.command_packages = None
165
Greg Ward9821bf42000-08-29 01:15:18 +0000166 # 'script_name' and 'script_args' are usually set to sys.argv[0]
167 # and sys.argv[1:], but they can be overridden when the caller is
168 # not necessarily a setup script run from the command-line.
169 self.script_name = None
170 self.script_args = None
171
Greg Wardd5d8a992000-05-23 01:42:17 +0000172 # 'command_options' is where we store command options between
173 # parsing them (from config files, the command-line, etc.) and when
174 # they are actually needed -- ie. when the command in question is
175 # instantiated. It is a dictionary of dictionaries of 2-tuples:
176 # command_options = { command_name : { option : (source, value) } }
Gregory P. Smith14263542000-05-12 00:41:33 +0000177 self.command_options = {}
178
Martin v. Löwis98da5622005-03-23 18:54:36 +0000179 # 'dist_files' is the list of (command, pyversion, file) that
180 # have been created by any dist commands run so far. This is
181 # filled regardless of whether the run is dry or not. pyversion
182 # gives sysconfig.get_python_version() if the dist file is
183 # specific to a Python version, 'any' if it is good for all
184 # Python versions on the target platform, and '' for a source
185 # file. pyversion should not be used to specify minimum or
186 # maximum required Python versions; use the metainfo for that
187 # instead.
Martin v. Löwis55f1bb82005-03-21 20:56:35 +0000188 self.dist_files = []
189
Greg Wardfe6462c2000-04-04 01:40:52 +0000190 # These options are really the business of various commands, rather
191 # than of the Distribution itself. We provide aliases for them in
192 # Distribution as a convenience to the developer.
Greg Wardfe6462c2000-04-04 01:40:52 +0000193 self.packages = None
Fred Drake0eb32a62004-06-11 21:50:33 +0000194 self.package_data = {}
Greg Wardfe6462c2000-04-04 01:40:52 +0000195 self.package_dir = None
196 self.py_modules = None
197 self.libraries = None
Greg Ward51def7d2000-05-27 01:36:14 +0000198 self.headers = None
Greg Wardfe6462c2000-04-04 01:40:52 +0000199 self.ext_modules = None
200 self.ext_package = None
201 self.include_dirs = None
202 self.extra_path = None
Gregory P. Smithb2e3bb32000-05-12 00:52:23 +0000203 self.scripts = None
Gregory P. Smith6a901dd2000-05-13 03:09:50 +0000204 self.data_files = None
Tarek Ziadé1a240fb2009-01-08 23:56:31 +0000205 self.password = ''
Greg Wardfe6462c2000-04-04 01:40:52 +0000206
207 # And now initialize bookkeeping stuff that can't be supplied by
208 # the caller at all. 'command_obj' maps command names to
209 # Command instances -- that's how we enforce that every command
210 # class is a singleton.
211 self.command_obj = {}
212
213 # 'have_run' maps command names to boolean values; it keeps track
214 # of whether we have actually run a particular command, to make it
215 # cheap to "run" a command whenever we think we might need to -- if
216 # it's already been done, no need for expensive filesystem
217 # operations, we just check the 'have_run' dictionary and carry on.
218 # It's only safe to query 'have_run' for a command class that has
219 # been instantiated -- a false value will be inserted when the
220 # command object is created, and replaced with a true value when
Greg Ward612eb9f2000-07-27 02:13:20 +0000221 # the command is successfully run. Thus it's probably best to use
Greg Wardfe6462c2000-04-04 01:40:52 +0000222 # '.get()' rather than a straight lookup.
223 self.have_run = {}
224
225 # Now we'll use the attrs dictionary (ultimately, keyword args from
Greg Ward82715e12000-04-21 02:28:14 +0000226 # the setup script) to possibly override any or all of these
227 # distribution options.
228
Greg Wardfe6462c2000-04-04 01:40:52 +0000229 if attrs:
Greg Wardfe6462c2000-04-04 01:40:52 +0000230 # Pull out the set of command options and work on them
231 # specifically. Note that this order guarantees that aliased
232 # command options will override any supplied redundantly
233 # through the general options dictionary.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000234 options = attrs.get('options')
Tarek Ziadéc13acb12008-12-29 22:23:53 +0000235 if options is not None:
Greg Wardfe6462c2000-04-04 01:40:52 +0000236 del attrs['options']
237 for (command, cmd_options) in options.items():
Greg Ward0e48cfd2000-05-26 01:00:15 +0000238 opt_dict = self.get_option_dict(command)
239 for (opt, val) in cmd_options.items():
240 opt_dict[opt] = ("setup script", val)
Greg Wardfe6462c2000-04-04 01:40:52 +0000241
Guido van Rossum8bc09652008-02-21 18:18:37 +0000242 if 'licence' in attrs:
Andrew M. Kuchlinga52b8522003-03-03 20:07:27 +0000243 attrs['license'] = attrs['licence']
244 del attrs['licence']
245 msg = "'licence' distribution option is deprecated; use 'license'"
246 if warnings is not None:
247 warnings.warn(msg)
248 else:
249 sys.stderr.write(msg + "\n")
250
Greg Wardfe6462c2000-04-04 01:40:52 +0000251 # Now work on the rest of the attributes. Any attribute that's
252 # not already defined is invalid!
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000253 for (key, val) in attrs.items():
Fred Drakedb7b0022005-03-20 22:19:47 +0000254 if hasattr(self.metadata, "set_" + key):
255 getattr(self.metadata, "set_" + key)(val)
256 elif hasattr(self.metadata, key):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000257 setattr(self.metadata, key, val)
258 elif hasattr(self, key):
259 setattr(self, key, val)
Anthony Baxter73cc8472004-10-13 13:22:34 +0000260 else:
Andrew M. Kuchlingff4ad9a2002-10-31 13:22:41 +0000261 msg = "Unknown distribution option: %s" % repr(key)
262 if warnings is not None:
263 warnings.warn(msg)
264 else:
265 sys.stderr.write(msg + "\n")
Greg Wardfe6462c2000-04-04 01:40:52 +0000266
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000267 self.finalize_options()
Fred Drakeb94b8492001-12-06 20:51:35 +0000268
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000269 def get_option_dict(self, command):
Greg Ward0e48cfd2000-05-26 01:00:15 +0000270 """Get the option dictionary for a given command. If that
271 command's option dictionary hasn't been created yet, then create it
272 and return the new dictionary; otherwise, return the existing
273 option dictionary.
274 """
Greg Ward0e48cfd2000-05-26 01:00:15 +0000275 dict = self.command_options.get(command)
276 if dict is None:
277 dict = self.command_options[command] = {}
278 return dict
279
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000280 def dump_option_dicts(self, header=None, commands=None, indent=""):
Greg Wardc32d9a62000-05-28 23:53:06 +0000281 from pprint import pformat
282
283 if commands is None: # dump all command option dicts
284 commands = self.command_options.keys()
285 commands.sort()
286
287 if header is not None:
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000288 self.announce(indent + header)
Greg Wardc32d9a62000-05-28 23:53:06 +0000289 indent = indent + " "
290
291 if not commands:
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000292 self.announce(indent + "no commands known yet")
Greg Wardc32d9a62000-05-28 23:53:06 +0000293 return
294
295 for cmd_name in commands:
296 opt_dict = self.command_options.get(cmd_name)
297 if opt_dict is None:
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000298 self.announce(indent +
299 "no option dict for '%s' command" % cmd_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000300 else:
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000301 self.announce(indent +
302 "option dict for '%s' command:" % cmd_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000303 out = pformat(opt_dict)
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000304 for line in out.split('\n'):
305 self.announce(indent + " " + line)
Greg Wardc32d9a62000-05-28 23:53:06 +0000306
Greg Wardd5d8a992000-05-23 01:42:17 +0000307 # -- Config file finding/parsing methods ---------------------------
308
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000309 def find_config_files(self):
Gregory P. Smith14263542000-05-12 00:41:33 +0000310 """Find as many configuration files as should be processed for this
311 platform, and return a list of filenames in the order in which they
312 should be parsed. The filenames returned are guaranteed to exist
313 (modulo nasty race conditions).
314
Andrew M. Kuchlingd303b612001-12-06 16:32:05 +0000315 There are three possible config files: distutils.cfg in the
316 Distutils installation directory (ie. where the top-level
317 Distutils __inst__.py file lives), a file in the user's home
318 directory named .pydistutils.cfg on Unix and pydistutils.cfg
319 on Windows/Mac, and setup.cfg in the current directory.
Greg Wardd5d8a992000-05-23 01:42:17 +0000320 """
Gregory P. Smith14263542000-05-12 00:41:33 +0000321 files = []
Greg Wardacf3f6a2000-06-07 02:26:19 +0000322 check_environ()
Gregory P. Smith14263542000-05-12 00:41:33 +0000323
Greg Ward11696872000-06-07 02:29:03 +0000324 # Where to look for the system-wide Distutils config file
325 sys_dir = os.path.dirname(sys.modules['distutils'].__file__)
326
327 # Look for the system config file
328 sys_file = os.path.join(sys_dir, "distutils.cfg")
Greg Wardacf3f6a2000-06-07 02:26:19 +0000329 if os.path.isfile(sys_file):
330 files.append(sys_file)
Gregory P. Smith14263542000-05-12 00:41:33 +0000331
Greg Ward11696872000-06-07 02:29:03 +0000332 # What to call the per-user config file
333 if os.name == 'posix':
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000334 user_filename = ".pydistutils.cfg"
335 else:
336 user_filename = "pydistutils.cfg"
Greg Wardfa9ff762000-10-14 04:06:40 +0000337
Greg Ward11696872000-06-07 02:29:03 +0000338 # And look for the user config file
Andrew M. Kuchlingaac5c862008-05-11 14:00:00 +0000339 user_file = os.path.join(os.path.expanduser('~'), user_filename)
340 if os.path.isfile(user_file):
341 files.append(user_file)
Gregory P. Smith14263542000-05-12 00:41:33 +0000342
Gregory P. Smith14263542000-05-12 00:41:33 +0000343 # All platforms support local setup.cfg
344 local_file = "setup.cfg"
345 if os.path.isfile(local_file):
346 files.append(local_file)
347
348 return files
349
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000350 def parse_config_files(self, filenames=None):
Georg Brandl392c6fc2008-05-25 07:25:25 +0000351 from ConfigParser import ConfigParser
Gregory P. Smith14263542000-05-12 00:41:33 +0000352
353 if filenames is None:
354 filenames = self.find_config_files()
355
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000356 if DEBUG:
357 self.announce("Distribution.parse_config_files():")
Greg Ward47460772000-05-23 03:47:35 +0000358
Gregory P. Smith14263542000-05-12 00:41:33 +0000359 parser = ConfigParser()
Greg Wardd5d8a992000-05-23 01:42:17 +0000360 for filename in filenames:
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000361 if DEBUG:
Tarek Ziadé99773352009-09-21 13:41:08 +0000362 self.announce(" reading %s" % filename)
Greg Wardd5d8a992000-05-23 01:42:17 +0000363 parser.read(filename)
364 for section in parser.sections():
365 options = parser.options(section)
Greg Ward0e48cfd2000-05-26 01:00:15 +0000366 opt_dict = self.get_option_dict(section)
Gregory P. Smith14263542000-05-12 00:41:33 +0000367
Greg Wardd5d8a992000-05-23 01:42:17 +0000368 for opt in options:
369 if opt != '__name__':
Greg Wardceb9e222000-09-25 01:23:52 +0000370 val = parser.get(section,opt)
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000371 opt = opt.replace('-', '_')
Greg Wardceb9e222000-09-25 01:23:52 +0000372 opt_dict[opt] = (filename, val)
Gregory P. Smith14263542000-05-12 00:41:33 +0000373
Greg Ward47460772000-05-23 03:47:35 +0000374 # Make the ConfigParser forget everything (so we retain
Fred Drakef06116d2004-02-17 22:35:19 +0000375 # the original filenames that options come from)
Greg Ward47460772000-05-23 03:47:35 +0000376 parser.__init__()
Gregory P. Smith14263542000-05-12 00:41:33 +0000377
Greg Wardceb9e222000-09-25 01:23:52 +0000378 # If there was a "global" section in the config file, use it
379 # to set Distribution options.
380
Guido van Rossum8bc09652008-02-21 18:18:37 +0000381 if 'global' in self.command_options:
Greg Wardceb9e222000-09-25 01:23:52 +0000382 for (opt, (src, val)) in self.command_options['global'].items():
383 alias = self.negative_opt.get(opt)
384 try:
385 if alias:
386 setattr(self, alias, not strtobool(val))
387 elif opt in ('verbose', 'dry_run'): # ugh!
388 setattr(self, opt, strtobool(val))
Fred Draked04573f2004-08-03 16:37:40 +0000389 else:
390 setattr(self, opt, val)
Greg Wardceb9e222000-09-25 01:23:52 +0000391 except ValueError, msg:
392 raise DistutilsOptionError, msg
393
Greg Wardd5d8a992000-05-23 01:42:17 +0000394 # -- Command-line parsing methods ----------------------------------
395
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000396 def parse_command_line(self):
Greg Ward9821bf42000-08-29 01:15:18 +0000397 """Parse the setup script's command line, taken from the
398 'script_args' instance attribute (which defaults to 'sys.argv[1:]'
399 -- see 'setup()' in core.py). This list is first processed for
400 "global options" -- options that set attributes of the Distribution
401 instance. Then, it is alternately scanned for Distutils commands
402 and options for that command. Each new command terminates the
403 options for the previous command. The allowed options for a
404 command are determined by the 'user_options' attribute of the
405 command class -- thus, we have to be able to load command classes
406 in order to parse the command line. Any error in that 'options'
407 attribute raises DistutilsGetoptError; any error on the
408 command-line raises DistutilsArgError. If no Distutils commands
409 were found on the command line, raises DistutilsArgError. Return
Greg Wardceb9e222000-09-25 01:23:52 +0000410 true if command-line was successfully parsed and we should carry
Greg Ward9821bf42000-08-29 01:15:18 +0000411 on with executing commands; false if no errors but we shouldn't
412 execute commands (currently, this only happens if user asks for
413 help).
Greg Wardd5d8a992000-05-23 01:42:17 +0000414 """
Andrew M. Kuchling3f819ec2001-01-15 16:09:35 +0000415 #
Fred Drake981a1782001-08-10 18:59:30 +0000416 # We now have enough information to show the Macintosh dialog
417 # that allows the user to interactively specify the "command line".
Andrew M. Kuchling3f819ec2001-01-15 16:09:35 +0000418 #
Fred Draked04573f2004-08-03 16:37:40 +0000419 toplevel_options = self._get_toplevel_options()
Fred Drakeb94b8492001-12-06 20:51:35 +0000420
Greg Wardfe6462c2000-04-04 01:40:52 +0000421 # We have to parse the command line a bit at a time -- global
422 # options, then the first command, then its options, and so on --
423 # because each command will be handled by a different class, and
Greg Wardd5d8a992000-05-23 01:42:17 +0000424 # the options that are valid for a particular class aren't known
425 # until we have loaded the command class, which doesn't happen
426 # until we know what the command is.
Greg Wardfe6462c2000-04-04 01:40:52 +0000427
428 self.commands = []
Fred Draked04573f2004-08-03 16:37:40 +0000429 parser = FancyGetopt(toplevel_options + self.display_options)
Greg Wardfd7b91e2000-09-26 01:52:25 +0000430 parser.set_negative_aliases(self.negative_opt)
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +0000431 parser.set_aliases({'licence': 'license'})
Greg Wardfd7b91e2000-09-26 01:52:25 +0000432 args = parser.getopt(args=self.script_args, object=self)
Greg Ward82715e12000-04-21 02:28:14 +0000433 option_order = parser.get_option_order()
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000434 log.set_verbosity(self.verbose)
Greg Wardfe6462c2000-04-04 01:40:52 +0000435
Greg Ward82715e12000-04-21 02:28:14 +0000436 # for display options we return immediately
437 if self.handle_display_options(option_order):
Greg Wardfe6462c2000-04-04 01:40:52 +0000438 return
Greg Wardfe6462c2000-04-04 01:40:52 +0000439 while args:
Greg Wardd5d8a992000-05-23 01:42:17 +0000440 args = self._parse_command_opts(parser, args)
441 if args is None: # user asked for help (and got it)
Greg Wardfe6462c2000-04-04 01:40:52 +0000442 return
Greg Wardfe6462c2000-04-04 01:40:52 +0000443
Greg Wardd5d8a992000-05-23 01:42:17 +0000444 # Handle the cases of --help as a "global" option, ie.
445 # "setup.py --help" and "setup.py --help command ...". For the
446 # former, we show global options (--verbose, --dry-run, etc.)
447 # and display-only options (--name, --version, etc.); for the
448 # latter, we omit the display-only options and show help for
449 # each command listed on the command line.
Greg Wardfe6462c2000-04-04 01:40:52 +0000450 if self.help:
Greg Wardd5d8a992000-05-23 01:42:17 +0000451 self._show_help(parser,
452 display_options=len(self.commands) == 0,
453 commands=self.commands)
Greg Wardfe6462c2000-04-04 01:40:52 +0000454 return
455
456 # Oops, no commands found -- an end-user error
457 if not self.commands:
458 raise DistutilsArgError, "no commands supplied"
459
460 # All is well: return true
461 return 1
462
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000463 def _get_toplevel_options(self):
Fred Draked04573f2004-08-03 16:37:40 +0000464 """Return the non-display options recognized at the top level.
465
466 This includes options that are recognized *only* at the top
467 level as well as options recognized for commands.
468 """
469 return self.global_options + [
470 ("command-packages=", None,
471 "list of packages that provide distutils commands"),
472 ]
473
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000474 def _parse_command_opts(self, parser, args):
Greg Wardd5d8a992000-05-23 01:42:17 +0000475 """Parse the command-line options for a single command.
476 'parser' must be a FancyGetopt instance; 'args' must be the list
477 of arguments, starting with the current command (whose options
478 we are about to parse). Returns a new version of 'args' with
479 the next command at the front of the list; will be the empty
480 list if there are no more commands on the command line. Returns
481 None if the user asked for help on this command.
482 """
483 # late import because of mutual dependence between these modules
484 from distutils.cmd import Command
485
486 # Pull the current command from the head of the command line
487 command = args[0]
Greg Wardfd7b91e2000-09-26 01:52:25 +0000488 if not command_re.match(command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000489 raise SystemExit, "invalid command name '%s'" % command
Greg Wardfd7b91e2000-09-26 01:52:25 +0000490 self.commands.append(command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000491
492 # Dig up the command class that implements this command, so we
493 # 1) know that it's a valid command, and 2) know which options
494 # it takes.
495 try:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000496 cmd_class = self.get_command_class(command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000497 except DistutilsModuleError, msg:
498 raise DistutilsArgError, msg
499
500 # Require that the command class be derived from Command -- want
501 # to be sure that the basic "command" interface is implemented.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000502 if not issubclass(cmd_class, Command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000503 raise DistutilsClassError, \
504 "command class %s must subclass Command" % cmd_class
505
506 # Also make sure that the command object provides a list of its
507 # known options.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000508 if not (hasattr(cmd_class, 'user_options') and
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000509 isinstance(cmd_class.user_options, list)):
Greg Wardd5d8a992000-05-23 01:42:17 +0000510 raise DistutilsClassError, \
511 ("command class %s must provide " +
512 "'user_options' attribute (a list of tuples)") % \
513 cmd_class
514
515 # If the command class has a list of negative alias options,
516 # merge it in with the global negative aliases.
517 negative_opt = self.negative_opt
Greg Wardfd7b91e2000-09-26 01:52:25 +0000518 if hasattr(cmd_class, 'negative_opt'):
Antoine Pitrouf5413782009-05-15 17:27:30 +0000519 negative_opt = negative_opt.copy()
Greg Wardfd7b91e2000-09-26 01:52:25 +0000520 negative_opt.update(cmd_class.negative_opt)
Greg Wardd5d8a992000-05-23 01:42:17 +0000521
Greg Wardfa9ff762000-10-14 04:06:40 +0000522 # Check for help_options in command class. They have a different
523 # format (tuple of four) so we need to preprocess them here.
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000524 if (hasattr(cmd_class, 'help_options') and
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000525 isinstance(cmd_class.help_options, list)):
Greg Ward2ff78872000-06-24 00:23:20 +0000526 help_options = fix_help_options(cmd_class.help_options)
527 else:
Greg Ward55fced32000-06-24 01:22:41 +0000528 help_options = []
Greg Ward2ff78872000-06-24 00:23:20 +0000529
Greg Ward9d17a7a2000-06-07 03:00:06 +0000530
Greg Wardd5d8a992000-05-23 01:42:17 +0000531 # All commands support the global options too, just by adding
532 # in 'global_options'.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000533 parser.set_option_table(self.global_options +
534 cmd_class.user_options +
535 help_options)
536 parser.set_negative_aliases(negative_opt)
537 (args, opts) = parser.getopt(args[1:])
Greg Ward47460772000-05-23 03:47:35 +0000538 if hasattr(opts, 'help') and opts.help:
Greg Wardd5d8a992000-05-23 01:42:17 +0000539 self._show_help(parser, display_options=0, commands=[cmd_class])
540 return
541
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000542 if (hasattr(cmd_class, 'help_options') and
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000543 isinstance(cmd_class.help_options, list)):
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000544 help_option_found=0
545 for (help_option, short, desc, func) in cmd_class.help_options:
546 if hasattr(opts, parser.get_attr_name(help_option)):
547 help_option_found=1
Greg Ward55fced32000-06-24 01:22:41 +0000548 if callable(func):
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000549 func()
Greg Ward55fced32000-06-24 01:22:41 +0000550 else:
Fred Drake981a1782001-08-10 18:59:30 +0000551 raise DistutilsClassError(
Walter Dörwald70a6b492004-02-12 17:35:32 +0000552 "invalid help function %r for help option '%s': "
Fred Drake981a1782001-08-10 18:59:30 +0000553 "must be a callable object (function, etc.)"
Walter Dörwald70a6b492004-02-12 17:35:32 +0000554 % (func, help_option))
Greg Ward55fced32000-06-24 01:22:41 +0000555
Fred Drakeb94b8492001-12-06 20:51:35 +0000556 if help_option_found:
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000557 return
Greg Ward9d17a7a2000-06-07 03:00:06 +0000558
Greg Wardd5d8a992000-05-23 01:42:17 +0000559 # Put the options from the command-line into their official
560 # holding pen, the 'command_options' dictionary.
Greg Ward0e48cfd2000-05-26 01:00:15 +0000561 opt_dict = self.get_option_dict(command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000562 for (name, value) in vars(opts).items():
Greg Ward0e48cfd2000-05-26 01:00:15 +0000563 opt_dict[name] = ("command line", value)
Greg Wardd5d8a992000-05-23 01:42:17 +0000564
565 return args
566
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000567 def finalize_options(self):
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000568 """Set final values for all the options on the Distribution
569 instance, analogous to the .finalize_options() method of Command
570 objects.
571 """
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000572 for attr in ('keywords', 'platforms'):
573 value = getattr(self.metadata, attr)
574 if value is None:
575 continue
576 if isinstance(value, str):
577 value = [elm.strip() for elm in value.split(',')]
578 setattr(self.metadata, attr, value)
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000579
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000580 def _show_help(self, parser, global_options=1, display_options=1,
581 commands=[]):
Greg Wardd5d8a992000-05-23 01:42:17 +0000582 """Show help for the setup script command-line in the form of
583 several lists of command-line options. 'parser' should be a
584 FancyGetopt instance; do not expect it to be returned in the
585 same state, as its option table will be reset to make it
586 generate the correct help text.
587
588 If 'global_options' is true, lists the global options:
589 --verbose, --dry-run, etc. If 'display_options' is true, lists
590 the "display-only" options: --name, --version, etc. Finally,
591 lists per-command help for every command name or command class
592 in 'commands'.
593 """
594 # late import because of mutual dependence between these modules
Greg Ward9821bf42000-08-29 01:15:18 +0000595 from distutils.core import gen_usage
Greg Wardd5d8a992000-05-23 01:42:17 +0000596 from distutils.cmd import Command
597
598 if global_options:
Fred Draked04573f2004-08-03 16:37:40 +0000599 if display_options:
600 options = self._get_toplevel_options()
601 else:
602 options = self.global_options
603 parser.set_option_table(options)
Martin v. Löwis8ed338a2005-03-03 08:12:27 +0000604 parser.print_help(self.common_usage + "\nGlobal options:")
Tarek Ziadécd947e02009-07-04 02:59:19 +0000605 print('')
Greg Wardd5d8a992000-05-23 01:42:17 +0000606
607 if display_options:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000608 parser.set_option_table(self.display_options)
609 parser.print_help(
Greg Wardd5d8a992000-05-23 01:42:17 +0000610 "Information display options (just display " +
611 "information, ignore any commands)")
Tarek Ziadécd947e02009-07-04 02:59:19 +0000612 print('')
Greg Wardd5d8a992000-05-23 01:42:17 +0000613
614 for command in self.commands:
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000615 if isinstance(command, type) and issubclass(command, Command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000616 klass = command
617 else:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000618 klass = self.get_command_class(command)
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000619 if (hasattr(klass, 'help_options') and
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000620 isinstance(klass.help_options, list)):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000621 parser.set_option_table(klass.user_options +
622 fix_help_options(klass.help_options))
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000623 else:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000624 parser.set_option_table(klass.user_options)
625 parser.print_help("Options for '%s' command:" % klass.__name__)
Tarek Ziadécd947e02009-07-04 02:59:19 +0000626 print('')
Greg Wardd5d8a992000-05-23 01:42:17 +0000627
Tarek Ziadécd947e02009-07-04 02:59:19 +0000628 print(gen_usage(self.script_name))
Greg Wardd5d8a992000-05-23 01:42:17 +0000629
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000630 def handle_display_options(self, option_order):
Greg Ward82715e12000-04-21 02:28:14 +0000631 """If there were any non-global "display-only" options
Greg Wardd5d8a992000-05-23 01:42:17 +0000632 (--help-commands or the metadata display options) on the command
633 line, display the requested info and return true; else return
634 false.
635 """
Greg Ward9821bf42000-08-29 01:15:18 +0000636 from distutils.core import gen_usage
Greg Ward82715e12000-04-21 02:28:14 +0000637
638 # User just wants a list of commands -- we'll print it out and stop
639 # processing now (ie. if they ran "setup --help-commands foo bar",
640 # we ignore "foo bar").
641 if self.help_commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000642 self.print_commands()
Tarek Ziadécd947e02009-07-04 02:59:19 +0000643 print('')
644 print(gen_usage(self.script_name))
Greg Ward82715e12000-04-21 02:28:14 +0000645 return 1
646
647 # If user supplied any of the "display metadata" options, then
648 # display that metadata in the order in which the user supplied the
649 # metadata options.
650 any_display_options = 0
651 is_display_option = {}
652 for option in self.display_options:
653 is_display_option[option[0]] = 1
654
655 for (opt, val) in option_order:
656 if val and is_display_option.get(opt):
Greg Ward2f2b6c62000-09-25 01:58:07 +0000657 opt = translate_longopt(opt)
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000658 value = getattr(self.metadata, "get_"+opt)()
659 if opt in ['keywords', 'platforms']:
Tarek Ziadécd947e02009-07-04 02:59:19 +0000660 print(','.join(value))
Fred Drakedb7b0022005-03-20 22:19:47 +0000661 elif opt in ('classifiers', 'provides', 'requires',
662 'obsoletes'):
Tarek Ziadécd947e02009-07-04 02:59:19 +0000663 print('\n'.join(value))
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000664 else:
Tarek Ziadécd947e02009-07-04 02:59:19 +0000665 print(value)
Greg Ward82715e12000-04-21 02:28:14 +0000666 any_display_options = 1
667
668 return any_display_options
669
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000670 def print_command_list(self, commands, header, max_length):
Greg Wardfe6462c2000-04-04 01:40:52 +0000671 """Print a subset of the list of all commands -- used by
Greg Wardd5d8a992000-05-23 01:42:17 +0000672 'print_commands()'.
673 """
Tarek Ziadécd947e02009-07-04 02:59:19 +0000674 print(header + ":")
Greg Wardfe6462c2000-04-04 01:40:52 +0000675
676 for cmd in commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000677 klass = self.cmdclass.get(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000678 if not klass:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000679 klass = self.get_command_class(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000680 try:
681 description = klass.description
682 except AttributeError:
683 description = "(no description available)"
684
Tarek Ziadécd947e02009-07-04 02:59:19 +0000685 print(" %-*s %s" % (max_length, cmd, description))
Greg Wardfe6462c2000-04-04 01:40:52 +0000686
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000687 def print_commands(self):
Greg Wardd5d8a992000-05-23 01:42:17 +0000688 """Print out a help message listing all available commands with a
689 description of each. The list is divided into "standard commands"
690 (listed in distutils.command.__all__) and "extra commands"
691 (mentioned in self.cmdclass, but not a standard command). The
692 descriptions come from the command class attribute
693 'description'.
694 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000695 import distutils.command
696 std_commands = distutils.command.__all__
697 is_std = {}
698 for cmd in std_commands:
699 is_std[cmd] = 1
700
701 extra_commands = []
702 for cmd in self.cmdclass.keys():
703 if not is_std.get(cmd):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000704 extra_commands.append(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000705
706 max_length = 0
707 for cmd in (std_commands + extra_commands):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000708 if len(cmd) > max_length:
709 max_length = len(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000710
Greg Wardfd7b91e2000-09-26 01:52:25 +0000711 self.print_command_list(std_commands,
712 "Standard commands",
713 max_length)
Greg Wardfe6462c2000-04-04 01:40:52 +0000714 if extra_commands:
715 print
Greg Wardfd7b91e2000-09-26 01:52:25 +0000716 self.print_command_list(extra_commands,
717 "Extra commands",
718 max_length)
Greg Wardfe6462c2000-04-04 01:40:52 +0000719
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000720 def get_command_list(self):
Greg Wardf6fc8752000-11-11 02:47:11 +0000721 """Get a list of (command, description) tuples.
722 The list is divided into "standard commands" (listed in
723 distutils.command.__all__) and "extra commands" (mentioned in
724 self.cmdclass, but not a standard command). The descriptions come
725 from the command class attribute 'description'.
726 """
727 # Currently this is only used on Mac OS, for the Mac-only GUI
728 # Distutils interface (by Jack Jansen)
729
730 import distutils.command
731 std_commands = distutils.command.__all__
732 is_std = {}
733 for cmd in std_commands:
734 is_std[cmd] = 1
735
736 extra_commands = []
737 for cmd in self.cmdclass.keys():
738 if not is_std.get(cmd):
739 extra_commands.append(cmd)
740
741 rv = []
742 for cmd in (std_commands + extra_commands):
743 klass = self.cmdclass.get(cmd)
744 if not klass:
745 klass = self.get_command_class(cmd)
746 try:
747 description = klass.description
748 except AttributeError:
749 description = "(no description available)"
750 rv.append((cmd, description))
751 return rv
Greg Wardfe6462c2000-04-04 01:40:52 +0000752
753 # -- Command class/object methods ----------------------------------
754
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000755 def get_command_packages(self):
Fred Draked04573f2004-08-03 16:37:40 +0000756 """Return a list of packages from which commands are loaded."""
757 pkgs = self.command_packages
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000758 if not isinstance(pkgs, list):
759 if pkgs is None:
760 pkgs = ''
761 pkgs = [pkg.strip() for pkg in pkgs.split(',') if pkg != '']
Fred Draked04573f2004-08-03 16:37:40 +0000762 if "distutils.command" not in pkgs:
763 pkgs.insert(0, "distutils.command")
764 self.command_packages = pkgs
765 return pkgs
766
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000767 def get_command_class(self, command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000768 """Return the class that implements the Distutils command named by
769 'command'. First we check the 'cmdclass' dictionary; if the
770 command is mentioned there, we fetch the class object from the
771 dictionary and return it. Otherwise we load the command module
772 ("distutils.command." + command) and fetch the command class from
773 the module. The loaded class is also stored in 'cmdclass'
774 to speed future calls to 'get_command_class()'.
Greg Wardfe6462c2000-04-04 01:40:52 +0000775
Gregory P. Smith14263542000-05-12 00:41:33 +0000776 Raises DistutilsModuleError if the expected module could not be
Greg Wardd5d8a992000-05-23 01:42:17 +0000777 found, or if that module does not define the expected class.
778 """
779 klass = self.cmdclass.get(command)
780 if klass:
781 return klass
Greg Wardfe6462c2000-04-04 01:40:52 +0000782
Fred Draked04573f2004-08-03 16:37:40 +0000783 for pkgname in self.get_command_packages():
784 module_name = "%s.%s" % (pkgname, command)
785 klass_name = command
Greg Wardfe6462c2000-04-04 01:40:52 +0000786
Fred Draked04573f2004-08-03 16:37:40 +0000787 try:
788 __import__ (module_name)
789 module = sys.modules[module_name]
790 except ImportError:
791 continue
Greg Wardfe6462c2000-04-04 01:40:52 +0000792
Fred Draked04573f2004-08-03 16:37:40 +0000793 try:
794 klass = getattr(module, klass_name)
795 except AttributeError:
796 raise DistutilsModuleError, \
797 "invalid command '%s' (no class '%s' in module '%s')" \
798 % (command, klass_name, module_name)
Greg Wardfe6462c2000-04-04 01:40:52 +0000799
Fred Draked04573f2004-08-03 16:37:40 +0000800 self.cmdclass[command] = klass
801 return klass
802
803 raise DistutilsModuleError("invalid command '%s'" % command)
804
Greg Wardfe6462c2000-04-04 01:40:52 +0000805
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000806 def get_command_obj(self, command, create=1):
Greg Wardd5d8a992000-05-23 01:42:17 +0000807 """Return the command object for 'command'. Normally this object
Greg Ward612eb9f2000-07-27 02:13:20 +0000808 is cached on a previous call to 'get_command_obj()'; if no command
Greg Wardd5d8a992000-05-23 01:42:17 +0000809 object for 'command' is in the cache, then we either create and
810 return it (if 'create' is true) or return None.
811 """
812 cmd_obj = self.command_obj.get(command)
Greg Wardfe6462c2000-04-04 01:40:52 +0000813 if not cmd_obj and create:
Greg Ward2bd3f422000-06-02 01:59:33 +0000814 if DEBUG:
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000815 self.announce("Distribution.get_command_obj(): " \
816 "creating '%s' command object" % command)
Greg Ward47460772000-05-23 03:47:35 +0000817
Greg Wardd5d8a992000-05-23 01:42:17 +0000818 klass = self.get_command_class(command)
Greg Ward47460772000-05-23 03:47:35 +0000819 cmd_obj = self.command_obj[command] = klass(self)
820 self.have_run[command] = 0
821
822 # Set any options that were supplied in config files
823 # or on the command line. (NB. support for error
824 # reporting is lame here: any errors aren't reported
825 # until 'finalize_options()' is called, which means
826 # we won't report the source of the error.)
827 options = self.command_options.get(command)
828 if options:
Greg Wardc32d9a62000-05-28 23:53:06 +0000829 self._set_command_options(cmd_obj, options)
Greg Wardfe6462c2000-04-04 01:40:52 +0000830
831 return cmd_obj
832
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000833 def _set_command_options(self, command_obj, option_dict=None):
Greg Wardc32d9a62000-05-28 23:53:06 +0000834 """Set the options for 'command_obj' from 'option_dict'. Basically
835 this means copying elements of a dictionary ('option_dict') to
836 attributes of an instance ('command').
837
Greg Wardceb9e222000-09-25 01:23:52 +0000838 'command_obj' must be a Command instance. If 'option_dict' is not
Greg Wardc32d9a62000-05-28 23:53:06 +0000839 supplied, uses the standard option dictionary for this command
840 (from 'self.command_options').
841 """
Greg Wardc32d9a62000-05-28 23:53:06 +0000842 command_name = command_obj.get_command_name()
843 if option_dict is None:
844 option_dict = self.get_option_dict(command_name)
845
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000846 if DEBUG:
847 self.announce(" setting options for '%s' command:" % command_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000848 for (option, (source, value)) in option_dict.items():
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000849 if DEBUG:
850 self.announce(" %s = %s (from %s)" % (option, value,
851 source))
Greg Wardceb9e222000-09-25 01:23:52 +0000852 try:
Greg Ward2f2b6c62000-09-25 01:58:07 +0000853 bool_opts = map(translate_longopt, command_obj.boolean_options)
Greg Wardceb9e222000-09-25 01:23:52 +0000854 except AttributeError:
855 bool_opts = []
856 try:
857 neg_opt = command_obj.negative_opt
858 except AttributeError:
859 neg_opt = {}
860
861 try:
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000862 is_string = isinstance(value, str)
Guido van Rossum8bc09652008-02-21 18:18:37 +0000863 if option in neg_opt and is_string:
Greg Wardceb9e222000-09-25 01:23:52 +0000864 setattr(command_obj, neg_opt[option], not strtobool(value))
Greg Ward2c08cf02000-09-27 00:15:37 +0000865 elif option in bool_opts and is_string:
Greg Wardceb9e222000-09-25 01:23:52 +0000866 setattr(command_obj, option, strtobool(value))
867 elif hasattr(command_obj, option):
868 setattr(command_obj, option, value)
869 else:
870 raise DistutilsOptionError, \
871 ("error in %s: command '%s' has no such option '%s'"
872 % (source, command_name, option))
873 except ValueError, msg:
874 raise DistutilsOptionError, msg
Greg Wardc32d9a62000-05-28 23:53:06 +0000875
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000876 def reinitialize_command(self, command, reinit_subcommands=0):
Greg Wardc32d9a62000-05-28 23:53:06 +0000877 """Reinitializes a command to the state it was in when first
878 returned by 'get_command_obj()': ie., initialized but not yet
Greg Ward7d9c7052000-06-28 01:25:27 +0000879 finalized. This provides the opportunity to sneak option
Greg Wardc32d9a62000-05-28 23:53:06 +0000880 values in programmatically, overriding or supplementing
881 user-supplied values from the config files and command line.
882 You'll have to re-finalize the command object (by calling
883 'finalize_options()' or 'ensure_finalized()') before using it for
Fred Drakeb94b8492001-12-06 20:51:35 +0000884 real.
Greg Wardc32d9a62000-05-28 23:53:06 +0000885
Greg Wardf449ea52000-09-16 15:23:28 +0000886 'command' should be a command name (string) or command object. If
887 'reinit_subcommands' is true, also reinitializes the command's
888 sub-commands, as declared by the 'sub_commands' class attribute (if
889 it has one). See the "install" command for an example. Only
890 reinitializes the sub-commands that actually matter, ie. those
891 whose test predicates return true.
892
Greg Wardc32d9a62000-05-28 23:53:06 +0000893 Returns the reinitialized command object.
894 """
895 from distutils.cmd import Command
896 if not isinstance(command, Command):
897 command_name = command
898 command = self.get_command_obj(command_name)
899 else:
900 command_name = command.get_command_name()
901
902 if not command.finalized:
Greg Ward282c7a02000-06-01 01:09:47 +0000903 return command
Greg Wardc32d9a62000-05-28 23:53:06 +0000904 command.initialize_options()
905 command.finalized = 0
Greg Ward43955c92000-06-06 02:52:36 +0000906 self.have_run[command_name] = 0
Greg Wardc32d9a62000-05-28 23:53:06 +0000907 self._set_command_options(command)
Greg Wardf449ea52000-09-16 15:23:28 +0000908
Greg Wardf449ea52000-09-16 15:23:28 +0000909 if reinit_subcommands:
Greg Wardf449ea52000-09-16 15:23:28 +0000910 for sub in command.get_sub_commands():
Fred Drakeb94b8492001-12-06 20:51:35 +0000911 self.reinitialize_command(sub, reinit_subcommands)
Greg Wardf449ea52000-09-16 15:23:28 +0000912
Greg Wardc32d9a62000-05-28 23:53:06 +0000913 return command
914
Greg Wardfe6462c2000-04-04 01:40:52 +0000915 # -- Methods that operate on the Distribution ----------------------
916
Tarek Ziadé63f17382009-07-04 02:02:41 +0000917 def announce(self, msg, level=log.INFO):
918 log.log(level, msg)
Greg Wardfe6462c2000-04-04 01:40:52 +0000919
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000920 def run_commands(self):
Greg Ward82715e12000-04-21 02:28:14 +0000921 """Run each command that was seen on the setup script command line.
Greg Wardd5d8a992000-05-23 01:42:17 +0000922 Uses the list of commands found and cache of command objects
Greg Wardfd7b91e2000-09-26 01:52:25 +0000923 created by 'get_command_obj()'.
924 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000925 for cmd in self.commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000926 self.run_command(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000927
Greg Wardfe6462c2000-04-04 01:40:52 +0000928 # -- Methods that operate on its Commands --------------------------
929
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000930 def run_command(self, command):
Greg Wardfe6462c2000-04-04 01:40:52 +0000931 """Do whatever it takes to run a command (including nothing at all,
Greg Wardd5d8a992000-05-23 01:42:17 +0000932 if the command has already been run). Specifically: if we have
933 already created and run the command named by 'command', return
934 silently without doing anything. If the command named by 'command'
935 doesn't even have a command object yet, create one. Then invoke
936 'run()' on that command object (or an existing one).
937 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000938 # Already been here, done that? then return silently.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000939 if self.have_run.get(command):
Greg Wardfe6462c2000-04-04 01:40:52 +0000940 return
941
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000942 log.info("running %s", command)
Greg Wardfd7b91e2000-09-26 01:52:25 +0000943 cmd_obj = self.get_command_obj(command)
944 cmd_obj.ensure_finalized()
945 cmd_obj.run()
Greg Wardfe6462c2000-04-04 01:40:52 +0000946 self.have_run[command] = 1
947
948
Greg Wardfe6462c2000-04-04 01:40:52 +0000949 # -- Distribution query methods ------------------------------------
950
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000951 def has_pure_modules(self):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000952 return len(self.packages or self.py_modules or []) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000953
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000954 def has_ext_modules(self):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000955 return self.ext_modules and len(self.ext_modules) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000956
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000957 def has_c_libraries(self):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000958 return self.libraries and len(self.libraries) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000959
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000960 def has_modules(self):
Greg Wardfe6462c2000-04-04 01:40:52 +0000961 return self.has_pure_modules() or self.has_ext_modules()
962
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000963 def has_headers(self):
Greg Ward51def7d2000-05-27 01:36:14 +0000964 return self.headers and len(self.headers) > 0
965
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000966 def has_scripts(self):
Greg Ward44a61bb2000-05-20 15:06:48 +0000967 return self.scripts and len(self.scripts) > 0
968
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000969 def has_data_files(self):
Greg Ward44a61bb2000-05-20 15:06:48 +0000970 return self.data_files and len(self.data_files) > 0
971
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000972 def is_pure(self):
Greg Wardfe6462c2000-04-04 01:40:52 +0000973 return (self.has_pure_modules() and
974 not self.has_ext_modules() and
975 not self.has_c_libraries())
976
Greg Ward82715e12000-04-21 02:28:14 +0000977 # -- Metadata query methods ----------------------------------------
978
979 # If you're looking for 'get_name()', 'get_version()', and so forth,
980 # they are defined in a sneaky way: the constructor binds self.get_XXX
981 # to self.metadata.get_XXX. The actual code is in the
982 # DistributionMetadata class, below.
983
Greg Ward82715e12000-04-21 02:28:14 +0000984class DistributionMetadata:
985 """Dummy class to hold the distribution meta-data: name, version,
Greg Wardfd7b91e2000-09-26 01:52:25 +0000986 author, and so forth.
987 """
Greg Ward82715e12000-04-21 02:28:14 +0000988
Neil Schemenauera8aefe52001-09-03 15:47:21 +0000989 _METHOD_BASENAMES = ("name", "version", "author", "author_email",
990 "maintainer", "maintainer_email", "url",
991 "license", "description", "long_description",
992 "keywords", "platforms", "fullname", "contact",
Andrew M. Kuchlinga52b8522003-03-03 20:07:27 +0000993 "contact_email", "license", "classifiers",
Fred Drakedb7b0022005-03-20 22:19:47 +0000994 "download_url",
995 # PEP 314
996 "provides", "requires", "obsoletes",
997 )
Neil Schemenauera8aefe52001-09-03 15:47:21 +0000998
Greg Ward82715e12000-04-21 02:28:14 +0000999 def __init__ (self):
1000 self.name = None
1001 self.version = None
1002 self.author = None
1003 self.author_email = None
1004 self.maintainer = None
1005 self.maintainer_email = None
1006 self.url = None
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +00001007 self.license = None
Greg Ward82715e12000-04-21 02:28:14 +00001008 self.description = None
Greg Warde5a584e2000-04-26 02:26:55 +00001009 self.long_description = None
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001010 self.keywords = None
1011 self.platforms = None
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +00001012 self.classifiers = None
Andrew M. Kuchling188d85f2003-02-19 14:16:01 +00001013 self.download_url = None
Fred Drakedb7b0022005-03-20 22:19:47 +00001014 # PEP 314
1015 self.provides = None
1016 self.requires = None
1017 self.obsoletes = None
Fred Drakeb94b8492001-12-06 20:51:35 +00001018
Tarek Ziadéae6acfc2009-05-16 18:29:40 +00001019 def write_pkg_info(self, base_dir):
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001020 """Write the PKG-INFO file into the release tree.
1021 """
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001022 pkg_info = open( os.path.join(base_dir, 'PKG-INFO'), 'w')
Fred Drakedb7b0022005-03-20 22:19:47 +00001023 self.write_pkg_file(pkg_info)
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001024 pkg_info.close()
Fred Drakeb94b8492001-12-06 20:51:35 +00001025
Tarek Ziadéae6acfc2009-05-16 18:29:40 +00001026 def write_pkg_file(self, file):
Fred Drakedb7b0022005-03-20 22:19:47 +00001027 """Write the PKG-INFO format data to a file object.
1028 """
1029 version = '1.0'
1030 if self.provides or self.requires or self.obsoletes:
1031 version = '1.1'
1032
Marc-André Lemburgb339b2a2008-09-03 11:13:56 +00001033 self._write_field(file, 'Metadata-Version', version)
1034 self._write_field(file, 'Name', self.get_name())
1035 self._write_field(file, 'Version', self.get_version())
1036 self._write_field(file, 'Summary', self.get_description())
1037 self._write_field(file, 'Home-page', self.get_url())
1038 self._write_field(file, 'Author', self.get_contact())
1039 self._write_field(file, 'Author-email', self.get_contact_email())
1040 self._write_field(file, 'License', self.get_license())
Fred Drakedb7b0022005-03-20 22:19:47 +00001041 if self.download_url:
Marc-André Lemburgb339b2a2008-09-03 11:13:56 +00001042 self._write_field(file, 'Download-URL', self.download_url)
Fred Drakedb7b0022005-03-20 22:19:47 +00001043
Tarek Ziadéc01cbc42009-06-01 22:22:13 +00001044 long_desc = rfc822_escape(self.get_long_description())
Marc-André Lemburgb339b2a2008-09-03 11:13:56 +00001045 self._write_field(file, 'Description', long_desc)
Fred Drakedb7b0022005-03-20 22:19:47 +00001046
Tarek Ziadéc01cbc42009-06-01 22:22:13 +00001047 keywords = ','.join(self.get_keywords())
Fred Drakedb7b0022005-03-20 22:19:47 +00001048 if keywords:
Marc-André Lemburgb339b2a2008-09-03 11:13:56 +00001049 self._write_field(file, 'Keywords', keywords)
Fred Drakedb7b0022005-03-20 22:19:47 +00001050
1051 self._write_list(file, 'Platform', self.get_platforms())
1052 self._write_list(file, 'Classifier', self.get_classifiers())
1053
1054 # PEP 314
1055 self._write_list(file, 'Requires', self.get_requires())
1056 self._write_list(file, 'Provides', self.get_provides())
1057 self._write_list(file, 'Obsoletes', self.get_obsoletes())
1058
Marc-André Lemburgb339b2a2008-09-03 11:13:56 +00001059 def _write_field(self, file, name, value):
Marc-André Lemburgb339b2a2008-09-03 11:13:56 +00001060 if isinstance(value, unicode):
1061 value = value.encode(PKG_INFO_ENCODING)
1062 else:
1063 value = str(value)
1064 file.write('%s: %s\n' % (name, value))
1065
Fred Drakedb7b0022005-03-20 22:19:47 +00001066 def _write_list (self, file, name, values):
1067 for value in values:
Marc-André Lemburgb339b2a2008-09-03 11:13:56 +00001068 self._write_field(file, name, value)
Fred Drakedb7b0022005-03-20 22:19:47 +00001069
Greg Ward82715e12000-04-21 02:28:14 +00001070 # -- Metadata query methods ----------------------------------------
1071
Tarek Ziadéae6acfc2009-05-16 18:29:40 +00001072 def get_name(self):
Greg Wardfe6462c2000-04-04 01:40:52 +00001073 return self.name or "UNKNOWN"
1074
Greg Ward82715e12000-04-21 02:28:14 +00001075 def get_version(self):
Thomas Hellerbcd89752001-12-06 20:44:19 +00001076 return self.version or "0.0.0"
Greg Wardfe6462c2000-04-04 01:40:52 +00001077
Tarek Ziadéae6acfc2009-05-16 18:29:40 +00001078 def get_fullname(self):
Greg Ward82715e12000-04-21 02:28:14 +00001079 return "%s-%s" % (self.get_name(), self.get_version())
1080
1081 def get_author(self):
1082 return self.author or "UNKNOWN"
1083
1084 def get_author_email(self):
1085 return self.author_email or "UNKNOWN"
1086
1087 def get_maintainer(self):
1088 return self.maintainer or "UNKNOWN"
1089
1090 def get_maintainer_email(self):
1091 return self.maintainer_email or "UNKNOWN"
1092
1093 def get_contact(self):
Tarek Ziadéae6acfc2009-05-16 18:29:40 +00001094 return self.maintainer or self.author or "UNKNOWN"
Greg Ward82715e12000-04-21 02:28:14 +00001095
1096 def get_contact_email(self):
Tarek Ziadéae6acfc2009-05-16 18:29:40 +00001097 return self.maintainer_email or self.author_email or "UNKNOWN"
Greg Ward82715e12000-04-21 02:28:14 +00001098
1099 def get_url(self):
1100 return self.url or "UNKNOWN"
1101
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +00001102 def get_license(self):
1103 return self.license or "UNKNOWN"
1104 get_licence = get_license
Fred Drakeb94b8492001-12-06 20:51:35 +00001105
Greg Ward82715e12000-04-21 02:28:14 +00001106 def get_description(self):
1107 return self.description or "UNKNOWN"
Greg Warde5a584e2000-04-26 02:26:55 +00001108
1109 def get_long_description(self):
1110 return self.long_description or "UNKNOWN"
1111
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001112 def get_keywords(self):
1113 return self.keywords or []
1114
1115 def get_platforms(self):
1116 return self.platforms or ["UNKNOWN"]
1117
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +00001118 def get_classifiers(self):
1119 return self.classifiers or []
1120
Andrew M. Kuchling188d85f2003-02-19 14:16:01 +00001121 def get_download_url(self):
1122 return self.download_url or "UNKNOWN"
1123
Fred Drakedb7b0022005-03-20 22:19:47 +00001124 # PEP 314
Fred Drakedb7b0022005-03-20 22:19:47 +00001125 def get_requires(self):
1126 return self.requires or []
1127
1128 def set_requires(self, value):
1129 import distutils.versionpredicate
1130 for v in value:
1131 distutils.versionpredicate.VersionPredicate(v)
1132 self.requires = value
1133
1134 def get_provides(self):
1135 return self.provides or []
1136
1137 def set_provides(self, value):
1138 value = [v.strip() for v in value]
1139 for v in value:
1140 import distutils.versionpredicate
Fred Drake227e8ff2005-03-21 06:36:32 +00001141 distutils.versionpredicate.split_provision(v)
Fred Drakedb7b0022005-03-20 22:19:47 +00001142 self.provides = value
1143
1144 def get_obsoletes(self):
1145 return self.obsoletes or []
1146
1147 def set_obsoletes(self, value):
1148 import distutils.versionpredicate
1149 for v in value:
1150 distutils.versionpredicate.VersionPredicate(v)
1151 self.obsoletes = value
1152
Tarek Ziadéae6acfc2009-05-16 18:29:40 +00001153def fix_help_options(options):
Greg Ward2ff78872000-06-24 00:23:20 +00001154 """Convert a 4-tuple 'help_options' list as found in various command
1155 classes to the 3-tuple form required by FancyGetopt.
1156 """
1157 new_options = []
1158 for help_tuple in options:
1159 new_options.append(help_tuple[0:3])
1160 return new_options