blob: ee2cec90887725185be8c49ef77a1dfc5ec66425 [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
Tarek Ziadé4b7f9432009-12-08 09:39:51 +000010from email import message_from_file
Andrew M. Kuchlingff4ad9a2002-10-31 13:22:41 +000011
12try:
13 import warnings
Andrew M. Kuchlingccf4e422002-10-31 13:39:33 +000014except ImportError:
Andrew M. Kuchlingff4ad9a2002-10-31 13:22:41 +000015 warnings = None
16
Greg Wardfe6462c2000-04-04 01:40:52 +000017from distutils.errors import *
Greg Ward2f2b6c62000-09-25 01:58:07 +000018from distutils.fancy_getopt import FancyGetopt, translate_longopt
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +000019from distutils.util import check_environ, strtobool, rfc822_escape
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000020from distutils import log
Jeremy Hyltonfcd73532002-09-11 16:31:53 +000021from distutils.debug import DEBUG
Greg Wardfe6462c2000-04-04 01:40:52 +000022
Marc-André Lemburgb339b2a2008-09-03 11:13:56 +000023# Encoding used for the PKG-INFO files
24PKG_INFO_ENCODING = 'utf-8'
25
Greg Wardfe6462c2000-04-04 01:40:52 +000026# Regex to define acceptable Distutils command names. This is not *quite*
27# the same as a Python NAME -- I don't allow leading underscores. The fact
28# that they're very similar is no coincidence; the default naming scheme is
29# to look for a Python module named after the command.
30command_re = re.compile (r'^[a-zA-Z]([a-zA-Z0-9_]*)$')
31
32
33class Distribution:
Greg Ward8ff5a3f2000-06-02 00:44:53 +000034 """The core of the Distutils. Most of the work hiding behind 'setup'
35 is really done within a Distribution instance, which farms the work out
36 to the Distutils commands specified on the command line.
Greg Wardfe6462c2000-04-04 01:40:52 +000037
Greg Ward8ff5a3f2000-06-02 00:44:53 +000038 Setup scripts will almost never instantiate Distribution directly,
39 unless the 'setup()' function is totally inadequate to their needs.
40 However, it is conceivable that a setup script might wish to subclass
41 Distribution for some specialized purpose, and then pass the subclass
42 to 'setup()' as the 'distclass' keyword argument. If so, it is
43 necessary to respect the expectations that 'setup' has of Distribution.
44 See the code for 'setup()', in core.py, for details.
45 """
Greg Wardfe6462c2000-04-04 01:40:52 +000046
47
48 # 'global_options' describes the command-line options that may be
Greg Ward82715e12000-04-21 02:28:14 +000049 # supplied to the setup script prior to any actual commands.
50 # Eg. "./setup.py -n" or "./setup.py --quiet" both take advantage of
Greg Wardfe6462c2000-04-04 01:40:52 +000051 # these global options. This list should be kept to a bare minimum,
52 # since every global option is also valid as a command option -- and we
53 # don't want to pollute the commands with too many options that they
54 # have minimal control over.
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000055 # The fourth entry for verbose means that it can be repeated.
56 global_options = [('verbose', 'v', "run verbosely (default)", 1),
Greg Wardd5d8a992000-05-23 01:42:17 +000057 ('quiet', 'q', "run quietly (turns verbosity off)"),
58 ('dry-run', 'n', "don't actually do anything"),
59 ('help', 'h', "show detailed help message"),
Tarek Ziadé40b998b2009-10-27 23:06:10 +000060 ('no-user-cfg', None,
61 'ignore pydistutils.cfg in your home directory'),
62 ]
Greg Ward82715e12000-04-21 02:28:14 +000063
Martin v. Löwis8ed338a2005-03-03 08:12:27 +000064 # 'common_usage' is a short (2-3 line) string describing the common
65 # usage of the setup script.
66 common_usage = """\
67Common commands: (see '--help-commands' for more)
68
69 setup.py build will build the package underneath 'build/'
70 setup.py install will install the package
71"""
72
Greg Ward82715e12000-04-21 02:28:14 +000073 # options that are not propagated to the commands
74 display_options = [
75 ('help-commands', None,
76 "list all available commands"),
77 ('name', None,
78 "print package name"),
79 ('version', 'V',
80 "print package version"),
81 ('fullname', None,
82 "print <package name>-<version>"),
83 ('author', None,
84 "print the author's name"),
85 ('author-email', None,
86 "print the author's email address"),
87 ('maintainer', None,
88 "print the maintainer's name"),
89 ('maintainer-email', None,
90 "print the maintainer's email address"),
91 ('contact', None,
Greg Wardd5d8a992000-05-23 01:42:17 +000092 "print the maintainer's name if known, else the author's"),
Greg Ward82715e12000-04-21 02:28:14 +000093 ('contact-email', None,
Greg Wardd5d8a992000-05-23 01:42:17 +000094 "print the maintainer's email address if known, else the author's"),
Greg Ward82715e12000-04-21 02:28:14 +000095 ('url', None,
96 "print the URL for this package"),
Greg Ward82715e12000-04-21 02:28:14 +000097 ('license', None,
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +000098 "print the license of the package"),
99 ('licence', None,
100 "alias for --license"),
Greg Ward82715e12000-04-21 02:28:14 +0000101 ('description', None,
102 "print the package description"),
Greg Warde5a584e2000-04-26 02:26:55 +0000103 ('long-description', None,
104 "print the long package description"),
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000105 ('platforms', None,
106 "print the list of platforms"),
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +0000107 ('classifiers', None,
108 "print the list of classifiers"),
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000109 ('keywords', None,
110 "print the list of keywords"),
Fred Drakedb7b0022005-03-20 22:19:47 +0000111 ('provides', None,
112 "print the list of packages/modules provided"),
113 ('requires', None,
114 "print the list of packages/modules required"),
115 ('obsoletes', None,
116 "print the list of packages/modules made obsolete")
Greg Ward82715e12000-04-21 02:28:14 +0000117 ]
Greg Ward2f2b6c62000-09-25 01:58:07 +0000118 display_option_names = map(lambda x: translate_longopt(x[0]),
119 display_options)
Greg Ward82715e12000-04-21 02:28:14 +0000120
121 # negative options are options that exclude other options
Greg Wardfe6462c2000-04-04 01:40:52 +0000122 negative_opt = {'quiet': 'verbose'}
123
124
125 # -- Creation/initialization methods -------------------------------
Fred Drakeb94b8492001-12-06 20:51:35 +0000126
Greg Wardfe6462c2000-04-04 01:40:52 +0000127 def __init__ (self, attrs=None):
128 """Construct a new Distribution instance: initialize all the
Greg Ward8ff5a3f2000-06-02 00:44:53 +0000129 attributes of a Distribution, and then use 'attrs' (a dictionary
130 mapping attribute names to values) to assign some of those
131 attributes their "real" values. (Any attributes not mentioned in
132 'attrs' will be assigned to some null value: 0, None, an empty list
133 or dictionary, etc.) Most importantly, initialize the
134 'command_obj' attribute to the empty dictionary; this will be
135 filled in with real command objects by 'parse_command_line()'.
136 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000137
138 # Default values for our command-line options
139 self.verbose = 1
140 self.dry_run = 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000141 self.help = 0
Greg Ward82715e12000-04-21 02:28:14 +0000142 for attr in self.display_option_names:
143 setattr(self, attr, 0)
Greg Wardfe6462c2000-04-04 01:40:52 +0000144
Greg Ward82715e12000-04-21 02:28:14 +0000145 # Store the distribution meta-data (name, version, author, and so
146 # forth) in a separate object -- we're getting to have enough
147 # information here (and enough command-line options) that it's
148 # worth it. Also delegate 'get_XXX()' methods to the 'metadata'
149 # object in a sneaky and underhanded (but efficient!) way.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000150 self.metadata = DistributionMetadata()
Neil Schemenauera8aefe52001-09-03 15:47:21 +0000151 for basename in self.metadata._METHOD_BASENAMES:
Greg Ward4982f982000-04-22 02:52:44 +0000152 method_name = "get_" + basename
153 setattr(self, method_name, getattr(self.metadata, method_name))
Greg Wardfe6462c2000-04-04 01:40:52 +0000154
155 # 'cmdclass' maps command names to class objects, so we
156 # can 1) quickly figure out which class to instantiate when
157 # we need to create a new command object, and 2) have a way
Greg Ward82715e12000-04-21 02:28:14 +0000158 # for the setup script to override command classes
Greg Wardfe6462c2000-04-04 01:40:52 +0000159 self.cmdclass = {}
160
Fred Draked04573f2004-08-03 16:37:40 +0000161 # 'command_packages' is a list of packages in which commands
162 # are searched for. The factory for command 'foo' is expected
163 # to be named 'foo' in the module 'foo' in one of the packages
164 # named here. This list is searched from the left; an error
165 # is raised if no named package provides the command being
166 # searched for. (Always access using get_command_packages().)
167 self.command_packages = None
168
Greg Ward9821bf42000-08-29 01:15:18 +0000169 # 'script_name' and 'script_args' are usually set to sys.argv[0]
170 # and sys.argv[1:], but they can be overridden when the caller is
171 # not necessarily a setup script run from the command-line.
172 self.script_name = None
173 self.script_args = None
174
Greg Wardd5d8a992000-05-23 01:42:17 +0000175 # 'command_options' is where we store command options between
176 # parsing them (from config files, the command-line, etc.) and when
177 # they are actually needed -- ie. when the command in question is
178 # instantiated. It is a dictionary of dictionaries of 2-tuples:
179 # command_options = { command_name : { option : (source, value) } }
Gregory P. Smith14263542000-05-12 00:41:33 +0000180 self.command_options = {}
181
Martin v. Löwis98da5622005-03-23 18:54:36 +0000182 # 'dist_files' is the list of (command, pyversion, file) that
183 # have been created by any dist commands run so far. This is
184 # filled regardless of whether the run is dry or not. pyversion
185 # gives sysconfig.get_python_version() if the dist file is
186 # specific to a Python version, 'any' if it is good for all
187 # Python versions on the target platform, and '' for a source
188 # file. pyversion should not be used to specify minimum or
189 # maximum required Python versions; use the metainfo for that
190 # instead.
Martin v. Löwis55f1bb82005-03-21 20:56:35 +0000191 self.dist_files = []
192
Greg Wardfe6462c2000-04-04 01:40:52 +0000193 # These options are really the business of various commands, rather
194 # than of the Distribution itself. We provide aliases for them in
195 # Distribution as a convenience to the developer.
Greg Wardfe6462c2000-04-04 01:40:52 +0000196 self.packages = None
Fred Drake0eb32a62004-06-11 21:50:33 +0000197 self.package_data = {}
Greg Wardfe6462c2000-04-04 01:40:52 +0000198 self.package_dir = None
199 self.py_modules = None
200 self.libraries = None
Greg Ward51def7d2000-05-27 01:36:14 +0000201 self.headers = None
Greg Wardfe6462c2000-04-04 01:40:52 +0000202 self.ext_modules = None
203 self.ext_package = None
204 self.include_dirs = None
205 self.extra_path = None
Gregory P. Smithb2e3bb32000-05-12 00:52:23 +0000206 self.scripts = None
Gregory P. Smith6a901dd2000-05-13 03:09:50 +0000207 self.data_files = None
Tarek Ziadé1a240fb2009-01-08 23:56:31 +0000208 self.password = ''
Greg Wardfe6462c2000-04-04 01:40:52 +0000209
210 # And now initialize bookkeeping stuff that can't be supplied by
211 # the caller at all. 'command_obj' maps command names to
212 # Command instances -- that's how we enforce that every command
213 # class is a singleton.
214 self.command_obj = {}
215
216 # 'have_run' maps command names to boolean values; it keeps track
217 # of whether we have actually run a particular command, to make it
218 # cheap to "run" a command whenever we think we might need to -- if
219 # it's already been done, no need for expensive filesystem
220 # operations, we just check the 'have_run' dictionary and carry on.
221 # It's only safe to query 'have_run' for a command class that has
222 # been instantiated -- a false value will be inserted when the
223 # command object is created, and replaced with a true value when
Greg Ward612eb9f2000-07-27 02:13:20 +0000224 # the command is successfully run. Thus it's probably best to use
Greg Wardfe6462c2000-04-04 01:40:52 +0000225 # '.get()' rather than a straight lookup.
226 self.have_run = {}
227
228 # Now we'll use the attrs dictionary (ultimately, keyword args from
Greg Ward82715e12000-04-21 02:28:14 +0000229 # the setup script) to possibly override any or all of these
230 # distribution options.
231
Greg Wardfe6462c2000-04-04 01:40:52 +0000232 if attrs:
Greg Wardfe6462c2000-04-04 01:40:52 +0000233 # Pull out the set of command options and work on them
234 # specifically. Note that this order guarantees that aliased
235 # command options will override any supplied redundantly
236 # through the general options dictionary.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000237 options = attrs.get('options')
Tarek Ziadéc13acb12008-12-29 22:23:53 +0000238 if options is not None:
Greg Wardfe6462c2000-04-04 01:40:52 +0000239 del attrs['options']
240 for (command, cmd_options) in options.items():
Greg Ward0e48cfd2000-05-26 01:00:15 +0000241 opt_dict = self.get_option_dict(command)
242 for (opt, val) in cmd_options.items():
243 opt_dict[opt] = ("setup script", val)
Greg Wardfe6462c2000-04-04 01:40:52 +0000244
Guido van Rossum8bc09652008-02-21 18:18:37 +0000245 if 'licence' in attrs:
Andrew M. Kuchlinga52b8522003-03-03 20:07:27 +0000246 attrs['license'] = attrs['licence']
247 del attrs['licence']
248 msg = "'licence' distribution option is deprecated; use 'license'"
249 if warnings is not None:
250 warnings.warn(msg)
251 else:
252 sys.stderr.write(msg + "\n")
253
Greg Wardfe6462c2000-04-04 01:40:52 +0000254 # Now work on the rest of the attributes. Any attribute that's
255 # not already defined is invalid!
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000256 for (key, val) in attrs.items():
Fred Drakedb7b0022005-03-20 22:19:47 +0000257 if hasattr(self.metadata, "set_" + key):
258 getattr(self.metadata, "set_" + key)(val)
259 elif hasattr(self.metadata, key):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000260 setattr(self.metadata, key, val)
261 elif hasattr(self, key):
262 setattr(self, key, val)
Anthony Baxter73cc8472004-10-13 13:22:34 +0000263 else:
Andrew M. Kuchlingff4ad9a2002-10-31 13:22:41 +0000264 msg = "Unknown distribution option: %s" % repr(key)
265 if warnings is not None:
266 warnings.warn(msg)
267 else:
268 sys.stderr.write(msg + "\n")
Greg Wardfe6462c2000-04-04 01:40:52 +0000269
Tarek Ziadé40b998b2009-10-27 23:06:10 +0000270 # no-user-cfg is handled before other command line args
271 # because other args override the config files, and this
272 # one is needed before we can load the config files.
273 # If attrs['script_args'] wasn't passed, assume false.
274 #
275 # This also make sure we just look at the global options
276 self.want_user_cfg = True
277
278 if self.script_args is not None:
279 for arg in self.script_args:
280 if not arg.startswith('-'):
281 break
282 if arg == '--no-user-cfg':
283 self.want_user_cfg = False
284 break
285
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000286 self.finalize_options()
Fred Drakeb94b8492001-12-06 20:51:35 +0000287
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000288 def get_option_dict(self, command):
Greg Ward0e48cfd2000-05-26 01:00:15 +0000289 """Get the option dictionary for a given command. If that
290 command's option dictionary hasn't been created yet, then create it
291 and return the new dictionary; otherwise, return the existing
292 option dictionary.
293 """
Greg Ward0e48cfd2000-05-26 01:00:15 +0000294 dict = self.command_options.get(command)
295 if dict is None:
296 dict = self.command_options[command] = {}
297 return dict
298
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000299 def dump_option_dicts(self, header=None, commands=None, indent=""):
Greg Wardc32d9a62000-05-28 23:53:06 +0000300 from pprint import pformat
301
302 if commands is None: # dump all command option dicts
303 commands = self.command_options.keys()
304 commands.sort()
305
306 if header is not None:
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000307 self.announce(indent + header)
Greg Wardc32d9a62000-05-28 23:53:06 +0000308 indent = indent + " "
309
310 if not commands:
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000311 self.announce(indent + "no commands known yet")
Greg Wardc32d9a62000-05-28 23:53:06 +0000312 return
313
314 for cmd_name in commands:
315 opt_dict = self.command_options.get(cmd_name)
316 if opt_dict is None:
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000317 self.announce(indent +
318 "no option dict for '%s' command" % cmd_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000319 else:
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000320 self.announce(indent +
321 "option dict for '%s' command:" % cmd_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000322 out = pformat(opt_dict)
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000323 for line in out.split('\n'):
324 self.announce(indent + " " + line)
Greg Wardc32d9a62000-05-28 23:53:06 +0000325
Greg Wardd5d8a992000-05-23 01:42:17 +0000326 # -- Config file finding/parsing methods ---------------------------
327
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000328 def find_config_files(self):
Gregory P. Smith14263542000-05-12 00:41:33 +0000329 """Find as many configuration files as should be processed for this
330 platform, and return a list of filenames in the order in which they
331 should be parsed. The filenames returned are guaranteed to exist
332 (modulo nasty race conditions).
333
Andrew M. Kuchlingd303b612001-12-06 16:32:05 +0000334 There are three possible config files: distutils.cfg in the
335 Distutils installation directory (ie. where the top-level
336 Distutils __inst__.py file lives), a file in the user's home
337 directory named .pydistutils.cfg on Unix and pydistutils.cfg
Tarek Ziadé40b998b2009-10-27 23:06:10 +0000338 on Windows/Mac; and setup.cfg in the current directory.
339
340 The file in the user's home directory can be disabled with the
341 --no-user-cfg option.
Greg Wardd5d8a992000-05-23 01:42:17 +0000342 """
Gregory P. Smith14263542000-05-12 00:41:33 +0000343 files = []
Greg Wardacf3f6a2000-06-07 02:26:19 +0000344 check_environ()
Gregory P. Smith14263542000-05-12 00:41:33 +0000345
Greg Ward11696872000-06-07 02:29:03 +0000346 # Where to look for the system-wide Distutils config file
347 sys_dir = os.path.dirname(sys.modules['distutils'].__file__)
348
349 # Look for the system config file
350 sys_file = os.path.join(sys_dir, "distutils.cfg")
Greg Wardacf3f6a2000-06-07 02:26:19 +0000351 if os.path.isfile(sys_file):
352 files.append(sys_file)
Gregory P. Smith14263542000-05-12 00:41:33 +0000353
Greg Ward11696872000-06-07 02:29:03 +0000354 # What to call the per-user config file
355 if os.name == 'posix':
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000356 user_filename = ".pydistutils.cfg"
357 else:
358 user_filename = "pydistutils.cfg"
Greg Wardfa9ff762000-10-14 04:06:40 +0000359
Greg Ward11696872000-06-07 02:29:03 +0000360 # And look for the user config file
Tarek Ziadé40b998b2009-10-27 23:06:10 +0000361 if self.want_user_cfg:
362 user_file = os.path.join(os.path.expanduser('~'), user_filename)
363 if os.path.isfile(user_file):
364 files.append(user_file)
Gregory P. Smith14263542000-05-12 00:41:33 +0000365
Gregory P. Smith14263542000-05-12 00:41:33 +0000366 # All platforms support local setup.cfg
367 local_file = "setup.cfg"
368 if os.path.isfile(local_file):
369 files.append(local_file)
370
Tarek Ziadé40b998b2009-10-27 23:06:10 +0000371 if DEBUG:
372 self.announce("using config files: %s" % ', '.join(files))
373
Gregory P. Smith14263542000-05-12 00:41:33 +0000374 return files
375
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000376 def parse_config_files(self, filenames=None):
Georg Brandl392c6fc2008-05-25 07:25:25 +0000377 from ConfigParser import ConfigParser
Gregory P. Smith14263542000-05-12 00:41:33 +0000378
379 if filenames is None:
380 filenames = self.find_config_files()
381
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000382 if DEBUG:
383 self.announce("Distribution.parse_config_files():")
Greg Ward47460772000-05-23 03:47:35 +0000384
Gregory P. Smith14263542000-05-12 00:41:33 +0000385 parser = ConfigParser()
Greg Wardd5d8a992000-05-23 01:42:17 +0000386 for filename in filenames:
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000387 if DEBUG:
Tarek Ziadé99773352009-09-21 13:41:08 +0000388 self.announce(" reading %s" % filename)
Greg Wardd5d8a992000-05-23 01:42:17 +0000389 parser.read(filename)
390 for section in parser.sections():
391 options = parser.options(section)
Greg Ward0e48cfd2000-05-26 01:00:15 +0000392 opt_dict = self.get_option_dict(section)
Gregory P. Smith14263542000-05-12 00:41:33 +0000393
Greg Wardd5d8a992000-05-23 01:42:17 +0000394 for opt in options:
395 if opt != '__name__':
Greg Wardceb9e222000-09-25 01:23:52 +0000396 val = parser.get(section,opt)
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000397 opt = opt.replace('-', '_')
Greg Wardceb9e222000-09-25 01:23:52 +0000398 opt_dict[opt] = (filename, val)
Gregory P. Smith14263542000-05-12 00:41:33 +0000399
Greg Ward47460772000-05-23 03:47:35 +0000400 # Make the ConfigParser forget everything (so we retain
Fred Drakef06116d2004-02-17 22:35:19 +0000401 # the original filenames that options come from)
Greg Ward47460772000-05-23 03:47:35 +0000402 parser.__init__()
Gregory P. Smith14263542000-05-12 00:41:33 +0000403
Greg Wardceb9e222000-09-25 01:23:52 +0000404 # If there was a "global" section in the config file, use it
405 # to set Distribution options.
406
Guido van Rossum8bc09652008-02-21 18:18:37 +0000407 if 'global' in self.command_options:
Greg Wardceb9e222000-09-25 01:23:52 +0000408 for (opt, (src, val)) in self.command_options['global'].items():
409 alias = self.negative_opt.get(opt)
410 try:
411 if alias:
412 setattr(self, alias, not strtobool(val))
413 elif opt in ('verbose', 'dry_run'): # ugh!
414 setattr(self, opt, strtobool(val))
Fred Draked04573f2004-08-03 16:37:40 +0000415 else:
416 setattr(self, opt, val)
Greg Wardceb9e222000-09-25 01:23:52 +0000417 except ValueError, msg:
418 raise DistutilsOptionError, msg
419
Greg Wardd5d8a992000-05-23 01:42:17 +0000420 # -- Command-line parsing methods ----------------------------------
421
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000422 def parse_command_line(self):
Greg Ward9821bf42000-08-29 01:15:18 +0000423 """Parse the setup script's command line, taken from the
424 'script_args' instance attribute (which defaults to 'sys.argv[1:]'
425 -- see 'setup()' in core.py). This list is first processed for
426 "global options" -- options that set attributes of the Distribution
427 instance. Then, it is alternately scanned for Distutils commands
428 and options for that command. Each new command terminates the
429 options for the previous command. The allowed options for a
430 command are determined by the 'user_options' attribute of the
431 command class -- thus, we have to be able to load command classes
432 in order to parse the command line. Any error in that 'options'
433 attribute raises DistutilsGetoptError; any error on the
434 command-line raises DistutilsArgError. If no Distutils commands
435 were found on the command line, raises DistutilsArgError. Return
Greg Wardceb9e222000-09-25 01:23:52 +0000436 true if command-line was successfully parsed and we should carry
Greg Ward9821bf42000-08-29 01:15:18 +0000437 on with executing commands; false if no errors but we shouldn't
438 execute commands (currently, this only happens if user asks for
439 help).
Greg Wardd5d8a992000-05-23 01:42:17 +0000440 """
Andrew M. Kuchling3f819ec2001-01-15 16:09:35 +0000441 #
Fred Drake981a1782001-08-10 18:59:30 +0000442 # We now have enough information to show the Macintosh dialog
443 # that allows the user to interactively specify the "command line".
Andrew M. Kuchling3f819ec2001-01-15 16:09:35 +0000444 #
Fred Draked04573f2004-08-03 16:37:40 +0000445 toplevel_options = self._get_toplevel_options()
Fred Drakeb94b8492001-12-06 20:51:35 +0000446
Greg Wardfe6462c2000-04-04 01:40:52 +0000447 # We have to parse the command line a bit at a time -- global
448 # options, then the first command, then its options, and so on --
449 # because each command will be handled by a different class, and
Greg Wardd5d8a992000-05-23 01:42:17 +0000450 # the options that are valid for a particular class aren't known
451 # until we have loaded the command class, which doesn't happen
452 # until we know what the command is.
Greg Wardfe6462c2000-04-04 01:40:52 +0000453
454 self.commands = []
Fred Draked04573f2004-08-03 16:37:40 +0000455 parser = FancyGetopt(toplevel_options + self.display_options)
Greg Wardfd7b91e2000-09-26 01:52:25 +0000456 parser.set_negative_aliases(self.negative_opt)
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +0000457 parser.set_aliases({'licence': 'license'})
Greg Wardfd7b91e2000-09-26 01:52:25 +0000458 args = parser.getopt(args=self.script_args, object=self)
Greg Ward82715e12000-04-21 02:28:14 +0000459 option_order = parser.get_option_order()
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000460 log.set_verbosity(self.verbose)
Greg Wardfe6462c2000-04-04 01:40:52 +0000461
Greg Ward82715e12000-04-21 02:28:14 +0000462 # for display options we return immediately
463 if self.handle_display_options(option_order):
Greg Wardfe6462c2000-04-04 01:40:52 +0000464 return
Greg Wardfe6462c2000-04-04 01:40:52 +0000465 while args:
Greg Wardd5d8a992000-05-23 01:42:17 +0000466 args = self._parse_command_opts(parser, args)
467 if args is None: # user asked for help (and got it)
Greg Wardfe6462c2000-04-04 01:40:52 +0000468 return
Greg Wardfe6462c2000-04-04 01:40:52 +0000469
Greg Wardd5d8a992000-05-23 01:42:17 +0000470 # Handle the cases of --help as a "global" option, ie.
471 # "setup.py --help" and "setup.py --help command ...". For the
472 # former, we show global options (--verbose, --dry-run, etc.)
473 # and display-only options (--name, --version, etc.); for the
474 # latter, we omit the display-only options and show help for
475 # each command listed on the command line.
Greg Wardfe6462c2000-04-04 01:40:52 +0000476 if self.help:
Greg Wardd5d8a992000-05-23 01:42:17 +0000477 self._show_help(parser,
478 display_options=len(self.commands) == 0,
479 commands=self.commands)
Greg Wardfe6462c2000-04-04 01:40:52 +0000480 return
481
482 # Oops, no commands found -- an end-user error
483 if not self.commands:
484 raise DistutilsArgError, "no commands supplied"
485
486 # All is well: return true
487 return 1
488
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000489 def _get_toplevel_options(self):
Fred Draked04573f2004-08-03 16:37:40 +0000490 """Return the non-display options recognized at the top level.
491
492 This includes options that are recognized *only* at the top
493 level as well as options recognized for commands.
494 """
495 return self.global_options + [
496 ("command-packages=", None,
497 "list of packages that provide distutils commands"),
498 ]
499
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000500 def _parse_command_opts(self, parser, args):
Greg Wardd5d8a992000-05-23 01:42:17 +0000501 """Parse the command-line options for a single command.
502 'parser' must be a FancyGetopt instance; 'args' must be the list
503 of arguments, starting with the current command (whose options
504 we are about to parse). Returns a new version of 'args' with
505 the next command at the front of the list; will be the empty
506 list if there are no more commands on the command line. Returns
507 None if the user asked for help on this command.
508 """
509 # late import because of mutual dependence between these modules
510 from distutils.cmd import Command
511
512 # Pull the current command from the head of the command line
513 command = args[0]
Greg Wardfd7b91e2000-09-26 01:52:25 +0000514 if not command_re.match(command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000515 raise SystemExit, "invalid command name '%s'" % command
Greg Wardfd7b91e2000-09-26 01:52:25 +0000516 self.commands.append(command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000517
518 # Dig up the command class that implements this command, so we
519 # 1) know that it's a valid command, and 2) know which options
520 # it takes.
521 try:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000522 cmd_class = self.get_command_class(command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000523 except DistutilsModuleError, msg:
524 raise DistutilsArgError, msg
525
526 # Require that the command class be derived from Command -- want
527 # to be sure that the basic "command" interface is implemented.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000528 if not issubclass(cmd_class, Command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000529 raise DistutilsClassError, \
530 "command class %s must subclass Command" % cmd_class
531
532 # Also make sure that the command object provides a list of its
533 # known options.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000534 if not (hasattr(cmd_class, 'user_options') and
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000535 isinstance(cmd_class.user_options, list)):
Greg Wardd5d8a992000-05-23 01:42:17 +0000536 raise DistutilsClassError, \
537 ("command class %s must provide " +
538 "'user_options' attribute (a list of tuples)") % \
539 cmd_class
540
541 # If the command class has a list of negative alias options,
542 # merge it in with the global negative aliases.
543 negative_opt = self.negative_opt
Greg Wardfd7b91e2000-09-26 01:52:25 +0000544 if hasattr(cmd_class, 'negative_opt'):
Antoine Pitrouf5413782009-05-15 17:27:30 +0000545 negative_opt = negative_opt.copy()
Greg Wardfd7b91e2000-09-26 01:52:25 +0000546 negative_opt.update(cmd_class.negative_opt)
Greg Wardd5d8a992000-05-23 01:42:17 +0000547
Greg Wardfa9ff762000-10-14 04:06:40 +0000548 # Check for help_options in command class. They have a different
549 # format (tuple of four) so we need to preprocess them here.
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000550 if (hasattr(cmd_class, 'help_options') and
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000551 isinstance(cmd_class.help_options, list)):
Greg Ward2ff78872000-06-24 00:23:20 +0000552 help_options = fix_help_options(cmd_class.help_options)
553 else:
Greg Ward55fced32000-06-24 01:22:41 +0000554 help_options = []
Greg Ward2ff78872000-06-24 00:23:20 +0000555
Greg Ward9d17a7a2000-06-07 03:00:06 +0000556
Greg Wardd5d8a992000-05-23 01:42:17 +0000557 # All commands support the global options too, just by adding
558 # in 'global_options'.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000559 parser.set_option_table(self.global_options +
560 cmd_class.user_options +
561 help_options)
562 parser.set_negative_aliases(negative_opt)
563 (args, opts) = parser.getopt(args[1:])
Greg Ward47460772000-05-23 03:47:35 +0000564 if hasattr(opts, 'help') and opts.help:
Greg Wardd5d8a992000-05-23 01:42:17 +0000565 self._show_help(parser, display_options=0, commands=[cmd_class])
566 return
567
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000568 if (hasattr(cmd_class, 'help_options') and
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000569 isinstance(cmd_class.help_options, list)):
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000570 help_option_found=0
571 for (help_option, short, desc, func) in cmd_class.help_options:
572 if hasattr(opts, parser.get_attr_name(help_option)):
573 help_option_found=1
Benjamin Petersonde055992009-10-09 22:05:45 +0000574 if hasattr(func, '__call__'):
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000575 func()
Greg Ward55fced32000-06-24 01:22:41 +0000576 else:
Fred Drake981a1782001-08-10 18:59:30 +0000577 raise DistutilsClassError(
Walter Dörwald70a6b492004-02-12 17:35:32 +0000578 "invalid help function %r for help option '%s': "
Fred Drake981a1782001-08-10 18:59:30 +0000579 "must be a callable object (function, etc.)"
Walter Dörwald70a6b492004-02-12 17:35:32 +0000580 % (func, help_option))
Greg Ward55fced32000-06-24 01:22:41 +0000581
Fred Drakeb94b8492001-12-06 20:51:35 +0000582 if help_option_found:
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000583 return
Greg Ward9d17a7a2000-06-07 03:00:06 +0000584
Greg Wardd5d8a992000-05-23 01:42:17 +0000585 # Put the options from the command-line into their official
586 # holding pen, the 'command_options' dictionary.
Greg Ward0e48cfd2000-05-26 01:00:15 +0000587 opt_dict = self.get_option_dict(command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000588 for (name, value) in vars(opts).items():
Greg Ward0e48cfd2000-05-26 01:00:15 +0000589 opt_dict[name] = ("command line", value)
Greg Wardd5d8a992000-05-23 01:42:17 +0000590
591 return args
592
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000593 def finalize_options(self):
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000594 """Set final values for all the options on the Distribution
595 instance, analogous to the .finalize_options() method of Command
596 objects.
597 """
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000598 for attr in ('keywords', 'platforms'):
599 value = getattr(self.metadata, attr)
600 if value is None:
601 continue
602 if isinstance(value, str):
603 value = [elm.strip() for elm in value.split(',')]
604 setattr(self.metadata, attr, value)
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000605
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000606 def _show_help(self, parser, global_options=1, display_options=1,
607 commands=[]):
Greg Wardd5d8a992000-05-23 01:42:17 +0000608 """Show help for the setup script command-line in the form of
609 several lists of command-line options. 'parser' should be a
610 FancyGetopt instance; do not expect it to be returned in the
611 same state, as its option table will be reset to make it
612 generate the correct help text.
613
614 If 'global_options' is true, lists the global options:
615 --verbose, --dry-run, etc. If 'display_options' is true, lists
616 the "display-only" options: --name, --version, etc. Finally,
617 lists per-command help for every command name or command class
618 in 'commands'.
619 """
620 # late import because of mutual dependence between these modules
Greg Ward9821bf42000-08-29 01:15:18 +0000621 from distutils.core import gen_usage
Greg Wardd5d8a992000-05-23 01:42:17 +0000622 from distutils.cmd import Command
623
624 if global_options:
Fred Draked04573f2004-08-03 16:37:40 +0000625 if display_options:
626 options = self._get_toplevel_options()
627 else:
628 options = self.global_options
629 parser.set_option_table(options)
Martin v. Löwis8ed338a2005-03-03 08:12:27 +0000630 parser.print_help(self.common_usage + "\nGlobal options:")
Tarek Ziadécd947e02009-07-04 02:59:19 +0000631 print('')
Greg Wardd5d8a992000-05-23 01:42:17 +0000632
633 if display_options:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000634 parser.set_option_table(self.display_options)
635 parser.print_help(
Greg Wardd5d8a992000-05-23 01:42:17 +0000636 "Information display options (just display " +
637 "information, ignore any commands)")
Tarek Ziadécd947e02009-07-04 02:59:19 +0000638 print('')
Greg Wardd5d8a992000-05-23 01:42:17 +0000639
640 for command in self.commands:
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000641 if isinstance(command, type) and issubclass(command, Command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000642 klass = command
643 else:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000644 klass = self.get_command_class(command)
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000645 if (hasattr(klass, 'help_options') and
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000646 isinstance(klass.help_options, list)):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000647 parser.set_option_table(klass.user_options +
648 fix_help_options(klass.help_options))
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000649 else:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000650 parser.set_option_table(klass.user_options)
651 parser.print_help("Options for '%s' command:" % klass.__name__)
Tarek Ziadécd947e02009-07-04 02:59:19 +0000652 print('')
Greg Wardd5d8a992000-05-23 01:42:17 +0000653
Tarek Ziadécd947e02009-07-04 02:59:19 +0000654 print(gen_usage(self.script_name))
Greg Wardd5d8a992000-05-23 01:42:17 +0000655
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000656 def handle_display_options(self, option_order):
Greg Ward82715e12000-04-21 02:28:14 +0000657 """If there were any non-global "display-only" options
Greg Wardd5d8a992000-05-23 01:42:17 +0000658 (--help-commands or the metadata display options) on the command
659 line, display the requested info and return true; else return
660 false.
661 """
Greg Ward9821bf42000-08-29 01:15:18 +0000662 from distutils.core import gen_usage
Greg Ward82715e12000-04-21 02:28:14 +0000663
664 # User just wants a list of commands -- we'll print it out and stop
665 # processing now (ie. if they ran "setup --help-commands foo bar",
666 # we ignore "foo bar").
667 if self.help_commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000668 self.print_commands()
Tarek Ziadécd947e02009-07-04 02:59:19 +0000669 print('')
670 print(gen_usage(self.script_name))
Greg Ward82715e12000-04-21 02:28:14 +0000671 return 1
672
673 # If user supplied any of the "display metadata" options, then
674 # display that metadata in the order in which the user supplied the
675 # metadata options.
676 any_display_options = 0
677 is_display_option = {}
678 for option in self.display_options:
679 is_display_option[option[0]] = 1
680
681 for (opt, val) in option_order:
682 if val and is_display_option.get(opt):
Greg Ward2f2b6c62000-09-25 01:58:07 +0000683 opt = translate_longopt(opt)
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000684 value = getattr(self.metadata, "get_"+opt)()
685 if opt in ['keywords', 'platforms']:
Tarek Ziadécd947e02009-07-04 02:59:19 +0000686 print(','.join(value))
Fred Drakedb7b0022005-03-20 22:19:47 +0000687 elif opt in ('classifiers', 'provides', 'requires',
688 'obsoletes'):
Tarek Ziadécd947e02009-07-04 02:59:19 +0000689 print('\n'.join(value))
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000690 else:
Tarek Ziadécd947e02009-07-04 02:59:19 +0000691 print(value)
Greg Ward82715e12000-04-21 02:28:14 +0000692 any_display_options = 1
693
694 return any_display_options
695
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000696 def print_command_list(self, commands, header, max_length):
Greg Wardfe6462c2000-04-04 01:40:52 +0000697 """Print a subset of the list of all commands -- used by
Greg Wardd5d8a992000-05-23 01:42:17 +0000698 'print_commands()'.
699 """
Tarek Ziadécd947e02009-07-04 02:59:19 +0000700 print(header + ":")
Greg Wardfe6462c2000-04-04 01:40:52 +0000701
702 for cmd in commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000703 klass = self.cmdclass.get(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000704 if not klass:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000705 klass = self.get_command_class(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000706 try:
707 description = klass.description
708 except AttributeError:
709 description = "(no description available)"
710
Tarek Ziadécd947e02009-07-04 02:59:19 +0000711 print(" %-*s %s" % (max_length, cmd, description))
Greg Wardfe6462c2000-04-04 01:40:52 +0000712
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000713 def print_commands(self):
Greg Wardd5d8a992000-05-23 01:42:17 +0000714 """Print out a help message listing all available commands with a
715 description of each. The list is divided into "standard commands"
716 (listed in distutils.command.__all__) and "extra commands"
717 (mentioned in self.cmdclass, but not a standard command). The
718 descriptions come from the command class attribute
719 'description'.
720 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000721 import distutils.command
722 std_commands = distutils.command.__all__
723 is_std = {}
724 for cmd in std_commands:
725 is_std[cmd] = 1
726
727 extra_commands = []
728 for cmd in self.cmdclass.keys():
729 if not is_std.get(cmd):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000730 extra_commands.append(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000731
732 max_length = 0
733 for cmd in (std_commands + extra_commands):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000734 if len(cmd) > max_length:
735 max_length = len(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000736
Greg Wardfd7b91e2000-09-26 01:52:25 +0000737 self.print_command_list(std_commands,
738 "Standard commands",
739 max_length)
Greg Wardfe6462c2000-04-04 01:40:52 +0000740 if extra_commands:
741 print
Greg Wardfd7b91e2000-09-26 01:52:25 +0000742 self.print_command_list(extra_commands,
743 "Extra commands",
744 max_length)
Greg Wardfe6462c2000-04-04 01:40:52 +0000745
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000746 def get_command_list(self):
Greg Wardf6fc8752000-11-11 02:47:11 +0000747 """Get a list of (command, description) tuples.
748 The list is divided into "standard commands" (listed in
749 distutils.command.__all__) and "extra commands" (mentioned in
750 self.cmdclass, but not a standard command). The descriptions come
751 from the command class attribute 'description'.
752 """
753 # Currently this is only used on Mac OS, for the Mac-only GUI
754 # Distutils interface (by Jack Jansen)
755
756 import distutils.command
757 std_commands = distutils.command.__all__
758 is_std = {}
759 for cmd in std_commands:
760 is_std[cmd] = 1
761
762 extra_commands = []
763 for cmd in self.cmdclass.keys():
764 if not is_std.get(cmd):
765 extra_commands.append(cmd)
766
767 rv = []
768 for cmd in (std_commands + extra_commands):
769 klass = self.cmdclass.get(cmd)
770 if not klass:
771 klass = self.get_command_class(cmd)
772 try:
773 description = klass.description
774 except AttributeError:
775 description = "(no description available)"
776 rv.append((cmd, description))
777 return rv
Greg Wardfe6462c2000-04-04 01:40:52 +0000778
779 # -- Command class/object methods ----------------------------------
780
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000781 def get_command_packages(self):
Fred Draked04573f2004-08-03 16:37:40 +0000782 """Return a list of packages from which commands are loaded."""
783 pkgs = self.command_packages
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000784 if not isinstance(pkgs, list):
785 if pkgs is None:
786 pkgs = ''
787 pkgs = [pkg.strip() for pkg in pkgs.split(',') if pkg != '']
Fred Draked04573f2004-08-03 16:37:40 +0000788 if "distutils.command" not in pkgs:
789 pkgs.insert(0, "distutils.command")
790 self.command_packages = pkgs
791 return pkgs
792
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000793 def get_command_class(self, command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000794 """Return the class that implements the Distutils command named by
795 'command'. First we check the 'cmdclass' dictionary; if the
796 command is mentioned there, we fetch the class object from the
797 dictionary and return it. Otherwise we load the command module
798 ("distutils.command." + command) and fetch the command class from
799 the module. The loaded class is also stored in 'cmdclass'
800 to speed future calls to 'get_command_class()'.
Greg Wardfe6462c2000-04-04 01:40:52 +0000801
Gregory P. Smith14263542000-05-12 00:41:33 +0000802 Raises DistutilsModuleError if the expected module could not be
Greg Wardd5d8a992000-05-23 01:42:17 +0000803 found, or if that module does not define the expected class.
804 """
805 klass = self.cmdclass.get(command)
806 if klass:
807 return klass
Greg Wardfe6462c2000-04-04 01:40:52 +0000808
Fred Draked04573f2004-08-03 16:37:40 +0000809 for pkgname in self.get_command_packages():
810 module_name = "%s.%s" % (pkgname, command)
811 klass_name = command
Greg Wardfe6462c2000-04-04 01:40:52 +0000812
Fred Draked04573f2004-08-03 16:37:40 +0000813 try:
814 __import__ (module_name)
815 module = sys.modules[module_name]
816 except ImportError:
817 continue
Greg Wardfe6462c2000-04-04 01:40:52 +0000818
Fred Draked04573f2004-08-03 16:37:40 +0000819 try:
820 klass = getattr(module, klass_name)
821 except AttributeError:
822 raise DistutilsModuleError, \
823 "invalid command '%s' (no class '%s' in module '%s')" \
824 % (command, klass_name, module_name)
Greg Wardfe6462c2000-04-04 01:40:52 +0000825
Fred Draked04573f2004-08-03 16:37:40 +0000826 self.cmdclass[command] = klass
827 return klass
828
829 raise DistutilsModuleError("invalid command '%s'" % command)
830
Greg Wardfe6462c2000-04-04 01:40:52 +0000831
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000832 def get_command_obj(self, command, create=1):
Greg Wardd5d8a992000-05-23 01:42:17 +0000833 """Return the command object for 'command'. Normally this object
Greg Ward612eb9f2000-07-27 02:13:20 +0000834 is cached on a previous call to 'get_command_obj()'; if no command
Greg Wardd5d8a992000-05-23 01:42:17 +0000835 object for 'command' is in the cache, then we either create and
836 return it (if 'create' is true) or return None.
837 """
838 cmd_obj = self.command_obj.get(command)
Greg Wardfe6462c2000-04-04 01:40:52 +0000839 if not cmd_obj and create:
Greg Ward2bd3f422000-06-02 01:59:33 +0000840 if DEBUG:
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000841 self.announce("Distribution.get_command_obj(): " \
842 "creating '%s' command object" % command)
Greg Ward47460772000-05-23 03:47:35 +0000843
Greg Wardd5d8a992000-05-23 01:42:17 +0000844 klass = self.get_command_class(command)
Greg Ward47460772000-05-23 03:47:35 +0000845 cmd_obj = self.command_obj[command] = klass(self)
846 self.have_run[command] = 0
847
848 # Set any options that were supplied in config files
849 # or on the command line. (NB. support for error
850 # reporting is lame here: any errors aren't reported
851 # until 'finalize_options()' is called, which means
852 # we won't report the source of the error.)
853 options = self.command_options.get(command)
854 if options:
Greg Wardc32d9a62000-05-28 23:53:06 +0000855 self._set_command_options(cmd_obj, options)
Greg Wardfe6462c2000-04-04 01:40:52 +0000856
857 return cmd_obj
858
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000859 def _set_command_options(self, command_obj, option_dict=None):
Greg Wardc32d9a62000-05-28 23:53:06 +0000860 """Set the options for 'command_obj' from 'option_dict'. Basically
861 this means copying elements of a dictionary ('option_dict') to
862 attributes of an instance ('command').
863
Greg Wardceb9e222000-09-25 01:23:52 +0000864 'command_obj' must be a Command instance. If 'option_dict' is not
Greg Wardc32d9a62000-05-28 23:53:06 +0000865 supplied, uses the standard option dictionary for this command
866 (from 'self.command_options').
867 """
Greg Wardc32d9a62000-05-28 23:53:06 +0000868 command_name = command_obj.get_command_name()
869 if option_dict is None:
870 option_dict = self.get_option_dict(command_name)
871
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000872 if DEBUG:
873 self.announce(" setting options for '%s' command:" % command_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000874 for (option, (source, value)) in option_dict.items():
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000875 if DEBUG:
876 self.announce(" %s = %s (from %s)" % (option, value,
877 source))
Greg Wardceb9e222000-09-25 01:23:52 +0000878 try:
Greg Ward2f2b6c62000-09-25 01:58:07 +0000879 bool_opts = map(translate_longopt, command_obj.boolean_options)
Greg Wardceb9e222000-09-25 01:23:52 +0000880 except AttributeError:
881 bool_opts = []
882 try:
883 neg_opt = command_obj.negative_opt
884 except AttributeError:
885 neg_opt = {}
886
887 try:
Tarek Ziadéc01cbc42009-06-01 22:22:13 +0000888 is_string = isinstance(value, str)
Guido van Rossum8bc09652008-02-21 18:18:37 +0000889 if option in neg_opt and is_string:
Greg Wardceb9e222000-09-25 01:23:52 +0000890 setattr(command_obj, neg_opt[option], not strtobool(value))
Greg Ward2c08cf02000-09-27 00:15:37 +0000891 elif option in bool_opts and is_string:
Greg Wardceb9e222000-09-25 01:23:52 +0000892 setattr(command_obj, option, strtobool(value))
893 elif hasattr(command_obj, option):
894 setattr(command_obj, option, value)
895 else:
896 raise DistutilsOptionError, \
897 ("error in %s: command '%s' has no such option '%s'"
898 % (source, command_name, option))
899 except ValueError, msg:
900 raise DistutilsOptionError, msg
Greg Wardc32d9a62000-05-28 23:53:06 +0000901
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000902 def reinitialize_command(self, command, reinit_subcommands=0):
Greg Wardc32d9a62000-05-28 23:53:06 +0000903 """Reinitializes a command to the state it was in when first
904 returned by 'get_command_obj()': ie., initialized but not yet
Greg Ward7d9c7052000-06-28 01:25:27 +0000905 finalized. This provides the opportunity to sneak option
Greg Wardc32d9a62000-05-28 23:53:06 +0000906 values in programmatically, overriding or supplementing
907 user-supplied values from the config files and command line.
908 You'll have to re-finalize the command object (by calling
909 'finalize_options()' or 'ensure_finalized()') before using it for
Fred Drakeb94b8492001-12-06 20:51:35 +0000910 real.
Greg Wardc32d9a62000-05-28 23:53:06 +0000911
Greg Wardf449ea52000-09-16 15:23:28 +0000912 'command' should be a command name (string) or command object. If
913 'reinit_subcommands' is true, also reinitializes the command's
914 sub-commands, as declared by the 'sub_commands' class attribute (if
915 it has one). See the "install" command for an example. Only
916 reinitializes the sub-commands that actually matter, ie. those
917 whose test predicates return true.
918
Greg Wardc32d9a62000-05-28 23:53:06 +0000919 Returns the reinitialized command object.
920 """
921 from distutils.cmd import Command
922 if not isinstance(command, Command):
923 command_name = command
924 command = self.get_command_obj(command_name)
925 else:
926 command_name = command.get_command_name()
927
928 if not command.finalized:
Greg Ward282c7a02000-06-01 01:09:47 +0000929 return command
Greg Wardc32d9a62000-05-28 23:53:06 +0000930 command.initialize_options()
931 command.finalized = 0
Greg Ward43955c92000-06-06 02:52:36 +0000932 self.have_run[command_name] = 0
Greg Wardc32d9a62000-05-28 23:53:06 +0000933 self._set_command_options(command)
Greg Wardf449ea52000-09-16 15:23:28 +0000934
Greg Wardf449ea52000-09-16 15:23:28 +0000935 if reinit_subcommands:
Greg Wardf449ea52000-09-16 15:23:28 +0000936 for sub in command.get_sub_commands():
Fred Drakeb94b8492001-12-06 20:51:35 +0000937 self.reinitialize_command(sub, reinit_subcommands)
Greg Wardf449ea52000-09-16 15:23:28 +0000938
Greg Wardc32d9a62000-05-28 23:53:06 +0000939 return command
940
Greg Wardfe6462c2000-04-04 01:40:52 +0000941 # -- Methods that operate on the Distribution ----------------------
942
Tarek Ziadé63f17382009-07-04 02:02:41 +0000943 def announce(self, msg, level=log.INFO):
944 log.log(level, msg)
Greg Wardfe6462c2000-04-04 01:40:52 +0000945
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000946 def run_commands(self):
Greg Ward82715e12000-04-21 02:28:14 +0000947 """Run each command that was seen on the setup script command line.
Greg Wardd5d8a992000-05-23 01:42:17 +0000948 Uses the list of commands found and cache of command objects
Greg Wardfd7b91e2000-09-26 01:52:25 +0000949 created by 'get_command_obj()'.
950 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000951 for cmd in self.commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000952 self.run_command(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000953
Greg Wardfe6462c2000-04-04 01:40:52 +0000954 # -- Methods that operate on its Commands --------------------------
955
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000956 def run_command(self, command):
Greg Wardfe6462c2000-04-04 01:40:52 +0000957 """Do whatever it takes to run a command (including nothing at all,
Greg Wardd5d8a992000-05-23 01:42:17 +0000958 if the command has already been run). Specifically: if we have
959 already created and run the command named by 'command', return
960 silently without doing anything. If the command named by 'command'
961 doesn't even have a command object yet, create one. Then invoke
962 'run()' on that command object (or an existing one).
963 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000964 # Already been here, done that? then return silently.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000965 if self.have_run.get(command):
Greg Wardfe6462c2000-04-04 01:40:52 +0000966 return
967
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000968 log.info("running %s", command)
Greg Wardfd7b91e2000-09-26 01:52:25 +0000969 cmd_obj = self.get_command_obj(command)
970 cmd_obj.ensure_finalized()
971 cmd_obj.run()
Greg Wardfe6462c2000-04-04 01:40:52 +0000972 self.have_run[command] = 1
973
974
Greg Wardfe6462c2000-04-04 01:40:52 +0000975 # -- Distribution query methods ------------------------------------
976
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000977 def has_pure_modules(self):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000978 return len(self.packages or self.py_modules or []) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000979
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000980 def has_ext_modules(self):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000981 return self.ext_modules and len(self.ext_modules) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000982
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000983 def has_c_libraries(self):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000984 return self.libraries and len(self.libraries) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000985
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000986 def has_modules(self):
Greg Wardfe6462c2000-04-04 01:40:52 +0000987 return self.has_pure_modules() or self.has_ext_modules()
988
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000989 def has_headers(self):
Greg Ward51def7d2000-05-27 01:36:14 +0000990 return self.headers and len(self.headers) > 0
991
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000992 def has_scripts(self):
Greg Ward44a61bb2000-05-20 15:06:48 +0000993 return self.scripts and len(self.scripts) > 0
994
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000995 def has_data_files(self):
Greg Ward44a61bb2000-05-20 15:06:48 +0000996 return self.data_files and len(self.data_files) > 0
997
Tarek Ziadéae6acfc2009-05-16 18:29:40 +0000998 def is_pure(self):
Greg Wardfe6462c2000-04-04 01:40:52 +0000999 return (self.has_pure_modules() and
1000 not self.has_ext_modules() and
1001 not self.has_c_libraries())
1002
Greg Ward82715e12000-04-21 02:28:14 +00001003 # -- Metadata query methods ----------------------------------------
1004
1005 # If you're looking for 'get_name()', 'get_version()', and so forth,
1006 # they are defined in a sneaky way: the constructor binds self.get_XXX
1007 # to self.metadata.get_XXX. The actual code is in the
1008 # DistributionMetadata class, below.
1009
Greg Ward82715e12000-04-21 02:28:14 +00001010class DistributionMetadata:
1011 """Dummy class to hold the distribution meta-data: name, version,
Greg Wardfd7b91e2000-09-26 01:52:25 +00001012 author, and so forth.
1013 """
Greg Ward82715e12000-04-21 02:28:14 +00001014
Neil Schemenauera8aefe52001-09-03 15:47:21 +00001015 _METHOD_BASENAMES = ("name", "version", "author", "author_email",
1016 "maintainer", "maintainer_email", "url",
1017 "license", "description", "long_description",
1018 "keywords", "platforms", "fullname", "contact",
Andrew M. Kuchlinga52b8522003-03-03 20:07:27 +00001019 "contact_email", "license", "classifiers",
Fred Drakedb7b0022005-03-20 22:19:47 +00001020 "download_url",
1021 # PEP 314
1022 "provides", "requires", "obsoletes",
1023 )
Neil Schemenauera8aefe52001-09-03 15:47:21 +00001024
Tarek Ziadéa939ecd2009-12-08 08:56:49 +00001025 def __init__(self, path=None):
1026 if path is not None:
1027 self.read_pkg_file(open(path))
1028 else:
1029 self.name = None
1030 self.version = None
1031 self.author = None
1032 self.author_email = None
1033 self.maintainer = None
1034 self.maintainer_email = None
1035 self.url = None
1036 self.license = None
1037 self.description = None
1038 self.long_description = None
1039 self.keywords = None
1040 self.platforms = None
1041 self.classifiers = None
1042 self.download_url = None
1043 # PEP 314
1044 self.provides = None
1045 self.requires = None
1046 self.obsoletes = None
1047
1048 def read_pkg_file(self, file):
1049 """Reads the metadata values from a file object."""
Tarek Ziadé4b7f9432009-12-08 09:39:51 +00001050 msg = message_from_file(file)
1051
1052 def _read_field(name):
1053 value = msg[name]
1054 if value == 'UNKNOWN':
1055 return None
1056 return value
1057
1058 def _read_list(name):
1059 values = msg.get_all(name, None)
1060 if values == []:
1061 return None
1062 return values
1063
Tarek Ziadéa939ecd2009-12-08 08:56:49 +00001064 metadata_version = msg['metadata-version']
Tarek Ziadé4b7f9432009-12-08 09:39:51 +00001065 self.name = _read_field('name')
1066 self.version = _read_field('version')
1067 self.description = _read_field('summary')
Tarek Ziadéa939ecd2009-12-08 08:56:49 +00001068 # we are filling author only.
Tarek Ziadé4b7f9432009-12-08 09:39:51 +00001069 self.author = _read_field('author')
Greg Ward82715e12000-04-21 02:28:14 +00001070 self.maintainer = None
Tarek Ziadé4b7f9432009-12-08 09:39:51 +00001071 self.author_email = _read_field('author-email')
Greg Ward82715e12000-04-21 02:28:14 +00001072 self.maintainer_email = None
Tarek Ziadé4b7f9432009-12-08 09:39:51 +00001073 self.url = _read_field('home-page')
1074 self.license = _read_field('license')
Tarek Ziadéa939ecd2009-12-08 08:56:49 +00001075
1076 if 'download-url' in msg:
Tarek Ziadé4b7f9432009-12-08 09:39:51 +00001077 self.download_url = _read_field('download-url')
Tarek Ziadéa939ecd2009-12-08 08:56:49 +00001078 else:
1079 self.download_url = None
1080
Tarek Ziadé4b7f9432009-12-08 09:39:51 +00001081 self.long_description = _read_field('description')
1082 self.description = _read_field('summary')
Tarek Ziadéa939ecd2009-12-08 08:56:49 +00001083
1084 if 'keywords' in msg:
Tarek Ziadé4b7f9432009-12-08 09:39:51 +00001085 self.keywords = _read_field('keywords').split(',')
Tarek Ziadéa939ecd2009-12-08 08:56:49 +00001086
Tarek Ziadé4b7f9432009-12-08 09:39:51 +00001087 self.platforms = _read_list('platform')
1088 self.classifiers = _read_list('classifier')
Tarek Ziadéa939ecd2009-12-08 08:56:49 +00001089
1090 # PEP 314 - these fields only exist in 1.1
1091 if metadata_version == '1.1':
Tarek Ziadé4b7f9432009-12-08 09:39:51 +00001092 self.requires = _read_list('requires')
1093 self.provides = _read_list('provides')
1094 self.obsoletes = _read_list('obsoletes')
Tarek Ziadéa939ecd2009-12-08 08:56:49 +00001095 else:
1096 self.requires = None
1097 self.provides = None
1098 self.obsoletes = None
Fred Drakeb94b8492001-12-06 20:51:35 +00001099
Tarek Ziadéae6acfc2009-05-16 18:29:40 +00001100 def write_pkg_info(self, base_dir):
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001101 """Write the PKG-INFO file into the release tree.
1102 """
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001103 pkg_info = open( os.path.join(base_dir, 'PKG-INFO'), 'w')
Fred Drakedb7b0022005-03-20 22:19:47 +00001104 self.write_pkg_file(pkg_info)
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001105 pkg_info.close()
Fred Drakeb94b8492001-12-06 20:51:35 +00001106
Tarek Ziadéae6acfc2009-05-16 18:29:40 +00001107 def write_pkg_file(self, file):
Fred Drakedb7b0022005-03-20 22:19:47 +00001108 """Write the PKG-INFO format data to a file object.
1109 """
1110 version = '1.0'
1111 if self.provides or self.requires or self.obsoletes:
1112 version = '1.1'
1113
Marc-André Lemburgb339b2a2008-09-03 11:13:56 +00001114 self._write_field(file, 'Metadata-Version', version)
1115 self._write_field(file, 'Name', self.get_name())
1116 self._write_field(file, 'Version', self.get_version())
1117 self._write_field(file, 'Summary', self.get_description())
1118 self._write_field(file, 'Home-page', self.get_url())
1119 self._write_field(file, 'Author', self.get_contact())
1120 self._write_field(file, 'Author-email', self.get_contact_email())
1121 self._write_field(file, 'License', self.get_license())
Fred Drakedb7b0022005-03-20 22:19:47 +00001122 if self.download_url:
Marc-André Lemburgb339b2a2008-09-03 11:13:56 +00001123 self._write_field(file, 'Download-URL', self.download_url)
Fred Drakedb7b0022005-03-20 22:19:47 +00001124
Tarek Ziadéc01cbc42009-06-01 22:22:13 +00001125 long_desc = rfc822_escape(self.get_long_description())
Marc-André Lemburgb339b2a2008-09-03 11:13:56 +00001126 self._write_field(file, 'Description', long_desc)
Fred Drakedb7b0022005-03-20 22:19:47 +00001127
Tarek Ziadéc01cbc42009-06-01 22:22:13 +00001128 keywords = ','.join(self.get_keywords())
Fred Drakedb7b0022005-03-20 22:19:47 +00001129 if keywords:
Marc-André Lemburgb339b2a2008-09-03 11:13:56 +00001130 self._write_field(file, 'Keywords', keywords)
Fred Drakedb7b0022005-03-20 22:19:47 +00001131
1132 self._write_list(file, 'Platform', self.get_platforms())
1133 self._write_list(file, 'Classifier', self.get_classifiers())
1134
1135 # PEP 314
1136 self._write_list(file, 'Requires', self.get_requires())
1137 self._write_list(file, 'Provides', self.get_provides())
1138 self._write_list(file, 'Obsoletes', self.get_obsoletes())
1139
Marc-André Lemburgb339b2a2008-09-03 11:13:56 +00001140 def _write_field(self, file, name, value):
Marc-André Lemburgb339b2a2008-09-03 11:13:56 +00001141 if isinstance(value, unicode):
1142 value = value.encode(PKG_INFO_ENCODING)
1143 else:
1144 value = str(value)
1145 file.write('%s: %s\n' % (name, value))
1146
Fred Drakedb7b0022005-03-20 22:19:47 +00001147 def _write_list (self, file, name, values):
1148 for value in values:
Marc-André Lemburgb339b2a2008-09-03 11:13:56 +00001149 self._write_field(file, name, value)
Fred Drakedb7b0022005-03-20 22:19:47 +00001150
Greg Ward82715e12000-04-21 02:28:14 +00001151 # -- Metadata query methods ----------------------------------------
1152
Tarek Ziadéae6acfc2009-05-16 18:29:40 +00001153 def get_name(self):
Greg Wardfe6462c2000-04-04 01:40:52 +00001154 return self.name or "UNKNOWN"
1155
Greg Ward82715e12000-04-21 02:28:14 +00001156 def get_version(self):
Thomas Hellerbcd89752001-12-06 20:44:19 +00001157 return self.version or "0.0.0"
Greg Wardfe6462c2000-04-04 01:40:52 +00001158
Tarek Ziadéae6acfc2009-05-16 18:29:40 +00001159 def get_fullname(self):
Greg Ward82715e12000-04-21 02:28:14 +00001160 return "%s-%s" % (self.get_name(), self.get_version())
1161
1162 def get_author(self):
1163 return self.author or "UNKNOWN"
1164
1165 def get_author_email(self):
1166 return self.author_email or "UNKNOWN"
1167
1168 def get_maintainer(self):
1169 return self.maintainer or "UNKNOWN"
1170
1171 def get_maintainer_email(self):
1172 return self.maintainer_email or "UNKNOWN"
1173
1174 def get_contact(self):
Tarek Ziadéae6acfc2009-05-16 18:29:40 +00001175 return self.maintainer or self.author or "UNKNOWN"
Greg Ward82715e12000-04-21 02:28:14 +00001176
1177 def get_contact_email(self):
Tarek Ziadéae6acfc2009-05-16 18:29:40 +00001178 return self.maintainer_email or self.author_email or "UNKNOWN"
Greg Ward82715e12000-04-21 02:28:14 +00001179
1180 def get_url(self):
1181 return self.url or "UNKNOWN"
1182
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +00001183 def get_license(self):
1184 return self.license or "UNKNOWN"
1185 get_licence = get_license
Fred Drakeb94b8492001-12-06 20:51:35 +00001186
Greg Ward82715e12000-04-21 02:28:14 +00001187 def get_description(self):
1188 return self.description or "UNKNOWN"
Greg Warde5a584e2000-04-26 02:26:55 +00001189
1190 def get_long_description(self):
1191 return self.long_description or "UNKNOWN"
1192
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001193 def get_keywords(self):
1194 return self.keywords or []
1195
1196 def get_platforms(self):
1197 return self.platforms or ["UNKNOWN"]
1198
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +00001199 def get_classifiers(self):
1200 return self.classifiers or []
1201
Andrew M. Kuchling188d85f2003-02-19 14:16:01 +00001202 def get_download_url(self):
1203 return self.download_url or "UNKNOWN"
1204
Fred Drakedb7b0022005-03-20 22:19:47 +00001205 # PEP 314
Fred Drakedb7b0022005-03-20 22:19:47 +00001206 def get_requires(self):
1207 return self.requires or []
1208
1209 def set_requires(self, value):
1210 import distutils.versionpredicate
1211 for v in value:
1212 distutils.versionpredicate.VersionPredicate(v)
1213 self.requires = value
1214
1215 def get_provides(self):
1216 return self.provides or []
1217
1218 def set_provides(self, value):
1219 value = [v.strip() for v in value]
1220 for v in value:
1221 import distutils.versionpredicate
Fred Drake227e8ff2005-03-21 06:36:32 +00001222 distutils.versionpredicate.split_provision(v)
Fred Drakedb7b0022005-03-20 22:19:47 +00001223 self.provides = value
1224
1225 def get_obsoletes(self):
1226 return self.obsoletes or []
1227
1228 def set_obsoletes(self, value):
1229 import distutils.versionpredicate
1230 for v in value:
1231 distutils.versionpredicate.VersionPredicate(v)
1232 self.obsoletes = value
1233
Tarek Ziadéae6acfc2009-05-16 18:29:40 +00001234def fix_help_options(options):
Greg Ward2ff78872000-06-24 00:23:20 +00001235 """Convert a 4-tuple 'help_options' list as found in various command
1236 classes to the 3-tuple form required by FancyGetopt.
1237 """
1238 new_options = []
1239 for help_tuple in options:
1240 new_options.append(help_tuple[0:3])
1241 return new_options