blob: 8dc64d43dae5ffa0aa8a7ff21b65d6e2879ab812 [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"),
Tarek Ziadé40b998b2009-10-27 23:06:10 +000059 ('no-user-cfg', None,
60 'ignore pydistutils.cfg in your home directory'),
61 ]
Greg Ward82715e12000-04-21 02:28:14 +000062
Martin v. Löwis8ed338a2005-03-03 08:12:27 +000063 # 'common_usage' is a short (2-3 line) string describing the common
64 # usage of the setup script.
65 common_usage = """\
66Common commands: (see '--help-commands' for more)
67
68 setup.py build will build the package underneath 'build/'
69 setup.py install will install the package
70"""
71
Greg Ward82715e12000-04-21 02:28:14 +000072 # options that are not propagated to the commands
73 display_options = [
74 ('help-commands', None,
75 "list all available commands"),
76 ('name', None,
77 "print package name"),
78 ('version', 'V',
79 "print package version"),
80 ('fullname', None,
81 "print <package name>-<version>"),
82 ('author', None,
83 "print the author's name"),
84 ('author-email', None,
85 "print the author's email address"),
86 ('maintainer', None,
87 "print the maintainer's name"),
88 ('maintainer-email', None,
89 "print the maintainer's email address"),
90 ('contact', None,
Greg Wardd5d8a992000-05-23 01:42:17 +000091 "print the maintainer's name if known, else the author's"),
Greg Ward82715e12000-04-21 02:28:14 +000092 ('contact-email', None,
Greg Wardd5d8a992000-05-23 01:42:17 +000093 "print the maintainer's email address if known, else the author's"),
Greg Ward82715e12000-04-21 02:28:14 +000094 ('url', None,
95 "print the URL for this package"),
Greg Ward82715e12000-04-21 02:28:14 +000096 ('license', None,
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +000097 "print the license of the package"),
98 ('licence', None,
99 "alias for --license"),
Greg Ward82715e12000-04-21 02:28:14 +0000100 ('description', None,
101 "print the package description"),
Greg Warde5a584e2000-04-26 02:26:55 +0000102 ('long-description', None,
103 "print the long package description"),
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000104 ('platforms', None,
105 "print the list of platforms"),
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +0000106 ('classifiers', None,
107 "print the list of classifiers"),
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000108 ('keywords', None,
109 "print the list of keywords"),
Fred Drakedb7b0022005-03-20 22:19:47 +0000110 ('provides', None,
111 "print the list of packages/modules provided"),
112 ('requires', None,
113 "print the list of packages/modules required"),
114 ('obsoletes', None,
115 "print the list of packages/modules made obsolete")
Greg Ward82715e12000-04-21 02:28:14 +0000116 ]
Greg Ward2f2b6c62000-09-25 01:58:07 +0000117 display_option_names = map(lambda x: translate_longopt(x[0]),
118 display_options)
Greg Ward82715e12000-04-21 02:28:14 +0000119
120 # negative options are options that exclude other options
Greg Wardfe6462c2000-04-04 01:40:52 +0000121 negative_opt = {'quiet': 'verbose'}
122
123
124 # -- Creation/initialization methods -------------------------------
Fred Drakeb94b8492001-12-06 20:51:35 +0000125
Greg Wardfe6462c2000-04-04 01:40:52 +0000126 def __init__ (self, attrs=None):
127 """Construct a new Distribution instance: initialize all the
Greg Ward8ff5a3f2000-06-02 00:44:53 +0000128 attributes of a Distribution, and then use 'attrs' (a dictionary
129 mapping attribute names to values) to assign some of those
130 attributes their "real" values. (Any attributes not mentioned in
131 'attrs' will be assigned to some null value: 0, None, an empty list
132 or dictionary, etc.) Most importantly, initialize the
133 'command_obj' attribute to the empty dictionary; this will be
134 filled in with real command objects by 'parse_command_line()'.
135 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000136
137 # Default values for our command-line options
138 self.verbose = 1
139 self.dry_run = 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000140 self.help = 0
Greg Ward82715e12000-04-21 02:28:14 +0000141 for attr in self.display_option_names:
142 setattr(self, attr, 0)
Greg Wardfe6462c2000-04-04 01:40:52 +0000143
Greg Ward82715e12000-04-21 02:28:14 +0000144 # Store the distribution meta-data (name, version, author, and so
145 # forth) in a separate object -- we're getting to have enough
146 # information here (and enough command-line options) that it's
147 # worth it. Also delegate 'get_XXX()' methods to the 'metadata'
148 # object in a sneaky and underhanded (but efficient!) way.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000149 self.metadata = DistributionMetadata()
Neil Schemenauera8aefe52001-09-03 15:47:21 +0000150 for basename in self.metadata._METHOD_BASENAMES:
Greg Ward4982f982000-04-22 02:52:44 +0000151 method_name = "get_" + basename
152 setattr(self, method_name, getattr(self.metadata, method_name))
Greg Wardfe6462c2000-04-04 01:40:52 +0000153
154 # 'cmdclass' maps command names to class objects, so we
155 # can 1) quickly figure out which class to instantiate when
156 # we need to create a new command object, and 2) have a way
Greg Ward82715e12000-04-21 02:28:14 +0000157 # for the setup script to override command classes
Greg Wardfe6462c2000-04-04 01:40:52 +0000158 self.cmdclass = {}
159
Fred Draked04573f2004-08-03 16:37:40 +0000160 # 'command_packages' is a list of packages in which commands
161 # are searched for. The factory for command 'foo' is expected
162 # to be named 'foo' in the module 'foo' in one of the packages
163 # named here. This list is searched from the left; an error
164 # is raised if no named package provides the command being
165 # searched for. (Always access using get_command_packages().)
166 self.command_packages = None
167
Greg Ward9821bf42000-08-29 01:15:18 +0000168 # 'script_name' and 'script_args' are usually set to sys.argv[0]
169 # and sys.argv[1:], but they can be overridden when the caller is
170 # not necessarily a setup script run from the command-line.
171 self.script_name = None
172 self.script_args = None
173
Greg Wardd5d8a992000-05-23 01:42:17 +0000174 # 'command_options' is where we store command options between
175 # parsing them (from config files, the command-line, etc.) and when
176 # they are actually needed -- ie. when the command in question is
177 # instantiated. It is a dictionary of dictionaries of 2-tuples:
178 # command_options = { command_name : { option : (source, value) } }
Gregory P. Smith14263542000-05-12 00:41:33 +0000179 self.command_options = {}
180
Martin v. Löwis98da5622005-03-23 18:54:36 +0000181 # 'dist_files' is the list of (command, pyversion, file) that
182 # have been created by any dist commands run so far. This is
183 # filled regardless of whether the run is dry or not. pyversion
184 # gives sysconfig.get_python_version() if the dist file is
185 # specific to a Python version, 'any' if it is good for all
186 # Python versions on the target platform, and '' for a source
187 # file. pyversion should not be used to specify minimum or
188 # maximum required Python versions; use the metainfo for that
189 # instead.
Martin v. Löwis55f1bb82005-03-21 20:56:35 +0000190 self.dist_files = []
191
Greg Wardfe6462c2000-04-04 01:40:52 +0000192 # These options are really the business of various commands, rather
193 # than of the Distribution itself. We provide aliases for them in
194 # Distribution as a convenience to the developer.
Greg Wardfe6462c2000-04-04 01:40:52 +0000195 self.packages = None
Fred Drake0eb32a62004-06-11 21:50:33 +0000196 self.package_data = {}
Greg Wardfe6462c2000-04-04 01:40:52 +0000197 self.package_dir = None
198 self.py_modules = None
199 self.libraries = None
Greg Ward51def7d2000-05-27 01:36:14 +0000200 self.headers = None
Greg Wardfe6462c2000-04-04 01:40:52 +0000201 self.ext_modules = None
202 self.ext_package = None
203 self.include_dirs = None
204 self.extra_path = None
Gregory P. Smithb2e3bb32000-05-12 00:52:23 +0000205 self.scripts = None
Gregory P. Smith6a901dd2000-05-13 03:09:50 +0000206 self.data_files = None
Tarek Ziadé1a240fb2009-01-08 23:56:31 +0000207 self.password = ''
Greg Wardfe6462c2000-04-04 01:40:52 +0000208
209 # And now initialize bookkeeping stuff that can't be supplied by
210 # the caller at all. 'command_obj' maps command names to
211 # Command instances -- that's how we enforce that every command
212 # class is a singleton.
213 self.command_obj = {}
214
215 # 'have_run' maps command names to boolean values; it keeps track
216 # of whether we have actually run a particular command, to make it
217 # cheap to "run" a command whenever we think we might need to -- if
218 # it's already been done, no need for expensive filesystem
219 # operations, we just check the 'have_run' dictionary and carry on.
220 # It's only safe to query 'have_run' for a command class that has
221 # been instantiated -- a false value will be inserted when the
222 # command object is created, and replaced with a true value when
Greg Ward612eb9f2000-07-27 02:13:20 +0000223 # the command is successfully run. Thus it's probably best to use
Greg Wardfe6462c2000-04-04 01:40:52 +0000224 # '.get()' rather than a straight lookup.
225 self.have_run = {}
226
227 # Now we'll use the attrs dictionary (ultimately, keyword args from
Greg Ward82715e12000-04-21 02:28:14 +0000228 # the setup script) to possibly override any or all of these
229 # distribution options.
230
Greg Wardfe6462c2000-04-04 01:40:52 +0000231 if attrs:
Greg Wardfe6462c2000-04-04 01:40:52 +0000232 # Pull out the set of command options and work on them
233 # specifically. Note that this order guarantees that aliased
234 # command options will override any supplied redundantly
235 # through the general options dictionary.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000236 options = attrs.get('options')
Tarek Ziadéc13acb12008-12-29 22:23:53 +0000237 if options is not None:
Greg Wardfe6462c2000-04-04 01:40:52 +0000238 del attrs['options']
239 for (command, cmd_options) in options.items():
Greg Ward0e48cfd2000-05-26 01:00:15 +0000240 opt_dict = self.get_option_dict(command)
241 for (opt, val) in cmd_options.items():
242 opt_dict[opt] = ("setup script", val)
Greg Wardfe6462c2000-04-04 01:40:52 +0000243
Guido van Rossum8bc09652008-02-21 18:18:37 +0000244 if 'licence' in attrs:
Andrew M. Kuchlinga52b8522003-03-03 20:07:27 +0000245 attrs['license'] = attrs['licence']
246 del attrs['licence']
247 msg = "'licence' distribution option is deprecated; use 'license'"
248 if warnings is not None:
249 warnings.warn(msg)
250 else:
251 sys.stderr.write(msg + "\n")
252
Greg Wardfe6462c2000-04-04 01:40:52 +0000253 # Now work on the rest of the attributes. Any attribute that's
254 # not already defined is invalid!
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000255 for (key, val) in attrs.items():
Fred Drakedb7b0022005-03-20 22:19:47 +0000256 if hasattr(self.metadata, "set_" + key):
257 getattr(self.metadata, "set_" + key)(val)
258 elif hasattr(self.metadata, key):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000259 setattr(self.metadata, key, val)
260 elif hasattr(self, key):
261 setattr(self, key, val)
Anthony Baxter73cc8472004-10-13 13:22:34 +0000262 else:
Andrew M. Kuchlingff4ad9a2002-10-31 13:22:41 +0000263 msg = "Unknown distribution option: %s" % repr(key)
264 if warnings is not None:
265 warnings.warn(msg)
266 else:
267 sys.stderr.write(msg + "\n")
Greg Wardfe6462c2000-04-04 01:40:52 +0000268
Tarek Ziadé40b998b2009-10-27 23:06:10 +0000269 # no-user-cfg is handled before other command line args
270 # because other args override the config files, and this
271 # one is needed before we can load the config files.
272 # If attrs['script_args'] wasn't passed, assume false.
273 #
274 # This also make sure we just look at the global options
275 self.want_user_cfg = True
276
277 if self.script_args is not None:
278 for arg in self.script_args:
279 if not arg.startswith('-'):
280 break
281 if arg == '--no-user-cfg':
282 self.want_user_cfg = False
283 break
284
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000285 self.finalize_options()
Fred Drakeb94b8492001-12-06 20:51:35 +0000286
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000287 def get_option_dict(self, command):
Greg Ward0e48cfd2000-05-26 01:00:15 +0000288 """Get the option dictionary for a given command. If that
289 command's option dictionary hasn't been created yet, then create it
290 and return the new dictionary; otherwise, return the existing
291 option dictionary.
292 """
Greg Ward0e48cfd2000-05-26 01:00:15 +0000293 dict = self.command_options.get(command)
294 if dict is None:
295 dict = self.command_options[command] = {}
296 return dict
297
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000298 def dump_option_dicts(self, header=None, commands=None, indent=""):
Greg Wardc32d9a62000-05-28 23:53:06 +0000299 from pprint import pformat
300
301 if commands is None: # dump all command option dicts
302 commands = self.command_options.keys()
303 commands.sort()
304
305 if header is not None:
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000306 self.announce(indent + header)
Greg Wardc32d9a62000-05-28 23:53:06 +0000307 indent = indent + " "
308
309 if not commands:
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000310 self.announce(indent + "no commands known yet")
Greg Wardc32d9a62000-05-28 23:53:06 +0000311 return
312
313 for cmd_name in commands:
314 opt_dict = self.command_options.get(cmd_name)
315 if opt_dict is None:
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000316 self.announce(indent +
317 "no option dict for '%s' command" % cmd_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000318 else:
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000319 self.announce(indent +
320 "option dict for '%s' command:" % cmd_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000321 out = pformat(opt_dict)
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000322 for line in out.split('\n'):
323 self.announce(indent + " " + line)
Greg Wardc32d9a62000-05-28 23:53:06 +0000324
Greg Wardd5d8a992000-05-23 01:42:17 +0000325 # -- Config file finding/parsing methods ---------------------------
326
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000327 def find_config_files(self):
Gregory P. Smith14263542000-05-12 00:41:33 +0000328 """Find as many configuration files as should be processed for this
329 platform, and return a list of filenames in the order in which they
330 should be parsed. The filenames returned are guaranteed to exist
331 (modulo nasty race conditions).
332
Andrew M. Kuchlingd303b612001-12-06 16:32:05 +0000333 There are three possible config files: distutils.cfg in the
334 Distutils installation directory (ie. where the top-level
335 Distutils __inst__.py file lives), a file in the user's home
336 directory named .pydistutils.cfg on Unix and pydistutils.cfg
Tarek Ziadé40b998b2009-10-27 23:06:10 +0000337 on Windows/Mac; and setup.cfg in the current directory.
338
339 The file in the user's home directory can be disabled with the
340 --no-user-cfg option.
Greg Wardd5d8a992000-05-23 01:42:17 +0000341 """
Gregory P. Smith14263542000-05-12 00:41:33 +0000342 files = []
Greg Wardacf3f6a2000-06-07 02:26:19 +0000343 check_environ()
Gregory P. Smith14263542000-05-12 00:41:33 +0000344
Greg Ward11696872000-06-07 02:29:03 +0000345 # Where to look for the system-wide Distutils config file
346 sys_dir = os.path.dirname(sys.modules['distutils'].__file__)
347
348 # Look for the system config file
349 sys_file = os.path.join(sys_dir, "distutils.cfg")
Greg Wardacf3f6a2000-06-07 02:26:19 +0000350 if os.path.isfile(sys_file):
351 files.append(sys_file)
Gregory P. Smith14263542000-05-12 00:41:33 +0000352
Greg Ward11696872000-06-07 02:29:03 +0000353 # What to call the per-user config file
354 if os.name == 'posix':
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000355 user_filename = ".pydistutils.cfg"
356 else:
357 user_filename = "pydistutils.cfg"
Greg Wardfa9ff762000-10-14 04:06:40 +0000358
Greg Ward11696872000-06-07 02:29:03 +0000359 # And look for the user config file
Tarek Ziadé40b998b2009-10-27 23:06:10 +0000360 if self.want_user_cfg:
361 user_file = os.path.join(os.path.expanduser('~'), user_filename)
362 if os.path.isfile(user_file):
363 files.append(user_file)
Gregory P. Smith14263542000-05-12 00:41:33 +0000364
Gregory P. Smith14263542000-05-12 00:41:33 +0000365 # All platforms support local setup.cfg
366 local_file = "setup.cfg"
367 if os.path.isfile(local_file):
368 files.append(local_file)
369
Tarek Ziadé40b998b2009-10-27 23:06:10 +0000370 if DEBUG:
371 self.announce("using config files: %s" % ', '.join(files))
372
Gregory P. Smith14263542000-05-12 00:41:33 +0000373 return files
374
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000375 def parse_config_files(self, filenames=None):
Georg Brandl392c6fc2008-05-25 07:25:25 +0000376 from ConfigParser import ConfigParser
Gregory P. Smith14263542000-05-12 00:41:33 +0000377
378 if filenames is None:
379 filenames = self.find_config_files()
380
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000381 if DEBUG:
382 self.announce("Distribution.parse_config_files():")
Greg Ward47460772000-05-23 03:47:35 +0000383
Gregory P. Smith14263542000-05-12 00:41:33 +0000384 parser = ConfigParser()
Greg Wardd5d8a992000-05-23 01:42:17 +0000385 for filename in filenames:
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000386 if DEBUG:
Tarek Ziadé99773352009-09-21 13:41:08 +0000387 self.announce(" reading %s" % filename)
Greg Wardd5d8a992000-05-23 01:42:17 +0000388 parser.read(filename)
389 for section in parser.sections():
390 options = parser.options(section)
Greg Ward0e48cfd2000-05-26 01:00:15 +0000391 opt_dict = self.get_option_dict(section)
Gregory P. Smith14263542000-05-12 00:41:33 +0000392
Greg Wardd5d8a992000-05-23 01:42:17 +0000393 for opt in options:
394 if opt != '__name__':
Greg Wardceb9e222000-09-25 01:23:52 +0000395 val = parser.get(section,opt)
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000396 opt = opt.replace('-', '_')
Greg Wardceb9e222000-09-25 01:23:52 +0000397 opt_dict[opt] = (filename, val)
Gregory P. Smith14263542000-05-12 00:41:33 +0000398
Greg Ward47460772000-05-23 03:47:35 +0000399 # Make the ConfigParser forget everything (so we retain
Fred Drakef06116d2004-02-17 22:35:19 +0000400 # the original filenames that options come from)
Greg Ward47460772000-05-23 03:47:35 +0000401 parser.__init__()
Gregory P. Smith14263542000-05-12 00:41:33 +0000402
Greg Wardceb9e222000-09-25 01:23:52 +0000403 # If there was a "global" section in the config file, use it
404 # to set Distribution options.
405
Guido van Rossum8bc09652008-02-21 18:18:37 +0000406 if 'global' in self.command_options:
Greg Wardceb9e222000-09-25 01:23:52 +0000407 for (opt, (src, val)) in self.command_options['global'].items():
408 alias = self.negative_opt.get(opt)
409 try:
410 if alias:
411 setattr(self, alias, not strtobool(val))
412 elif opt in ('verbose', 'dry_run'): # ugh!
413 setattr(self, opt, strtobool(val))
Fred Draked04573f2004-08-03 16:37:40 +0000414 else:
415 setattr(self, opt, val)
Greg Wardceb9e222000-09-25 01:23:52 +0000416 except ValueError, msg:
417 raise DistutilsOptionError, msg
418
Greg Wardd5d8a992000-05-23 01:42:17 +0000419 # -- Command-line parsing methods ----------------------------------
420
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000421 def parse_command_line(self):
Greg Ward9821bf42000-08-29 01:15:18 +0000422 """Parse the setup script's command line, taken from the
423 'script_args' instance attribute (which defaults to 'sys.argv[1:]'
424 -- see 'setup()' in core.py). This list is first processed for
425 "global options" -- options that set attributes of the Distribution
426 instance. Then, it is alternately scanned for Distutils commands
427 and options for that command. Each new command terminates the
428 options for the previous command. The allowed options for a
429 command are determined by the 'user_options' attribute of the
430 command class -- thus, we have to be able to load command classes
431 in order to parse the command line. Any error in that 'options'
432 attribute raises DistutilsGetoptError; any error on the
433 command-line raises DistutilsArgError. If no Distutils commands
434 were found on the command line, raises DistutilsArgError. Return
Greg Wardceb9e222000-09-25 01:23:52 +0000435 true if command-line was successfully parsed and we should carry
Greg Ward9821bf42000-08-29 01:15:18 +0000436 on with executing commands; false if no errors but we shouldn't
437 execute commands (currently, this only happens if user asks for
438 help).
Greg Wardd5d8a992000-05-23 01:42:17 +0000439 """
Andrew M. Kuchling3f819ec2001-01-15 16:09:35 +0000440 #
Fred Drake981a1782001-08-10 18:59:30 +0000441 # We now have enough information to show the Macintosh dialog
442 # that allows the user to interactively specify the "command line".
Andrew M. Kuchling3f819ec2001-01-15 16:09:35 +0000443 #
Fred Draked04573f2004-08-03 16:37:40 +0000444 toplevel_options = self._get_toplevel_options()
Fred Drakeb94b8492001-12-06 20:51:35 +0000445
Greg Wardfe6462c2000-04-04 01:40:52 +0000446 # We have to parse the command line a bit at a time -- global
447 # options, then the first command, then its options, and so on --
448 # because each command will be handled by a different class, and
Greg Wardd5d8a992000-05-23 01:42:17 +0000449 # the options that are valid for a particular class aren't known
450 # until we have loaded the command class, which doesn't happen
451 # until we know what the command is.
Greg Wardfe6462c2000-04-04 01:40:52 +0000452
453 self.commands = []
Fred Draked04573f2004-08-03 16:37:40 +0000454 parser = FancyGetopt(toplevel_options + self.display_options)
Greg Wardfd7b91e2000-09-26 01:52:25 +0000455 parser.set_negative_aliases(self.negative_opt)
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +0000456 parser.set_aliases({'licence': 'license'})
Greg Wardfd7b91e2000-09-26 01:52:25 +0000457 args = parser.getopt(args=self.script_args, object=self)
Greg Ward82715e12000-04-21 02:28:14 +0000458 option_order = parser.get_option_order()
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000459 log.set_verbosity(self.verbose)
Greg Wardfe6462c2000-04-04 01:40:52 +0000460
Greg Ward82715e12000-04-21 02:28:14 +0000461 # for display options we return immediately
462 if self.handle_display_options(option_order):
Greg Wardfe6462c2000-04-04 01:40:52 +0000463 return
Greg Wardfe6462c2000-04-04 01:40:52 +0000464 while args:
Greg Wardd5d8a992000-05-23 01:42:17 +0000465 args = self._parse_command_opts(parser, args)
466 if args is None: # user asked for help (and got it)
Greg Wardfe6462c2000-04-04 01:40:52 +0000467 return
Greg Wardfe6462c2000-04-04 01:40:52 +0000468
Greg Wardd5d8a992000-05-23 01:42:17 +0000469 # Handle the cases of --help as a "global" option, ie.
470 # "setup.py --help" and "setup.py --help command ...". For the
471 # former, we show global options (--verbose, --dry-run, etc.)
472 # and display-only options (--name, --version, etc.); for the
473 # latter, we omit the display-only options and show help for
474 # each command listed on the command line.
Greg Wardfe6462c2000-04-04 01:40:52 +0000475 if self.help:
Greg Wardd5d8a992000-05-23 01:42:17 +0000476 self._show_help(parser,
477 display_options=len(self.commands) == 0,
478 commands=self.commands)
Greg Wardfe6462c2000-04-04 01:40:52 +0000479 return
480
481 # Oops, no commands found -- an end-user error
482 if not self.commands:
483 raise DistutilsArgError, "no commands supplied"
484
485 # All is well: return true
486 return 1
487
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000488 def _get_toplevel_options(self):
Fred Draked04573f2004-08-03 16:37:40 +0000489 """Return the non-display options recognized at the top level.
490
491 This includes options that are recognized *only* at the top
492 level as well as options recognized for commands.
493 """
494 return self.global_options + [
495 ("command-packages=", None,
496 "list of packages that provide distutils commands"),
497 ]
498
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000499 def _parse_command_opts(self, parser, args):
Greg Wardd5d8a992000-05-23 01:42:17 +0000500 """Parse the command-line options for a single command.
501 'parser' must be a FancyGetopt instance; 'args' must be the list
502 of arguments, starting with the current command (whose options
503 we are about to parse). Returns a new version of 'args' with
504 the next command at the front of the list; will be the empty
505 list if there are no more commands on the command line. Returns
506 None if the user asked for help on this command.
507 """
508 # late import because of mutual dependence between these modules
509 from distutils.cmd import Command
510
511 # Pull the current command from the head of the command line
512 command = args[0]
Greg Wardfd7b91e2000-09-26 01:52:25 +0000513 if not command_re.match(command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000514 raise SystemExit, "invalid command name '%s'" % command
Greg Wardfd7b91e2000-09-26 01:52:25 +0000515 self.commands.append(command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000516
517 # Dig up the command class that implements this command, so we
518 # 1) know that it's a valid command, and 2) know which options
519 # it takes.
520 try:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000521 cmd_class = self.get_command_class(command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000522 except DistutilsModuleError, msg:
523 raise DistutilsArgError, msg
524
525 # Require that the command class be derived from Command -- want
526 # to be sure that the basic "command" interface is implemented.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000527 if not issubclass(cmd_class, Command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000528 raise DistutilsClassError, \
529 "command class %s must subclass Command" % cmd_class
530
531 # Also make sure that the command object provides a list of its
532 # known options.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000533 if not (hasattr(cmd_class, 'user_options') and
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000534 isinstance(cmd_class.user_options, list)):
Greg Wardd5d8a992000-05-23 01:42:17 +0000535 raise DistutilsClassError, \
536 ("command class %s must provide " +
537 "'user_options' attribute (a list of tuples)") % \
538 cmd_class
539
540 # If the command class has a list of negative alias options,
541 # merge it in with the global negative aliases.
542 negative_opt = self.negative_opt
Greg Wardfd7b91e2000-09-26 01:52:25 +0000543 if hasattr(cmd_class, 'negative_opt'):
Antoine Pitrouf5413782009-05-15 17:27:30 +0000544 negative_opt = negative_opt.copy()
Greg Wardfd7b91e2000-09-26 01:52:25 +0000545 negative_opt.update(cmd_class.negative_opt)
Greg Wardd5d8a992000-05-23 01:42:17 +0000546
Greg Wardfa9ff762000-10-14 04:06:40 +0000547 # Check for help_options in command class. They have a different
548 # format (tuple of four) so we need to preprocess them here.
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000549 if (hasattr(cmd_class, 'help_options') and
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000550 isinstance(cmd_class.help_options, list)):
Greg Ward2ff78872000-06-24 00:23:20 +0000551 help_options = fix_help_options(cmd_class.help_options)
552 else:
Greg Ward55fced32000-06-24 01:22:41 +0000553 help_options = []
Greg Ward2ff78872000-06-24 00:23:20 +0000554
Greg Ward9d17a7a2000-06-07 03:00:06 +0000555
Greg Wardd5d8a992000-05-23 01:42:17 +0000556 # All commands support the global options too, just by adding
557 # in 'global_options'.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000558 parser.set_option_table(self.global_options +
559 cmd_class.user_options +
560 help_options)
561 parser.set_negative_aliases(negative_opt)
562 (args, opts) = parser.getopt(args[1:])
Greg Ward47460772000-05-23 03:47:35 +0000563 if hasattr(opts, 'help') and opts.help:
Greg Wardd5d8a992000-05-23 01:42:17 +0000564 self._show_help(parser, display_options=0, commands=[cmd_class])
565 return
566
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000567 if (hasattr(cmd_class, 'help_options') and
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000568 isinstance(cmd_class.help_options, list)):
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000569 help_option_found=0
570 for (help_option, short, desc, func) in cmd_class.help_options:
571 if hasattr(opts, parser.get_attr_name(help_option)):
572 help_option_found=1
Benjamin Petersonde055992009-10-09 22:05:45 +0000573 if hasattr(func, '__call__'):
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000574 func()
Greg Ward55fced32000-06-24 01:22:41 +0000575 else:
Fred Drake981a1782001-08-10 18:59:30 +0000576 raise DistutilsClassError(
Walter Dörwald70a6b492004-02-12 17:35:32 +0000577 "invalid help function %r for help option '%s': "
Fred Drake981a1782001-08-10 18:59:30 +0000578 "must be a callable object (function, etc.)"
Walter Dörwald70a6b492004-02-12 17:35:32 +0000579 % (func, help_option))
Greg Ward55fced32000-06-24 01:22:41 +0000580
Fred Drakeb94b8492001-12-06 20:51:35 +0000581 if help_option_found:
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000582 return
Greg Ward9d17a7a2000-06-07 03:00:06 +0000583
Greg Wardd5d8a992000-05-23 01:42:17 +0000584 # Put the options from the command-line into their official
585 # holding pen, the 'command_options' dictionary.
Greg Ward0e48cfd2000-05-26 01:00:15 +0000586 opt_dict = self.get_option_dict(command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000587 for (name, value) in vars(opts).items():
Greg Ward0e48cfd2000-05-26 01:00:15 +0000588 opt_dict[name] = ("command line", value)
Greg Wardd5d8a992000-05-23 01:42:17 +0000589
590 return args
591
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000592 def finalize_options(self):
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000593 """Set final values for all the options on the Distribution
594 instance, analogous to the .finalize_options() method of Command
595 objects.
596 """
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000597 for attr in ('keywords', 'platforms'):
598 value = getattr(self.metadata, attr)
599 if value is None:
600 continue
601 if isinstance(value, str):
602 value = [elm.strip() for elm in value.split(',')]
603 setattr(self.metadata, attr, value)
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000604
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000605 def _show_help(self, parser, global_options=1, display_options=1,
606 commands=[]):
Greg Wardd5d8a992000-05-23 01:42:17 +0000607 """Show help for the setup script command-line in the form of
608 several lists of command-line options. 'parser' should be a
609 FancyGetopt instance; do not expect it to be returned in the
610 same state, as its option table will be reset to make it
611 generate the correct help text.
612
613 If 'global_options' is true, lists the global options:
614 --verbose, --dry-run, etc. If 'display_options' is true, lists
615 the "display-only" options: --name, --version, etc. Finally,
616 lists per-command help for every command name or command class
617 in 'commands'.
618 """
619 # late import because of mutual dependence between these modules
Greg Ward9821bf42000-08-29 01:15:18 +0000620 from distutils.core import gen_usage
Greg Wardd5d8a992000-05-23 01:42:17 +0000621 from distutils.cmd import Command
622
623 if global_options:
Fred Draked04573f2004-08-03 16:37:40 +0000624 if display_options:
625 options = self._get_toplevel_options()
626 else:
627 options = self.global_options
628 parser.set_option_table(options)
Martin v. Löwis8ed338a2005-03-03 08:12:27 +0000629 parser.print_help(self.common_usage + "\nGlobal options:")
Tarek Ziadécd947e02009-07-04 02:59:19 +0000630 print('')
Greg Wardd5d8a992000-05-23 01:42:17 +0000631
632 if display_options:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000633 parser.set_option_table(self.display_options)
634 parser.print_help(
Greg Wardd5d8a992000-05-23 01:42:17 +0000635 "Information display options (just display " +
636 "information, ignore any commands)")
Tarek Ziadécd947e02009-07-04 02:59:19 +0000637 print('')
Greg Wardd5d8a992000-05-23 01:42:17 +0000638
639 for command in self.commands:
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000640 if isinstance(command, type) and issubclass(command, Command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000641 klass = command
642 else:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000643 klass = self.get_command_class(command)
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000644 if (hasattr(klass, 'help_options') and
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000645 isinstance(klass.help_options, list)):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000646 parser.set_option_table(klass.user_options +
647 fix_help_options(klass.help_options))
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000648 else:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000649 parser.set_option_table(klass.user_options)
650 parser.print_help("Options for '%s' command:" % klass.__name__)
Tarek Ziadécd947e02009-07-04 02:59:19 +0000651 print('')
Greg Wardd5d8a992000-05-23 01:42:17 +0000652
Tarek Ziadécd947e02009-07-04 02:59:19 +0000653 print(gen_usage(self.script_name))
Greg Wardd5d8a992000-05-23 01:42:17 +0000654
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000655 def handle_display_options(self, option_order):
Greg Ward82715e12000-04-21 02:28:14 +0000656 """If there were any non-global "display-only" options
Greg Wardd5d8a992000-05-23 01:42:17 +0000657 (--help-commands or the metadata display options) on the command
658 line, display the requested info and return true; else return
659 false.
660 """
Greg Ward9821bf42000-08-29 01:15:18 +0000661 from distutils.core import gen_usage
Greg Ward82715e12000-04-21 02:28:14 +0000662
663 # User just wants a list of commands -- we'll print it out and stop
664 # processing now (ie. if they ran "setup --help-commands foo bar",
665 # we ignore "foo bar").
666 if self.help_commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000667 self.print_commands()
Tarek Ziadécd947e02009-07-04 02:59:19 +0000668 print('')
669 print(gen_usage(self.script_name))
Greg Ward82715e12000-04-21 02:28:14 +0000670 return 1
671
672 # If user supplied any of the "display metadata" options, then
673 # display that metadata in the order in which the user supplied the
674 # metadata options.
675 any_display_options = 0
676 is_display_option = {}
677 for option in self.display_options:
678 is_display_option[option[0]] = 1
679
680 for (opt, val) in option_order:
681 if val and is_display_option.get(opt):
Greg Ward2f2b6c62000-09-25 01:58:07 +0000682 opt = translate_longopt(opt)
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000683 value = getattr(self.metadata, "get_"+opt)()
684 if opt in ['keywords', 'platforms']:
Tarek Ziadécd947e02009-07-04 02:59:19 +0000685 print(','.join(value))
Fred Drakedb7b0022005-03-20 22:19:47 +0000686 elif opt in ('classifiers', 'provides', 'requires',
687 'obsoletes'):
Tarek Ziadécd947e02009-07-04 02:59:19 +0000688 print('\n'.join(value))
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000689 else:
Tarek Ziadécd947e02009-07-04 02:59:19 +0000690 print(value)
Greg Ward82715e12000-04-21 02:28:14 +0000691 any_display_options = 1
692
693 return any_display_options
694
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000695 def print_command_list(self, commands, header, max_length):
Greg Wardfe6462c2000-04-04 01:40:52 +0000696 """Print a subset of the list of all commands -- used by
Greg Wardd5d8a992000-05-23 01:42:17 +0000697 'print_commands()'.
698 """
Tarek Ziadécd947e02009-07-04 02:59:19 +0000699 print(header + ":")
Greg Wardfe6462c2000-04-04 01:40:52 +0000700
701 for cmd in commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000702 klass = self.cmdclass.get(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000703 if not klass:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000704 klass = self.get_command_class(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000705 try:
706 description = klass.description
707 except AttributeError:
708 description = "(no description available)"
709
Tarek Ziadécd947e02009-07-04 02:59:19 +0000710 print(" %-*s %s" % (max_length, cmd, description))
Greg Wardfe6462c2000-04-04 01:40:52 +0000711
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000712 def print_commands(self):
Greg Wardd5d8a992000-05-23 01:42:17 +0000713 """Print out a help message listing all available commands with a
714 description of each. The list is divided into "standard commands"
715 (listed in distutils.command.__all__) and "extra commands"
716 (mentioned in self.cmdclass, but not a standard command). The
717 descriptions come from the command class attribute
718 'description'.
719 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000720 import distutils.command
721 std_commands = distutils.command.__all__
722 is_std = {}
723 for cmd in std_commands:
724 is_std[cmd] = 1
725
726 extra_commands = []
727 for cmd in self.cmdclass.keys():
728 if not is_std.get(cmd):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000729 extra_commands.append(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000730
731 max_length = 0
732 for cmd in (std_commands + extra_commands):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000733 if len(cmd) > max_length:
734 max_length = len(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000735
Greg Wardfd7b91e2000-09-26 01:52:25 +0000736 self.print_command_list(std_commands,
737 "Standard commands",
738 max_length)
Greg Wardfe6462c2000-04-04 01:40:52 +0000739 if extra_commands:
740 print
Greg Wardfd7b91e2000-09-26 01:52:25 +0000741 self.print_command_list(extra_commands,
742 "Extra commands",
743 max_length)
Greg Wardfe6462c2000-04-04 01:40:52 +0000744
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000745 def get_command_list(self):
Greg Wardf6fc8752000-11-11 02:47:11 +0000746 """Get a list of (command, description) tuples.
747 The list is divided into "standard commands" (listed in
748 distutils.command.__all__) and "extra commands" (mentioned in
749 self.cmdclass, but not a standard command). The descriptions come
750 from the command class attribute 'description'.
751 """
752 # Currently this is only used on Mac OS, for the Mac-only GUI
753 # Distutils interface (by Jack Jansen)
754
755 import distutils.command
756 std_commands = distutils.command.__all__
757 is_std = {}
758 for cmd in std_commands:
759 is_std[cmd] = 1
760
761 extra_commands = []
762 for cmd in self.cmdclass.keys():
763 if not is_std.get(cmd):
764 extra_commands.append(cmd)
765
766 rv = []
767 for cmd in (std_commands + extra_commands):
768 klass = self.cmdclass.get(cmd)
769 if not klass:
770 klass = self.get_command_class(cmd)
771 try:
772 description = klass.description
773 except AttributeError:
774 description = "(no description available)"
775 rv.append((cmd, description))
776 return rv
Greg Wardfe6462c2000-04-04 01:40:52 +0000777
778 # -- Command class/object methods ----------------------------------
779
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000780 def get_command_packages(self):
Fred Draked04573f2004-08-03 16:37:40 +0000781 """Return a list of packages from which commands are loaded."""
782 pkgs = self.command_packages
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000783 if not isinstance(pkgs, list):
784 if pkgs is None:
785 pkgs = ''
786 pkgs = [pkg.strip() for pkg in pkgs.split(',') if pkg != '']
Fred Draked04573f2004-08-03 16:37:40 +0000787 if "distutils.command" not in pkgs:
788 pkgs.insert(0, "distutils.command")
789 self.command_packages = pkgs
790 return pkgs
791
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000792 def get_command_class(self, command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000793 """Return the class that implements the Distutils command named by
794 'command'. First we check the 'cmdclass' dictionary; if the
795 command is mentioned there, we fetch the class object from the
796 dictionary and return it. Otherwise we load the command module
797 ("distutils.command." + command) and fetch the command class from
798 the module. The loaded class is also stored in 'cmdclass'
799 to speed future calls to 'get_command_class()'.
Greg Wardfe6462c2000-04-04 01:40:52 +0000800
Gregory P. Smith14263542000-05-12 00:41:33 +0000801 Raises DistutilsModuleError if the expected module could not be
Greg Wardd5d8a992000-05-23 01:42:17 +0000802 found, or if that module does not define the expected class.
803 """
804 klass = self.cmdclass.get(command)
805 if klass:
806 return klass
Greg Wardfe6462c2000-04-04 01:40:52 +0000807
Fred Draked04573f2004-08-03 16:37:40 +0000808 for pkgname in self.get_command_packages():
809 module_name = "%s.%s" % (pkgname, command)
810 klass_name = command
Greg Wardfe6462c2000-04-04 01:40:52 +0000811
Fred Draked04573f2004-08-03 16:37:40 +0000812 try:
813 __import__ (module_name)
814 module = sys.modules[module_name]
815 except ImportError:
816 continue
Greg Wardfe6462c2000-04-04 01:40:52 +0000817
Fred Draked04573f2004-08-03 16:37:40 +0000818 try:
819 klass = getattr(module, klass_name)
820 except AttributeError:
821 raise DistutilsModuleError, \
822 "invalid command '%s' (no class '%s' in module '%s')" \
823 % (command, klass_name, module_name)
Greg Wardfe6462c2000-04-04 01:40:52 +0000824
Fred Draked04573f2004-08-03 16:37:40 +0000825 self.cmdclass[command] = klass
826 return klass
827
828 raise DistutilsModuleError("invalid command '%s'" % command)
829
Greg Wardfe6462c2000-04-04 01:40:52 +0000830
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000831 def get_command_obj(self, command, create=1):
Greg Wardd5d8a992000-05-23 01:42:17 +0000832 """Return the command object for 'command'. Normally this object
Greg Ward612eb9f2000-07-27 02:13:20 +0000833 is cached on a previous call to 'get_command_obj()'; if no command
Greg Wardd5d8a992000-05-23 01:42:17 +0000834 object for 'command' is in the cache, then we either create and
835 return it (if 'create' is true) or return None.
836 """
837 cmd_obj = self.command_obj.get(command)
Greg Wardfe6462c2000-04-04 01:40:52 +0000838 if not cmd_obj and create:
Greg Ward2bd3f422000-06-02 01:59:33 +0000839 if DEBUG:
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000840 self.announce("Distribution.get_command_obj(): " \
841 "creating '%s' command object" % command)
Greg Ward47460772000-05-23 03:47:35 +0000842
Greg Wardd5d8a992000-05-23 01:42:17 +0000843 klass = self.get_command_class(command)
Greg Ward47460772000-05-23 03:47:35 +0000844 cmd_obj = self.command_obj[command] = klass(self)
845 self.have_run[command] = 0
846
847 # Set any options that were supplied in config files
848 # or on the command line. (NB. support for error
849 # reporting is lame here: any errors aren't reported
850 # until 'finalize_options()' is called, which means
851 # we won't report the source of the error.)
852 options = self.command_options.get(command)
853 if options:
Greg Wardc32d9a62000-05-28 23:53:06 +0000854 self._set_command_options(cmd_obj, options)
Greg Wardfe6462c2000-04-04 01:40:52 +0000855
856 return cmd_obj
857
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000858 def _set_command_options(self, command_obj, option_dict=None):
Greg Wardc32d9a62000-05-28 23:53:06 +0000859 """Set the options for 'command_obj' from 'option_dict'. Basically
860 this means copying elements of a dictionary ('option_dict') to
861 attributes of an instance ('command').
862
Greg Wardceb9e222000-09-25 01:23:52 +0000863 'command_obj' must be a Command instance. If 'option_dict' is not
Greg Wardc32d9a62000-05-28 23:53:06 +0000864 supplied, uses the standard option dictionary for this command
865 (from 'self.command_options').
866 """
Greg Wardc32d9a62000-05-28 23:53:06 +0000867 command_name = command_obj.get_command_name()
868 if option_dict is None:
869 option_dict = self.get_option_dict(command_name)
870
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000871 if DEBUG:
872 self.announce(" setting options for '%s' command:" % command_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000873 for (option, (source, value)) in option_dict.items():
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000874 if DEBUG:
875 self.announce(" %s = %s (from %s)" % (option, value,
876 source))
Greg Wardceb9e222000-09-25 01:23:52 +0000877 try:
Greg Ward2f2b6c62000-09-25 01:58:07 +0000878 bool_opts = map(translate_longopt, command_obj.boolean_options)
Greg Wardceb9e222000-09-25 01:23:52 +0000879 except AttributeError:
880 bool_opts = []
881 try:
882 neg_opt = command_obj.negative_opt
883 except AttributeError:
884 neg_opt = {}
885
886 try:
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000887 is_string = isinstance(value, str)
Guido van Rossum8bc09652008-02-21 18:18:37 +0000888 if option in neg_opt and is_string:
Greg Wardceb9e222000-09-25 01:23:52 +0000889 setattr(command_obj, neg_opt[option], not strtobool(value))
Greg Ward2c08cf02000-09-27 00:15:37 +0000890 elif option in bool_opts and is_string:
Greg Wardceb9e222000-09-25 01:23:52 +0000891 setattr(command_obj, option, strtobool(value))
892 elif hasattr(command_obj, option):
893 setattr(command_obj, option, value)
894 else:
895 raise DistutilsOptionError, \
896 ("error in %s: command '%s' has no such option '%s'"
897 % (source, command_name, option))
898 except ValueError, msg:
899 raise DistutilsOptionError, msg
Greg Wardc32d9a62000-05-28 23:53:06 +0000900
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000901 def reinitialize_command(self, command, reinit_subcommands=0):
Greg Wardc32d9a62000-05-28 23:53:06 +0000902 """Reinitializes a command to the state it was in when first
903 returned by 'get_command_obj()': ie., initialized but not yet
Greg Ward7d9c7052000-06-28 01:25:27 +0000904 finalized. This provides the opportunity to sneak option
Greg Wardc32d9a62000-05-28 23:53:06 +0000905 values in programmatically, overriding or supplementing
906 user-supplied values from the config files and command line.
907 You'll have to re-finalize the command object (by calling
908 'finalize_options()' or 'ensure_finalized()') before using it for
Fred Drakeb94b8492001-12-06 20:51:35 +0000909 real.
Greg Wardc32d9a62000-05-28 23:53:06 +0000910
Greg Wardf449ea52000-09-16 15:23:28 +0000911 'command' should be a command name (string) or command object. If
912 'reinit_subcommands' is true, also reinitializes the command's
913 sub-commands, as declared by the 'sub_commands' class attribute (if
914 it has one). See the "install" command for an example. Only
915 reinitializes the sub-commands that actually matter, ie. those
916 whose test predicates return true.
917
Greg Wardc32d9a62000-05-28 23:53:06 +0000918 Returns the reinitialized command object.
919 """
920 from distutils.cmd import Command
921 if not isinstance(command, Command):
922 command_name = command
923 command = self.get_command_obj(command_name)
924 else:
925 command_name = command.get_command_name()
926
927 if not command.finalized:
Greg Ward282c7a02000-06-01 01:09:47 +0000928 return command
Greg Wardc32d9a62000-05-28 23:53:06 +0000929 command.initialize_options()
930 command.finalized = 0
Greg Ward43955c92000-06-06 02:52:36 +0000931 self.have_run[command_name] = 0
Greg Wardc32d9a62000-05-28 23:53:06 +0000932 self._set_command_options(command)
Greg Wardf449ea52000-09-16 15:23:28 +0000933
Greg Wardf449ea52000-09-16 15:23:28 +0000934 if reinit_subcommands:
Greg Wardf449ea52000-09-16 15:23:28 +0000935 for sub in command.get_sub_commands():
Fred Drakeb94b8492001-12-06 20:51:35 +0000936 self.reinitialize_command(sub, reinit_subcommands)
Greg Wardf449ea52000-09-16 15:23:28 +0000937
Greg Wardc32d9a62000-05-28 23:53:06 +0000938 return command
939
Greg Wardfe6462c2000-04-04 01:40:52 +0000940 # -- Methods that operate on the Distribution ----------------------
941
Tarek Ziadé63f17382009-07-04 02:02:41 +0000942 def announce(self, msg, level=log.INFO):
943 log.log(level, msg)
Greg Wardfe6462c2000-04-04 01:40:52 +0000944
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000945 def run_commands(self):
Greg Ward82715e12000-04-21 02:28:14 +0000946 """Run each command that was seen on the setup script command line.
Greg Wardd5d8a992000-05-23 01:42:17 +0000947 Uses the list of commands found and cache of command objects
Greg Wardfd7b91e2000-09-26 01:52:25 +0000948 created by 'get_command_obj()'.
949 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000950 for cmd in self.commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000951 self.run_command(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000952
Greg Wardfe6462c2000-04-04 01:40:52 +0000953 # -- Methods that operate on its Commands --------------------------
954
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000955 def run_command(self, command):
Greg Wardfe6462c2000-04-04 01:40:52 +0000956 """Do whatever it takes to run a command (including nothing at all,
Greg Wardd5d8a992000-05-23 01:42:17 +0000957 if the command has already been run). Specifically: if we have
958 already created and run the command named by 'command', return
959 silently without doing anything. If the command named by 'command'
960 doesn't even have a command object yet, create one. Then invoke
961 'run()' on that command object (or an existing one).
962 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000963 # Already been here, done that? then return silently.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000964 if self.have_run.get(command):
Greg Wardfe6462c2000-04-04 01:40:52 +0000965 return
966
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000967 log.info("running %s", command)
Greg Wardfd7b91e2000-09-26 01:52:25 +0000968 cmd_obj = self.get_command_obj(command)
969 cmd_obj.ensure_finalized()
970 cmd_obj.run()
Greg Wardfe6462c2000-04-04 01:40:52 +0000971 self.have_run[command] = 1
972
973
Greg Wardfe6462c2000-04-04 01:40:52 +0000974 # -- Distribution query methods ------------------------------------
975
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000976 def has_pure_modules(self):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000977 return len(self.packages or self.py_modules or []) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000978
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000979 def has_ext_modules(self):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000980 return self.ext_modules and len(self.ext_modules) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000981
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000982 def has_c_libraries(self):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000983 return self.libraries and len(self.libraries) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000984
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000985 def has_modules(self):
Greg Wardfe6462c2000-04-04 01:40:52 +0000986 return self.has_pure_modules() or self.has_ext_modules()
987
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000988 def has_headers(self):
Greg Ward51def7d2000-05-27 01:36:14 +0000989 return self.headers and len(self.headers) > 0
990
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000991 def has_scripts(self):
Greg Ward44a61bb2000-05-20 15:06:48 +0000992 return self.scripts and len(self.scripts) > 0
993
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000994 def has_data_files(self):
Greg Ward44a61bb2000-05-20 15:06:48 +0000995 return self.data_files and len(self.data_files) > 0
996
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000997 def is_pure(self):
Greg Wardfe6462c2000-04-04 01:40:52 +0000998 return (self.has_pure_modules() and
999 not self.has_ext_modules() and
1000 not self.has_c_libraries())
1001
Greg Ward82715e12000-04-21 02:28:14 +00001002 # -- Metadata query methods ----------------------------------------
1003
1004 # If you're looking for 'get_name()', 'get_version()', and so forth,
1005 # they are defined in a sneaky way: the constructor binds self.get_XXX
1006 # to self.metadata.get_XXX. The actual code is in the
1007 # DistributionMetadata class, below.
1008
Greg Ward82715e12000-04-21 02:28:14 +00001009class DistributionMetadata:
1010 """Dummy class to hold the distribution meta-data: name, version,
Greg Wardfd7b91e2000-09-26 01:52:25 +00001011 author, and so forth.
1012 """
Greg Ward82715e12000-04-21 02:28:14 +00001013
Neil Schemenauera8aefe52001-09-03 15:47:21 +00001014 _METHOD_BASENAMES = ("name", "version", "author", "author_email",
1015 "maintainer", "maintainer_email", "url",
1016 "license", "description", "long_description",
1017 "keywords", "platforms", "fullname", "contact",
Andrew M. Kuchlinga52b8522003-03-03 20:07:27 +00001018 "contact_email", "license", "classifiers",
Fred Drakedb7b0022005-03-20 22:19:47 +00001019 "download_url",
1020 # PEP 314
1021 "provides", "requires", "obsoletes",
1022 )
Neil Schemenauera8aefe52001-09-03 15:47:21 +00001023
Greg Ward82715e12000-04-21 02:28:14 +00001024 def __init__ (self):
1025 self.name = None
1026 self.version = None
1027 self.author = None
1028 self.author_email = None
1029 self.maintainer = None
1030 self.maintainer_email = None
1031 self.url = None
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +00001032 self.license = None
Greg Ward82715e12000-04-21 02:28:14 +00001033 self.description = None
Greg Warde5a584e2000-04-26 02:26:55 +00001034 self.long_description = None
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001035 self.keywords = None
1036 self.platforms = None
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +00001037 self.classifiers = None
Andrew M. Kuchling188d85f2003-02-19 14:16:01 +00001038 self.download_url = None
Fred Drakedb7b0022005-03-20 22:19:47 +00001039 # PEP 314
1040 self.provides = None
1041 self.requires = None
1042 self.obsoletes = None
Fred Drakeb94b8492001-12-06 20:51:35 +00001043
Tarek Ziadéae6acfc2009-05-16 18:29:40 +00001044 def write_pkg_info(self, base_dir):
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001045 """Write the PKG-INFO file into the release tree.
1046 """
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001047 pkg_info = open( os.path.join(base_dir, 'PKG-INFO'), 'w')
Fred Drakedb7b0022005-03-20 22:19:47 +00001048 self.write_pkg_file(pkg_info)
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001049 pkg_info.close()
Fred Drakeb94b8492001-12-06 20:51:35 +00001050
Tarek Ziadéae6acfc2009-05-16 18:29:40 +00001051 def write_pkg_file(self, file):
Fred Drakedb7b0022005-03-20 22:19:47 +00001052 """Write the PKG-INFO format data to a file object.
1053 """
1054 version = '1.0'
1055 if self.provides or self.requires or self.obsoletes:
1056 version = '1.1'
1057
Marc-André Lemburgb339b2a2008-09-03 11:13:56 +00001058 self._write_field(file, 'Metadata-Version', version)
1059 self._write_field(file, 'Name', self.get_name())
1060 self._write_field(file, 'Version', self.get_version())
1061 self._write_field(file, 'Summary', self.get_description())
1062 self._write_field(file, 'Home-page', self.get_url())
1063 self._write_field(file, 'Author', self.get_contact())
1064 self._write_field(file, 'Author-email', self.get_contact_email())
1065 self._write_field(file, 'License', self.get_license())
Fred Drakedb7b0022005-03-20 22:19:47 +00001066 if self.download_url:
Marc-André Lemburgb339b2a2008-09-03 11:13:56 +00001067 self._write_field(file, 'Download-URL', self.download_url)
Fred Drakedb7b0022005-03-20 22:19:47 +00001068
Tarek Ziadéc01cbc42009-06-01 22:22:13 +00001069 long_desc = rfc822_escape(self.get_long_description())
Marc-André Lemburgb339b2a2008-09-03 11:13:56 +00001070 self._write_field(file, 'Description', long_desc)
Fred Drakedb7b0022005-03-20 22:19:47 +00001071
Tarek Ziadéc01cbc42009-06-01 22:22:13 +00001072 keywords = ','.join(self.get_keywords())
Fred Drakedb7b0022005-03-20 22:19:47 +00001073 if keywords:
Marc-André Lemburgb339b2a2008-09-03 11:13:56 +00001074 self._write_field(file, 'Keywords', keywords)
Fred Drakedb7b0022005-03-20 22:19:47 +00001075
1076 self._write_list(file, 'Platform', self.get_platforms())
1077 self._write_list(file, 'Classifier', self.get_classifiers())
1078
1079 # PEP 314
1080 self._write_list(file, 'Requires', self.get_requires())
1081 self._write_list(file, 'Provides', self.get_provides())
1082 self._write_list(file, 'Obsoletes', self.get_obsoletes())
1083
Marc-André Lemburgb339b2a2008-09-03 11:13:56 +00001084 def _write_field(self, file, name, value):
Marc-André Lemburgb339b2a2008-09-03 11:13:56 +00001085 if isinstance(value, unicode):
1086 value = value.encode(PKG_INFO_ENCODING)
1087 else:
1088 value = str(value)
1089 file.write('%s: %s\n' % (name, value))
1090
Fred Drakedb7b0022005-03-20 22:19:47 +00001091 def _write_list (self, file, name, values):
1092 for value in values:
Marc-André Lemburgb339b2a2008-09-03 11:13:56 +00001093 self._write_field(file, name, value)
Fred Drakedb7b0022005-03-20 22:19:47 +00001094
Greg Ward82715e12000-04-21 02:28:14 +00001095 # -- Metadata query methods ----------------------------------------
1096
Tarek Ziadéae6acfc2009-05-16 18:29:40 +00001097 def get_name(self):
Greg Wardfe6462c2000-04-04 01:40:52 +00001098 return self.name or "UNKNOWN"
1099
Greg Ward82715e12000-04-21 02:28:14 +00001100 def get_version(self):
Thomas Hellerbcd89752001-12-06 20:44:19 +00001101 return self.version or "0.0.0"
Greg Wardfe6462c2000-04-04 01:40:52 +00001102
Tarek Ziadéae6acfc2009-05-16 18:29:40 +00001103 def get_fullname(self):
Greg Ward82715e12000-04-21 02:28:14 +00001104 return "%s-%s" % (self.get_name(), self.get_version())
1105
1106 def get_author(self):
1107 return self.author or "UNKNOWN"
1108
1109 def get_author_email(self):
1110 return self.author_email or "UNKNOWN"
1111
1112 def get_maintainer(self):
1113 return self.maintainer or "UNKNOWN"
1114
1115 def get_maintainer_email(self):
1116 return self.maintainer_email or "UNKNOWN"
1117
1118 def get_contact(self):
Tarek Ziadéae6acfc2009-05-16 18:29:40 +00001119 return self.maintainer or self.author or "UNKNOWN"
Greg Ward82715e12000-04-21 02:28:14 +00001120
1121 def get_contact_email(self):
Tarek Ziadéae6acfc2009-05-16 18:29:40 +00001122 return self.maintainer_email or self.author_email or "UNKNOWN"
Greg Ward82715e12000-04-21 02:28:14 +00001123
1124 def get_url(self):
1125 return self.url or "UNKNOWN"
1126
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +00001127 def get_license(self):
1128 return self.license or "UNKNOWN"
1129 get_licence = get_license
Fred Drakeb94b8492001-12-06 20:51:35 +00001130
Greg Ward82715e12000-04-21 02:28:14 +00001131 def get_description(self):
1132 return self.description or "UNKNOWN"
Greg Warde5a584e2000-04-26 02:26:55 +00001133
1134 def get_long_description(self):
1135 return self.long_description or "UNKNOWN"
1136
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001137 def get_keywords(self):
1138 return self.keywords or []
1139
1140 def get_platforms(self):
1141 return self.platforms or ["UNKNOWN"]
1142
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +00001143 def get_classifiers(self):
1144 return self.classifiers or []
1145
Andrew M. Kuchling188d85f2003-02-19 14:16:01 +00001146 def get_download_url(self):
1147 return self.download_url or "UNKNOWN"
1148
Fred Drakedb7b0022005-03-20 22:19:47 +00001149 # PEP 314
Fred Drakedb7b0022005-03-20 22:19:47 +00001150 def get_requires(self):
1151 return self.requires or []
1152
1153 def set_requires(self, value):
1154 import distutils.versionpredicate
1155 for v in value:
1156 distutils.versionpredicate.VersionPredicate(v)
1157 self.requires = value
1158
1159 def get_provides(self):
1160 return self.provides or []
1161
1162 def set_provides(self, value):
1163 value = [v.strip() for v in value]
1164 for v in value:
1165 import distutils.versionpredicate
Fred Drake227e8ff2005-03-21 06:36:32 +00001166 distutils.versionpredicate.split_provision(v)
Fred Drakedb7b0022005-03-20 22:19:47 +00001167 self.provides = value
1168
1169 def get_obsoletes(self):
1170 return self.obsoletes or []
1171
1172 def set_obsoletes(self, value):
1173 import distutils.versionpredicate
1174 for v in value:
1175 distutils.versionpredicate.VersionPredicate(v)
1176 self.obsoletes = value
1177
Tarek Ziadéae6acfc2009-05-16 18:29:40 +00001178def fix_help_options(options):
Greg Ward2ff78872000-06-24 00:23:20 +00001179 """Convert a 4-tuple 'help_options' list as found in various command
1180 classes to the 3-tuple form required by FancyGetopt.
1181 """
1182 new_options = []
1183 for help_tuple in options:
1184 new_options.append(help_tuple[0:3])
1185 return new_options