blob: 0b13c1e6c19261f540960f5368eb87891d2d261c [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
Martin v. Löwis5a6601c2004-11-10 22:23:15 +00007# This module should be kept compatible with Python 2.1.
Andrew M. Kuchlingd448f662002-11-19 13:12:28 +00008
Greg Wardfe6462c2000-04-04 01:40:52 +00009__revision__ = "$Id$"
10
Gregory P. Smith14263542000-05-12 00:41:33 +000011import sys, os, string, re
Greg Wardfe6462c2000-04-04 01:40:52 +000012from types import *
13from copy import copy
Andrew M. Kuchlingff4ad9a2002-10-31 13:22:41 +000014
15try:
16 import warnings
Andrew M. Kuchlingccf4e422002-10-31 13:39:33 +000017except ImportError:
Andrew M. Kuchlingff4ad9a2002-10-31 13:22:41 +000018 warnings = None
19
Greg Wardfe6462c2000-04-04 01:40:52 +000020from distutils.errors import *
Greg Ward2f2b6c62000-09-25 01:58:07 +000021from distutils.fancy_getopt import FancyGetopt, translate_longopt
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +000022from distutils.util import check_environ, strtobool, rfc822_escape
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000023from distutils import log
Jeremy Hyltonfcd73532002-09-11 16:31:53 +000024from distutils.debug import DEBUG
Greg Wardfe6462c2000-04-04 01:40:52 +000025
26# 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"),
Greg Wardfe6462c2000-04-04 01:40:52 +000060 ]
Greg Ward82715e12000-04-21 02:28:14 +000061
Martin v. Löwis8ed338a2005-03-03 08:12:27 +000062 # 'common_usage' is a short (2-3 line) string describing the common
63 # usage of the setup script.
64 common_usage = """\
65Common commands: (see '--help-commands' for more)
66
67 setup.py build will build the package underneath 'build/'
68 setup.py install will install the package
69"""
70
Greg Ward82715e12000-04-21 02:28:14 +000071 # options that are not propagated to the commands
72 display_options = [
73 ('help-commands', None,
74 "list all available commands"),
75 ('name', None,
76 "print package name"),
77 ('version', 'V',
78 "print package version"),
79 ('fullname', None,
80 "print <package name>-<version>"),
81 ('author', None,
82 "print the author's name"),
83 ('author-email', None,
84 "print the author's email address"),
85 ('maintainer', None,
86 "print the maintainer's name"),
87 ('maintainer-email', None,
88 "print the maintainer's email address"),
89 ('contact', None,
Greg Wardd5d8a992000-05-23 01:42:17 +000090 "print the maintainer's name if known, else the author's"),
Greg Ward82715e12000-04-21 02:28:14 +000091 ('contact-email', None,
Greg Wardd5d8a992000-05-23 01:42:17 +000092 "print the maintainer's email address if known, else the author's"),
Greg Ward82715e12000-04-21 02:28:14 +000093 ('url', None,
94 "print the URL for this package"),
Greg Ward82715e12000-04-21 02:28:14 +000095 ('license', None,
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +000096 "print the license of the package"),
97 ('licence', None,
98 "alias for --license"),
Greg Ward82715e12000-04-21 02:28:14 +000099 ('description', None,
100 "print the package description"),
Greg Warde5a584e2000-04-26 02:26:55 +0000101 ('long-description', None,
102 "print the long package description"),
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000103 ('platforms', None,
104 "print the list of platforms"),
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +0000105 ('classifiers', None,
106 "print the list of classifiers"),
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000107 ('keywords', None,
108 "print the list of keywords"),
Fred Drakedb7b0022005-03-20 22:19:47 +0000109 ('provides', None,
110 "print the list of packages/modules provided"),
111 ('requires', None,
112 "print the list of packages/modules required"),
113 ('obsoletes', None,
114 "print the list of packages/modules made obsolete")
Greg Ward82715e12000-04-21 02:28:14 +0000115 ]
Greg Ward2f2b6c62000-09-25 01:58:07 +0000116 display_option_names = map(lambda x: translate_longopt(x[0]),
117 display_options)
Greg Ward82715e12000-04-21 02:28:14 +0000118
119 # negative options are options that exclude other options
Greg Wardfe6462c2000-04-04 01:40:52 +0000120 negative_opt = {'quiet': 'verbose'}
121
122
123 # -- Creation/initialization methods -------------------------------
Fred Drakeb94b8492001-12-06 20:51:35 +0000124
Greg Wardfe6462c2000-04-04 01:40:52 +0000125 def __init__ (self, attrs=None):
126 """Construct a new Distribution instance: initialize all the
Greg Ward8ff5a3f2000-06-02 00:44:53 +0000127 attributes of a Distribution, and then use 'attrs' (a dictionary
128 mapping attribute names to values) to assign some of those
129 attributes their "real" values. (Any attributes not mentioned in
130 'attrs' will be assigned to some null value: 0, None, an empty list
131 or dictionary, etc.) Most importantly, initialize the
132 'command_obj' attribute to the empty dictionary; this will be
133 filled in with real command objects by 'parse_command_line()'.
134 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000135
136 # Default values for our command-line options
137 self.verbose = 1
138 self.dry_run = 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000139 self.help = 0
Greg Ward82715e12000-04-21 02:28:14 +0000140 for attr in self.display_option_names:
141 setattr(self, attr, 0)
Greg Wardfe6462c2000-04-04 01:40:52 +0000142
Greg Ward82715e12000-04-21 02:28:14 +0000143 # Store the distribution meta-data (name, version, author, and so
144 # forth) in a separate object -- we're getting to have enough
145 # information here (and enough command-line options) that it's
146 # worth it. Also delegate 'get_XXX()' methods to the 'metadata'
147 # object in a sneaky and underhanded (but efficient!) way.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000148 self.metadata = DistributionMetadata()
Neil Schemenauera8aefe52001-09-03 15:47:21 +0000149 for basename in self.metadata._METHOD_BASENAMES:
Greg Ward4982f982000-04-22 02:52:44 +0000150 method_name = "get_" + basename
151 setattr(self, method_name, getattr(self.metadata, method_name))
Greg Wardfe6462c2000-04-04 01:40:52 +0000152
153 # 'cmdclass' maps command names to class objects, so we
154 # can 1) quickly figure out which class to instantiate when
155 # we need to create a new command object, and 2) have a way
Greg Ward82715e12000-04-21 02:28:14 +0000156 # for the setup script to override command classes
Greg Wardfe6462c2000-04-04 01:40:52 +0000157 self.cmdclass = {}
158
Fred Draked04573f2004-08-03 16:37:40 +0000159 # 'command_packages' is a list of packages in which commands
160 # are searched for. The factory for command 'foo' is expected
161 # to be named 'foo' in the module 'foo' in one of the packages
162 # named here. This list is searched from the left; an error
163 # is raised if no named package provides the command being
164 # searched for. (Always access using get_command_packages().)
165 self.command_packages = None
166
Greg Ward9821bf42000-08-29 01:15:18 +0000167 # 'script_name' and 'script_args' are usually set to sys.argv[0]
168 # and sys.argv[1:], but they can be overridden when the caller is
169 # not necessarily a setup script run from the command-line.
170 self.script_name = None
171 self.script_args = None
172
Greg Wardd5d8a992000-05-23 01:42:17 +0000173 # 'command_options' is where we store command options between
174 # parsing them (from config files, the command-line, etc.) and when
175 # they are actually needed -- ie. when the command in question is
176 # instantiated. It is a dictionary of dictionaries of 2-tuples:
177 # command_options = { command_name : { option : (source, value) } }
Gregory P. Smith14263542000-05-12 00:41:33 +0000178 self.command_options = {}
179
Martin v. Löwis98da5622005-03-23 18:54:36 +0000180 # 'dist_files' is the list of (command, pyversion, file) that
181 # have been created by any dist commands run so far. This is
182 # filled regardless of whether the run is dry or not. pyversion
183 # gives sysconfig.get_python_version() if the dist file is
184 # specific to a Python version, 'any' if it is good for all
185 # Python versions on the target platform, and '' for a source
186 # file. pyversion should not be used to specify minimum or
187 # maximum required Python versions; use the metainfo for that
188 # instead.
Martin v. Löwis55f1bb82005-03-21 20:56:35 +0000189 self.dist_files = []
190
Greg Wardfe6462c2000-04-04 01:40:52 +0000191 # These options are really the business of various commands, rather
192 # than of the Distribution itself. We provide aliases for them in
193 # Distribution as a convenience to the developer.
Greg Wardfe6462c2000-04-04 01:40:52 +0000194 self.packages = None
Fred Drake0eb32a62004-06-11 21:50:33 +0000195 self.package_data = {}
Greg Wardfe6462c2000-04-04 01:40:52 +0000196 self.package_dir = None
197 self.py_modules = None
198 self.libraries = None
Greg Ward51def7d2000-05-27 01:36:14 +0000199 self.headers = None
Greg Wardfe6462c2000-04-04 01:40:52 +0000200 self.ext_modules = None
201 self.ext_package = None
202 self.include_dirs = None
203 self.extra_path = None
Gregory P. Smithb2e3bb32000-05-12 00:52:23 +0000204 self.scripts = None
Gregory P. Smith6a901dd2000-05-13 03:09:50 +0000205 self.data_files = None
Greg Wardfe6462c2000-04-04 01:40:52 +0000206
207 # And now initialize bookkeeping stuff that can't be supplied by
208 # the caller at all. 'command_obj' maps command names to
209 # Command instances -- that's how we enforce that every command
210 # class is a singleton.
211 self.command_obj = {}
212
213 # 'have_run' maps command names to boolean values; it keeps track
214 # of whether we have actually run a particular command, to make it
215 # cheap to "run" a command whenever we think we might need to -- if
216 # it's already been done, no need for expensive filesystem
217 # operations, we just check the 'have_run' dictionary and carry on.
218 # It's only safe to query 'have_run' for a command class that has
219 # been instantiated -- a false value will be inserted when the
220 # command object is created, and replaced with a true value when
Greg Ward612eb9f2000-07-27 02:13:20 +0000221 # the command is successfully run. Thus it's probably best to use
Greg Wardfe6462c2000-04-04 01:40:52 +0000222 # '.get()' rather than a straight lookup.
223 self.have_run = {}
224
225 # Now we'll use the attrs dictionary (ultimately, keyword args from
Greg Ward82715e12000-04-21 02:28:14 +0000226 # the setup script) to possibly override any or all of these
227 # distribution options.
228
Greg Wardfe6462c2000-04-04 01:40:52 +0000229 if attrs:
Greg Wardfe6462c2000-04-04 01:40:52 +0000230 # Pull out the set of command options and work on them
231 # specifically. Note that this order guarantees that aliased
232 # command options will override any supplied redundantly
233 # through the general options dictionary.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000234 options = attrs.get('options')
Greg Wardfe6462c2000-04-04 01:40:52 +0000235 if options:
236 del attrs['options']
237 for (command, cmd_options) in options.items():
Greg Ward0e48cfd2000-05-26 01:00:15 +0000238 opt_dict = self.get_option_dict(command)
239 for (opt, val) in cmd_options.items():
240 opt_dict[opt] = ("setup script", val)
Greg Wardfe6462c2000-04-04 01:40:52 +0000241
Guido van Rossum8bc09652008-02-21 18:18:37 +0000242 if 'licence' in attrs:
Andrew M. Kuchlinga52b8522003-03-03 20:07:27 +0000243 attrs['license'] = attrs['licence']
244 del attrs['licence']
245 msg = "'licence' distribution option is deprecated; use 'license'"
246 if warnings is not None:
247 warnings.warn(msg)
248 else:
249 sys.stderr.write(msg + "\n")
250
Greg Wardfe6462c2000-04-04 01:40:52 +0000251 # Now work on the rest of the attributes. Any attribute that's
252 # not already defined is invalid!
253 for (key,val) in attrs.items():
Fred Drakedb7b0022005-03-20 22:19:47 +0000254 if hasattr(self.metadata, "set_" + key):
255 getattr(self.metadata, "set_" + key)(val)
256 elif hasattr(self.metadata, key):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000257 setattr(self.metadata, key, val)
258 elif hasattr(self, key):
259 setattr(self, key, val)
Anthony Baxter73cc8472004-10-13 13:22:34 +0000260 else:
Andrew M. Kuchlingff4ad9a2002-10-31 13:22:41 +0000261 msg = "Unknown distribution option: %s" % repr(key)
262 if warnings is not None:
263 warnings.warn(msg)
264 else:
265 sys.stderr.write(msg + "\n")
Greg Wardfe6462c2000-04-04 01:40:52 +0000266
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000267 self.finalize_options()
Fred Drakeb94b8492001-12-06 20:51:35 +0000268
Greg Wardfe6462c2000-04-04 01:40:52 +0000269 # __init__ ()
270
271
Greg Ward0e48cfd2000-05-26 01:00:15 +0000272 def get_option_dict (self, command):
273 """Get the option dictionary for a given command. If that
274 command's option dictionary hasn't been created yet, then create it
275 and return the new dictionary; otherwise, return the existing
276 option dictionary.
277 """
278
279 dict = self.command_options.get(command)
280 if dict is None:
281 dict = self.command_options[command] = {}
282 return dict
283
284
Greg Wardc32d9a62000-05-28 23:53:06 +0000285 def dump_option_dicts (self, header=None, commands=None, indent=""):
286 from pprint import pformat
287
288 if commands is None: # dump all command option dicts
289 commands = self.command_options.keys()
290 commands.sort()
291
292 if header is not None:
293 print indent + header
294 indent = indent + " "
295
296 if not commands:
297 print indent + "no commands known yet"
298 return
299
300 for cmd_name in commands:
301 opt_dict = self.command_options.get(cmd_name)
302 if opt_dict is None:
303 print indent + "no option dict for '%s' command" % cmd_name
304 else:
305 print indent + "option dict for '%s' command:" % cmd_name
306 out = pformat(opt_dict)
307 for line in string.split(out, "\n"):
308 print indent + " " + line
309
310 # dump_option_dicts ()
Fred Drakeb94b8492001-12-06 20:51:35 +0000311
Greg Wardc32d9a62000-05-28 23:53:06 +0000312
313
Greg Wardd5d8a992000-05-23 01:42:17 +0000314 # -- Config file finding/parsing methods ---------------------------
315
Gregory P. Smith14263542000-05-12 00:41:33 +0000316 def find_config_files (self):
317 """Find as many configuration files as should be processed for this
318 platform, and return a list of filenames in the order in which they
319 should be parsed. The filenames returned are guaranteed to exist
320 (modulo nasty race conditions).
321
Andrew M. Kuchlingd303b612001-12-06 16:32:05 +0000322 There are three possible config files: distutils.cfg in the
323 Distutils installation directory (ie. where the top-level
324 Distutils __inst__.py file lives), a file in the user's home
325 directory named .pydistutils.cfg on Unix and pydistutils.cfg
326 on Windows/Mac, and setup.cfg in the current directory.
Greg Wardd5d8a992000-05-23 01:42:17 +0000327 """
Gregory P. Smith14263542000-05-12 00:41:33 +0000328 files = []
Greg Wardacf3f6a2000-06-07 02:26:19 +0000329 check_environ()
Gregory P. Smith14263542000-05-12 00:41:33 +0000330
Greg Ward11696872000-06-07 02:29:03 +0000331 # Where to look for the system-wide Distutils config file
332 sys_dir = os.path.dirname(sys.modules['distutils'].__file__)
333
334 # Look for the system config file
335 sys_file = os.path.join(sys_dir, "distutils.cfg")
Greg Wardacf3f6a2000-06-07 02:26:19 +0000336 if os.path.isfile(sys_file):
337 files.append(sys_file)
Gregory P. Smith14263542000-05-12 00:41:33 +0000338
Greg Ward11696872000-06-07 02:29:03 +0000339 # What to call the per-user config file
340 if os.name == 'posix':
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000341 user_filename = ".pydistutils.cfg"
342 else:
343 user_filename = "pydistutils.cfg"
Greg Wardfa9ff762000-10-14 04:06:40 +0000344
Greg Ward11696872000-06-07 02:29:03 +0000345 # And look for the user config file
Andrew M. Kuchlingaac5c862008-05-11 14:00:00 +0000346 user_file = os.path.join(os.path.expanduser('~'), user_filename)
347 if os.path.isfile(user_file):
348 files.append(user_file)
Gregory P. Smith14263542000-05-12 00:41:33 +0000349
Gregory P. Smith14263542000-05-12 00:41:33 +0000350 # All platforms support local setup.cfg
351 local_file = "setup.cfg"
352 if os.path.isfile(local_file):
353 files.append(local_file)
354
355 return files
356
357 # find_config_files ()
358
359
360 def parse_config_files (self, filenames=None):
361
362 from ConfigParser import ConfigParser
363
364 if filenames is None:
365 filenames = self.find_config_files()
366
Greg Ward2bd3f422000-06-02 01:59:33 +0000367 if DEBUG: print "Distribution.parse_config_files():"
Greg Ward47460772000-05-23 03:47:35 +0000368
Gregory P. Smith14263542000-05-12 00:41:33 +0000369 parser = ConfigParser()
Greg Wardd5d8a992000-05-23 01:42:17 +0000370 for filename in filenames:
Greg Ward2bd3f422000-06-02 01:59:33 +0000371 if DEBUG: print " reading", filename
Greg Wardd5d8a992000-05-23 01:42:17 +0000372 parser.read(filename)
373 for section in parser.sections():
374 options = parser.options(section)
Greg Ward0e48cfd2000-05-26 01:00:15 +0000375 opt_dict = self.get_option_dict(section)
Gregory P. Smith14263542000-05-12 00:41:33 +0000376
Greg Wardd5d8a992000-05-23 01:42:17 +0000377 for opt in options:
378 if opt != '__name__':
Greg Wardceb9e222000-09-25 01:23:52 +0000379 val = parser.get(section,opt)
380 opt = string.replace(opt, '-', '_')
381 opt_dict[opt] = (filename, val)
Gregory P. Smith14263542000-05-12 00:41:33 +0000382
Greg Ward47460772000-05-23 03:47:35 +0000383 # Make the ConfigParser forget everything (so we retain
Fred Drakef06116d2004-02-17 22:35:19 +0000384 # the original filenames that options come from)
Greg Ward47460772000-05-23 03:47:35 +0000385 parser.__init__()
Gregory P. Smith14263542000-05-12 00:41:33 +0000386
Greg Wardceb9e222000-09-25 01:23:52 +0000387 # If there was a "global" section in the config file, use it
388 # to set Distribution options.
389
Guido van Rossum8bc09652008-02-21 18:18:37 +0000390 if 'global' in self.command_options:
Greg Wardceb9e222000-09-25 01:23:52 +0000391 for (opt, (src, val)) in self.command_options['global'].items():
392 alias = self.negative_opt.get(opt)
393 try:
394 if alias:
395 setattr(self, alias, not strtobool(val))
396 elif opt in ('verbose', 'dry_run'): # ugh!
397 setattr(self, opt, strtobool(val))
Fred Draked04573f2004-08-03 16:37:40 +0000398 else:
399 setattr(self, opt, val)
Greg Wardceb9e222000-09-25 01:23:52 +0000400 except ValueError, msg:
401 raise DistutilsOptionError, msg
402
403 # parse_config_files ()
404
Gregory P. Smith14263542000-05-12 00:41:33 +0000405
Greg Wardd5d8a992000-05-23 01:42:17 +0000406 # -- Command-line parsing methods ----------------------------------
407
Greg Ward9821bf42000-08-29 01:15:18 +0000408 def parse_command_line (self):
409 """Parse the setup script's command line, taken from the
410 'script_args' instance attribute (which defaults to 'sys.argv[1:]'
411 -- see 'setup()' in core.py). This list is first processed for
412 "global options" -- options that set attributes of the Distribution
413 instance. Then, it is alternately scanned for Distutils commands
414 and options for that command. Each new command terminates the
415 options for the previous command. The allowed options for a
416 command are determined by the 'user_options' attribute of the
417 command class -- thus, we have to be able to load command classes
418 in order to parse the command line. Any error in that 'options'
419 attribute raises DistutilsGetoptError; any error on the
420 command-line raises DistutilsArgError. If no Distutils commands
421 were found on the command line, raises DistutilsArgError. Return
Greg Wardceb9e222000-09-25 01:23:52 +0000422 true if command-line was successfully parsed and we should carry
Greg Ward9821bf42000-08-29 01:15:18 +0000423 on with executing commands; false if no errors but we shouldn't
424 execute commands (currently, this only happens if user asks for
425 help).
Greg Wardd5d8a992000-05-23 01:42:17 +0000426 """
Andrew M. Kuchling3f819ec2001-01-15 16:09:35 +0000427 #
Fred Drake981a1782001-08-10 18:59:30 +0000428 # We now have enough information to show the Macintosh dialog
429 # that allows the user to interactively specify the "command line".
Andrew M. Kuchling3f819ec2001-01-15 16:09:35 +0000430 #
Fred Draked04573f2004-08-03 16:37:40 +0000431 toplevel_options = self._get_toplevel_options()
Andrew M. Kuchling3f819ec2001-01-15 16:09:35 +0000432 if sys.platform == 'mac':
433 import EasyDialogs
434 cmdlist = self.get_command_list()
435 self.script_args = EasyDialogs.GetArgv(
Fred Draked04573f2004-08-03 16:37:40 +0000436 toplevel_options + self.display_options, cmdlist)
Fred Drakeb94b8492001-12-06 20:51:35 +0000437
Greg Wardfe6462c2000-04-04 01:40:52 +0000438 # We have to parse the command line a bit at a time -- global
439 # options, then the first command, then its options, and so on --
440 # because each command will be handled by a different class, and
Greg Wardd5d8a992000-05-23 01:42:17 +0000441 # the options that are valid for a particular class aren't known
442 # until we have loaded the command class, which doesn't happen
443 # until we know what the command is.
Greg Wardfe6462c2000-04-04 01:40:52 +0000444
445 self.commands = []
Fred Draked04573f2004-08-03 16:37:40 +0000446 parser = FancyGetopt(toplevel_options + self.display_options)
Greg Wardfd7b91e2000-09-26 01:52:25 +0000447 parser.set_negative_aliases(self.negative_opt)
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +0000448 parser.set_aliases({'licence': 'license'})
Greg Wardfd7b91e2000-09-26 01:52:25 +0000449 args = parser.getopt(args=self.script_args, object=self)
Greg Ward82715e12000-04-21 02:28:14 +0000450 option_order = parser.get_option_order()
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000451 log.set_verbosity(self.verbose)
Greg Wardfe6462c2000-04-04 01:40:52 +0000452
Greg Ward82715e12000-04-21 02:28:14 +0000453 # for display options we return immediately
454 if self.handle_display_options(option_order):
Greg Wardfe6462c2000-04-04 01:40:52 +0000455 return
Fred Drakeb94b8492001-12-06 20:51:35 +0000456
Greg Wardfe6462c2000-04-04 01:40:52 +0000457 while args:
Greg Wardd5d8a992000-05-23 01:42:17 +0000458 args = self._parse_command_opts(parser, args)
459 if args is None: # user asked for help (and got it)
Greg Wardfe6462c2000-04-04 01:40:52 +0000460 return
Greg Wardfe6462c2000-04-04 01:40:52 +0000461
Greg Wardd5d8a992000-05-23 01:42:17 +0000462 # Handle the cases of --help as a "global" option, ie.
463 # "setup.py --help" and "setup.py --help command ...". For the
464 # former, we show global options (--verbose, --dry-run, etc.)
465 # and display-only options (--name, --version, etc.); for the
466 # latter, we omit the display-only options and show help for
467 # each command listed on the command line.
Greg Wardfe6462c2000-04-04 01:40:52 +0000468 if self.help:
Greg Wardd5d8a992000-05-23 01:42:17 +0000469 self._show_help(parser,
470 display_options=len(self.commands) == 0,
471 commands=self.commands)
Greg Wardfe6462c2000-04-04 01:40:52 +0000472 return
473
474 # Oops, no commands found -- an end-user error
475 if not self.commands:
476 raise DistutilsArgError, "no commands supplied"
477
478 # All is well: return true
479 return 1
480
481 # parse_command_line()
482
Fred Draked04573f2004-08-03 16:37:40 +0000483 def _get_toplevel_options (self):
484 """Return the non-display options recognized at the top level.
485
486 This includes options that are recognized *only* at the top
487 level as well as options recognized for commands.
488 """
489 return self.global_options + [
490 ("command-packages=", None,
491 "list of packages that provide distutils commands"),
492 ]
493
Greg Wardd5d8a992000-05-23 01:42:17 +0000494 def _parse_command_opts (self, parser, args):
Greg Wardd5d8a992000-05-23 01:42:17 +0000495 """Parse the command-line options for a single command.
496 'parser' must be a FancyGetopt instance; 'args' must be the list
497 of arguments, starting with the current command (whose options
498 we are about to parse). Returns a new version of 'args' with
499 the next command at the front of the list; will be the empty
500 list if there are no more commands on the command line. Returns
501 None if the user asked for help on this command.
502 """
503 # late import because of mutual dependence between these modules
504 from distutils.cmd import Command
505
506 # Pull the current command from the head of the command line
507 command = args[0]
Greg Wardfd7b91e2000-09-26 01:52:25 +0000508 if not command_re.match(command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000509 raise SystemExit, "invalid command name '%s'" % command
Greg Wardfd7b91e2000-09-26 01:52:25 +0000510 self.commands.append(command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000511
512 # Dig up the command class that implements this command, so we
513 # 1) know that it's a valid command, and 2) know which options
514 # it takes.
515 try:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000516 cmd_class = self.get_command_class(command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000517 except DistutilsModuleError, msg:
518 raise DistutilsArgError, msg
519
520 # Require that the command class be derived from Command -- want
521 # to be sure that the basic "command" interface is implemented.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000522 if not issubclass(cmd_class, Command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000523 raise DistutilsClassError, \
524 "command class %s must subclass Command" % cmd_class
525
526 # Also make sure that the command object provides a list of its
527 # known options.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000528 if not (hasattr(cmd_class, 'user_options') and
529 type(cmd_class.user_options) is ListType):
Greg Wardd5d8a992000-05-23 01:42:17 +0000530 raise DistutilsClassError, \
531 ("command class %s must provide " +
532 "'user_options' attribute (a list of tuples)") % \
533 cmd_class
534
535 # If the command class has a list of negative alias options,
536 # merge it in with the global negative aliases.
537 negative_opt = self.negative_opt
Greg Wardfd7b91e2000-09-26 01:52:25 +0000538 if hasattr(cmd_class, 'negative_opt'):
539 negative_opt = copy(negative_opt)
540 negative_opt.update(cmd_class.negative_opt)
Greg Wardd5d8a992000-05-23 01:42:17 +0000541
Greg Wardfa9ff762000-10-14 04:06:40 +0000542 # Check for help_options in command class. They have a different
543 # format (tuple of four) so we need to preprocess them here.
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000544 if (hasattr(cmd_class, 'help_options') and
Greg Wardfd7b91e2000-09-26 01:52:25 +0000545 type(cmd_class.help_options) is ListType):
Greg Ward2ff78872000-06-24 00:23:20 +0000546 help_options = fix_help_options(cmd_class.help_options)
547 else:
Greg Ward55fced32000-06-24 01:22:41 +0000548 help_options = []
Greg Ward2ff78872000-06-24 00:23:20 +0000549
Greg Ward9d17a7a2000-06-07 03:00:06 +0000550
Greg Wardd5d8a992000-05-23 01:42:17 +0000551 # All commands support the global options too, just by adding
552 # in 'global_options'.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000553 parser.set_option_table(self.global_options +
554 cmd_class.user_options +
555 help_options)
556 parser.set_negative_aliases(negative_opt)
557 (args, opts) = parser.getopt(args[1:])
Greg Ward47460772000-05-23 03:47:35 +0000558 if hasattr(opts, 'help') and opts.help:
Greg Wardd5d8a992000-05-23 01:42:17 +0000559 self._show_help(parser, display_options=0, commands=[cmd_class])
560 return
561
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000562 if (hasattr(cmd_class, 'help_options') and
Greg Wardfd7b91e2000-09-26 01:52:25 +0000563 type(cmd_class.help_options) is ListType):
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000564 help_option_found=0
565 for (help_option, short, desc, func) in cmd_class.help_options:
566 if hasattr(opts, parser.get_attr_name(help_option)):
567 help_option_found=1
Greg Wardfa9ff762000-10-14 04:06:40 +0000568 #print "showing help for option %s of command %s" % \
Greg Ward2ff78872000-06-24 00:23:20 +0000569 # (help_option[0],cmd_class)
Greg Ward55fced32000-06-24 01:22:41 +0000570
571 if callable(func):
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000572 func()
Greg Ward55fced32000-06-24 01:22:41 +0000573 else:
Fred Drake981a1782001-08-10 18:59:30 +0000574 raise DistutilsClassError(
Walter Dörwald70a6b492004-02-12 17:35:32 +0000575 "invalid help function %r for help option '%s': "
Fred Drake981a1782001-08-10 18:59:30 +0000576 "must be a callable object (function, etc.)"
Walter Dörwald70a6b492004-02-12 17:35:32 +0000577 % (func, help_option))
Greg Ward55fced32000-06-24 01:22:41 +0000578
Fred Drakeb94b8492001-12-06 20:51:35 +0000579 if help_option_found:
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000580 return
Greg Ward9d17a7a2000-06-07 03:00:06 +0000581
Greg Wardd5d8a992000-05-23 01:42:17 +0000582 # Put the options from the command-line into their official
583 # holding pen, the 'command_options' dictionary.
Greg Ward0e48cfd2000-05-26 01:00:15 +0000584 opt_dict = self.get_option_dict(command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000585 for (name, value) in vars(opts).items():
Greg Ward0e48cfd2000-05-26 01:00:15 +0000586 opt_dict[name] = ("command line", value)
Greg Wardd5d8a992000-05-23 01:42:17 +0000587
588 return args
589
590 # _parse_command_opts ()
591
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000592 def finalize_options (self):
593 """Set final values for all the options on the Distribution
594 instance, analogous to the .finalize_options() method of Command
595 objects.
596 """
597
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000598 keywords = self.metadata.keywords
599 if keywords is not None:
600 if type(keywords) is StringType:
601 keywordlist = string.split(keywords, ',')
602 self.metadata.keywords = map(string.strip, keywordlist)
603
604 platforms = self.metadata.platforms
605 if platforms is not None:
606 if type(platforms) is StringType:
607 platformlist = string.split(platforms, ',')
608 self.metadata.platforms = map(string.strip, platformlist)
609
Greg Wardd5d8a992000-05-23 01:42:17 +0000610 def _show_help (self,
611 parser,
612 global_options=1,
613 display_options=1,
614 commands=[]):
615 """Show help for the setup script command-line in the form of
616 several lists of command-line options. 'parser' should be a
617 FancyGetopt instance; do not expect it to be returned in the
618 same state, as its option table will be reset to make it
619 generate the correct help text.
620
621 If 'global_options' is true, lists the global options:
622 --verbose, --dry-run, etc. If 'display_options' is true, lists
623 the "display-only" options: --name, --version, etc. Finally,
624 lists per-command help for every command name or command class
625 in 'commands'.
626 """
627 # late import because of mutual dependence between these modules
Greg Ward9821bf42000-08-29 01:15:18 +0000628 from distutils.core import gen_usage
Greg Wardd5d8a992000-05-23 01:42:17 +0000629 from distutils.cmd import Command
630
631 if global_options:
Fred Draked04573f2004-08-03 16:37:40 +0000632 if display_options:
633 options = self._get_toplevel_options()
634 else:
635 options = self.global_options
636 parser.set_option_table(options)
Martin v. Löwis8ed338a2005-03-03 08:12:27 +0000637 parser.print_help(self.common_usage + "\nGlobal options:")
Greg Wardd5d8a992000-05-23 01:42:17 +0000638 print
639
640 if display_options:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000641 parser.set_option_table(self.display_options)
642 parser.print_help(
Greg Wardd5d8a992000-05-23 01:42:17 +0000643 "Information display options (just display " +
644 "information, ignore any commands)")
645 print
646
647 for command in self.commands:
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +0000648 if type(command) is ClassType and issubclass(command, Command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000649 klass = command
650 else:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000651 klass = self.get_command_class(command)
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000652 if (hasattr(klass, 'help_options') and
Greg Wardfd7b91e2000-09-26 01:52:25 +0000653 type(klass.help_options) is ListType):
654 parser.set_option_table(klass.user_options +
655 fix_help_options(klass.help_options))
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000656 else:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000657 parser.set_option_table(klass.user_options)
658 parser.print_help("Options for '%s' command:" % klass.__name__)
Greg Wardd5d8a992000-05-23 01:42:17 +0000659 print
660
Greg Ward9821bf42000-08-29 01:15:18 +0000661 print gen_usage(self.script_name)
Greg Wardd5d8a992000-05-23 01:42:17 +0000662 return
663
664 # _show_help ()
Greg Wardfa9ff762000-10-14 04:06:40 +0000665
Greg Wardd5d8a992000-05-23 01:42:17 +0000666
Greg Ward82715e12000-04-21 02:28:14 +0000667 def handle_display_options (self, option_order):
668 """If there were any non-global "display-only" options
Greg Wardd5d8a992000-05-23 01:42:17 +0000669 (--help-commands or the metadata display options) on the command
670 line, display the requested info and return true; else return
671 false.
672 """
Greg Ward9821bf42000-08-29 01:15:18 +0000673 from distutils.core import gen_usage
Greg Ward82715e12000-04-21 02:28:14 +0000674
675 # User just wants a list of commands -- we'll print it out and stop
676 # processing now (ie. if they ran "setup --help-commands foo bar",
677 # we ignore "foo bar").
678 if self.help_commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000679 self.print_commands()
Greg Ward82715e12000-04-21 02:28:14 +0000680 print
Greg Ward9821bf42000-08-29 01:15:18 +0000681 print gen_usage(self.script_name)
Greg Ward82715e12000-04-21 02:28:14 +0000682 return 1
683
684 # If user supplied any of the "display metadata" options, then
685 # display that metadata in the order in which the user supplied the
686 # metadata options.
687 any_display_options = 0
688 is_display_option = {}
689 for option in self.display_options:
690 is_display_option[option[0]] = 1
691
692 for (opt, val) in option_order:
693 if val and is_display_option.get(opt):
Greg Ward2f2b6c62000-09-25 01:58:07 +0000694 opt = translate_longopt(opt)
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000695 value = getattr(self.metadata, "get_"+opt)()
696 if opt in ['keywords', 'platforms']:
697 print string.join(value, ',')
Fred Drakedb7b0022005-03-20 22:19:47 +0000698 elif opt in ('classifiers', 'provides', 'requires',
699 'obsoletes'):
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +0000700 print string.join(value, '\n')
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000701 else:
702 print value
Greg Ward82715e12000-04-21 02:28:14 +0000703 any_display_options = 1
704
705 return any_display_options
706
707 # handle_display_options()
Greg Wardfe6462c2000-04-04 01:40:52 +0000708
709 def print_command_list (self, commands, header, max_length):
710 """Print a subset of the list of all commands -- used by
Greg Wardd5d8a992000-05-23 01:42:17 +0000711 'print_commands()'.
712 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000713
714 print header + ":"
715
716 for cmd in commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000717 klass = self.cmdclass.get(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000718 if not klass:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000719 klass = self.get_command_class(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000720 try:
721 description = klass.description
722 except AttributeError:
723 description = "(no description available)"
724
725 print " %-*s %s" % (max_length, cmd, description)
726
727 # print_command_list ()
728
729
730 def print_commands (self):
Greg Wardd5d8a992000-05-23 01:42:17 +0000731 """Print out a help message listing all available commands with a
732 description of each. The list is divided into "standard commands"
733 (listed in distutils.command.__all__) and "extra commands"
734 (mentioned in self.cmdclass, but not a standard command). The
735 descriptions come from the command class attribute
736 'description'.
737 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000738
739 import distutils.command
740 std_commands = distutils.command.__all__
741 is_std = {}
742 for cmd in std_commands:
743 is_std[cmd] = 1
744
745 extra_commands = []
746 for cmd in self.cmdclass.keys():
747 if not is_std.get(cmd):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000748 extra_commands.append(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000749
750 max_length = 0
751 for cmd in (std_commands + extra_commands):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000752 if len(cmd) > max_length:
753 max_length = len(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000754
Greg Wardfd7b91e2000-09-26 01:52:25 +0000755 self.print_command_list(std_commands,
756 "Standard commands",
757 max_length)
Greg Wardfe6462c2000-04-04 01:40:52 +0000758 if extra_commands:
759 print
Greg Wardfd7b91e2000-09-26 01:52:25 +0000760 self.print_command_list(extra_commands,
761 "Extra commands",
762 max_length)
Greg Wardfe6462c2000-04-04 01:40:52 +0000763
764 # print_commands ()
Greg Wardfe6462c2000-04-04 01:40:52 +0000765
Greg Wardf6fc8752000-11-11 02:47:11 +0000766 def get_command_list (self):
767 """Get a list of (command, description) tuples.
768 The list is divided into "standard commands" (listed in
769 distutils.command.__all__) and "extra commands" (mentioned in
770 self.cmdclass, but not a standard command). The descriptions come
771 from the command class attribute 'description'.
772 """
773 # Currently this is only used on Mac OS, for the Mac-only GUI
774 # Distutils interface (by Jack Jansen)
775
776 import distutils.command
777 std_commands = distutils.command.__all__
778 is_std = {}
779 for cmd in std_commands:
780 is_std[cmd] = 1
781
782 extra_commands = []
783 for cmd in self.cmdclass.keys():
784 if not is_std.get(cmd):
785 extra_commands.append(cmd)
786
787 rv = []
788 for cmd in (std_commands + extra_commands):
789 klass = self.cmdclass.get(cmd)
790 if not klass:
791 klass = self.get_command_class(cmd)
792 try:
793 description = klass.description
794 except AttributeError:
795 description = "(no description available)"
796 rv.append((cmd, description))
797 return rv
Greg Wardfe6462c2000-04-04 01:40:52 +0000798
799 # -- Command class/object methods ----------------------------------
800
Fred Draked04573f2004-08-03 16:37:40 +0000801 def get_command_packages (self):
802 """Return a list of packages from which commands are loaded."""
803 pkgs = self.command_packages
804 if not isinstance(pkgs, type([])):
805 pkgs = string.split(pkgs or "", ",")
806 for i in range(len(pkgs)):
807 pkgs[i] = string.strip(pkgs[i])
808 pkgs = filter(None, pkgs)
809 if "distutils.command" not in pkgs:
810 pkgs.insert(0, "distutils.command")
811 self.command_packages = pkgs
812 return pkgs
813
Greg Wardd5d8a992000-05-23 01:42:17 +0000814 def get_command_class (self, command):
815 """Return the class that implements the Distutils command named by
816 'command'. First we check the 'cmdclass' dictionary; if the
817 command is mentioned there, we fetch the class object from the
818 dictionary and return it. Otherwise we load the command module
819 ("distutils.command." + command) and fetch the command class from
820 the module. The loaded class is also stored in 'cmdclass'
821 to speed future calls to 'get_command_class()'.
Greg Wardfe6462c2000-04-04 01:40:52 +0000822
Gregory P. Smith14263542000-05-12 00:41:33 +0000823 Raises DistutilsModuleError if the expected module could not be
Greg Wardd5d8a992000-05-23 01:42:17 +0000824 found, or if that module does not define the expected class.
825 """
826 klass = self.cmdclass.get(command)
827 if klass:
828 return klass
Greg Wardfe6462c2000-04-04 01:40:52 +0000829
Fred Draked04573f2004-08-03 16:37:40 +0000830 for pkgname in self.get_command_packages():
831 module_name = "%s.%s" % (pkgname, command)
832 klass_name = command
Greg Wardfe6462c2000-04-04 01:40:52 +0000833
Fred Draked04573f2004-08-03 16:37:40 +0000834 try:
835 __import__ (module_name)
836 module = sys.modules[module_name]
837 except ImportError:
838 continue
Greg Wardfe6462c2000-04-04 01:40:52 +0000839
Fred Draked04573f2004-08-03 16:37:40 +0000840 try:
841 klass = getattr(module, klass_name)
842 except AttributeError:
843 raise DistutilsModuleError, \
844 "invalid command '%s' (no class '%s' in module '%s')" \
845 % (command, klass_name, module_name)
Greg Wardfe6462c2000-04-04 01:40:52 +0000846
Fred Draked04573f2004-08-03 16:37:40 +0000847 self.cmdclass[command] = klass
848 return klass
849
850 raise DistutilsModuleError("invalid command '%s'" % command)
851
Greg Wardfe6462c2000-04-04 01:40:52 +0000852
Greg Wardd5d8a992000-05-23 01:42:17 +0000853 # get_command_class ()
Greg Wardfe6462c2000-04-04 01:40:52 +0000854
Greg Wardd5d8a992000-05-23 01:42:17 +0000855 def get_command_obj (self, command, create=1):
856 """Return the command object for 'command'. Normally this object
Greg Ward612eb9f2000-07-27 02:13:20 +0000857 is cached on a previous call to 'get_command_obj()'; if no command
Greg Wardd5d8a992000-05-23 01:42:17 +0000858 object for 'command' is in the cache, then we either create and
859 return it (if 'create' is true) or return None.
860 """
861 cmd_obj = self.command_obj.get(command)
Greg Wardfe6462c2000-04-04 01:40:52 +0000862 if not cmd_obj and create:
Greg Ward2bd3f422000-06-02 01:59:33 +0000863 if DEBUG:
864 print "Distribution.get_command_obj(): " \
865 "creating '%s' command object" % command
Greg Ward47460772000-05-23 03:47:35 +0000866
Greg Wardd5d8a992000-05-23 01:42:17 +0000867 klass = self.get_command_class(command)
Greg Ward47460772000-05-23 03:47:35 +0000868 cmd_obj = self.command_obj[command] = klass(self)
869 self.have_run[command] = 0
870
871 # Set any options that were supplied in config files
872 # or on the command line. (NB. support for error
873 # reporting is lame here: any errors aren't reported
874 # until 'finalize_options()' is called, which means
875 # we won't report the source of the error.)
876 options = self.command_options.get(command)
877 if options:
Greg Wardc32d9a62000-05-28 23:53:06 +0000878 self._set_command_options(cmd_obj, options)
Greg Wardfe6462c2000-04-04 01:40:52 +0000879
880 return cmd_obj
881
Greg Wardc32d9a62000-05-28 23:53:06 +0000882 def _set_command_options (self, command_obj, option_dict=None):
Greg Wardc32d9a62000-05-28 23:53:06 +0000883 """Set the options for 'command_obj' from 'option_dict'. Basically
884 this means copying elements of a dictionary ('option_dict') to
885 attributes of an instance ('command').
886
Greg Wardceb9e222000-09-25 01:23:52 +0000887 'command_obj' must be a Command instance. If 'option_dict' is not
Greg Wardc32d9a62000-05-28 23:53:06 +0000888 supplied, uses the standard option dictionary for this command
889 (from 'self.command_options').
890 """
Greg Wardc32d9a62000-05-28 23:53:06 +0000891 command_name = command_obj.get_command_name()
892 if option_dict is None:
893 option_dict = self.get_option_dict(command_name)
894
895 if DEBUG: print " setting options for '%s' command:" % command_name
896 for (option, (source, value)) in option_dict.items():
897 if DEBUG: print " %s = %s (from %s)" % (option, value, source)
Greg Wardceb9e222000-09-25 01:23:52 +0000898 try:
Greg Ward2f2b6c62000-09-25 01:58:07 +0000899 bool_opts = map(translate_longopt, command_obj.boolean_options)
Greg Wardceb9e222000-09-25 01:23:52 +0000900 except AttributeError:
901 bool_opts = []
902 try:
903 neg_opt = command_obj.negative_opt
904 except AttributeError:
905 neg_opt = {}
906
907 try:
Greg Ward2c08cf02000-09-27 00:15:37 +0000908 is_string = type(value) is StringType
Guido van Rossum8bc09652008-02-21 18:18:37 +0000909 if option in neg_opt and is_string:
Greg Wardceb9e222000-09-25 01:23:52 +0000910 setattr(command_obj, neg_opt[option], not strtobool(value))
Greg Ward2c08cf02000-09-27 00:15:37 +0000911 elif option in bool_opts and is_string:
Greg Wardceb9e222000-09-25 01:23:52 +0000912 setattr(command_obj, option, strtobool(value))
913 elif hasattr(command_obj, option):
914 setattr(command_obj, option, value)
915 else:
916 raise DistutilsOptionError, \
917 ("error in %s: command '%s' has no such option '%s'"
918 % (source, command_name, option))
919 except ValueError, msg:
920 raise DistutilsOptionError, msg
Greg Wardc32d9a62000-05-28 23:53:06 +0000921
Greg Wardf449ea52000-09-16 15:23:28 +0000922 def reinitialize_command (self, command, reinit_subcommands=0):
Greg Wardc32d9a62000-05-28 23:53:06 +0000923 """Reinitializes a command to the state it was in when first
924 returned by 'get_command_obj()': ie., initialized but not yet
Greg Ward7d9c7052000-06-28 01:25:27 +0000925 finalized. This provides the opportunity to sneak option
Greg Wardc32d9a62000-05-28 23:53:06 +0000926 values in programmatically, overriding or supplementing
927 user-supplied values from the config files and command line.
928 You'll have to re-finalize the command object (by calling
929 'finalize_options()' or 'ensure_finalized()') before using it for
Fred Drakeb94b8492001-12-06 20:51:35 +0000930 real.
Greg Wardc32d9a62000-05-28 23:53:06 +0000931
Greg Wardf449ea52000-09-16 15:23:28 +0000932 'command' should be a command name (string) or command object. If
933 'reinit_subcommands' is true, also reinitializes the command's
934 sub-commands, as declared by the 'sub_commands' class attribute (if
935 it has one). See the "install" command for an example. Only
936 reinitializes the sub-commands that actually matter, ie. those
937 whose test predicates return true.
938
Greg Wardc32d9a62000-05-28 23:53:06 +0000939 Returns the reinitialized command object.
940 """
941 from distutils.cmd import Command
942 if not isinstance(command, Command):
943 command_name = command
944 command = self.get_command_obj(command_name)
945 else:
946 command_name = command.get_command_name()
947
948 if not command.finalized:
Greg Ward282c7a02000-06-01 01:09:47 +0000949 return command
Greg Wardc32d9a62000-05-28 23:53:06 +0000950 command.initialize_options()
951 command.finalized = 0
Greg Ward43955c92000-06-06 02:52:36 +0000952 self.have_run[command_name] = 0
Greg Wardc32d9a62000-05-28 23:53:06 +0000953 self._set_command_options(command)
Greg Wardf449ea52000-09-16 15:23:28 +0000954
Greg Wardf449ea52000-09-16 15:23:28 +0000955 if reinit_subcommands:
Greg Wardf449ea52000-09-16 15:23:28 +0000956 for sub in command.get_sub_commands():
Fred Drakeb94b8492001-12-06 20:51:35 +0000957 self.reinitialize_command(sub, reinit_subcommands)
Greg Wardf449ea52000-09-16 15:23:28 +0000958
Greg Wardc32d9a62000-05-28 23:53:06 +0000959 return command
960
Fred Drakeb94b8492001-12-06 20:51:35 +0000961
Greg Wardfe6462c2000-04-04 01:40:52 +0000962 # -- Methods that operate on the Distribution ----------------------
963
964 def announce (self, msg, level=1):
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000965 log.debug(msg)
Greg Wardfe6462c2000-04-04 01:40:52 +0000966
967 def run_commands (self):
Greg Ward82715e12000-04-21 02:28:14 +0000968 """Run each command that was seen on the setup script command line.
Greg Wardd5d8a992000-05-23 01:42:17 +0000969 Uses the list of commands found and cache of command objects
Greg Wardfd7b91e2000-09-26 01:52:25 +0000970 created by 'get_command_obj()'.
971 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000972 for cmd in self.commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000973 self.run_command(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000974
975
Greg Wardfe6462c2000-04-04 01:40:52 +0000976 # -- Methods that operate on its Commands --------------------------
977
978 def run_command (self, command):
Greg Wardfe6462c2000-04-04 01:40:52 +0000979 """Do whatever it takes to run a command (including nothing at all,
Greg Wardd5d8a992000-05-23 01:42:17 +0000980 if the command has already been run). Specifically: if we have
981 already created and run the command named by 'command', return
982 silently without doing anything. If the command named by 'command'
983 doesn't even have a command object yet, create one. Then invoke
984 'run()' on that command object (or an existing one).
985 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000986 # Already been here, done that? then return silently.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000987 if self.have_run.get(command):
Greg Wardfe6462c2000-04-04 01:40:52 +0000988 return
989
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000990 log.info("running %s", command)
Greg Wardfd7b91e2000-09-26 01:52:25 +0000991 cmd_obj = self.get_command_obj(command)
992 cmd_obj.ensure_finalized()
993 cmd_obj.run()
Greg Wardfe6462c2000-04-04 01:40:52 +0000994 self.have_run[command] = 1
995
996
Greg Wardfe6462c2000-04-04 01:40:52 +0000997 # -- Distribution query methods ------------------------------------
998
999 def has_pure_modules (self):
Greg Wardfd7b91e2000-09-26 01:52:25 +00001000 return len(self.packages or self.py_modules or []) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +00001001
1002 def has_ext_modules (self):
Greg Wardfd7b91e2000-09-26 01:52:25 +00001003 return self.ext_modules and len(self.ext_modules) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +00001004
1005 def has_c_libraries (self):
Greg Wardfd7b91e2000-09-26 01:52:25 +00001006 return self.libraries and len(self.libraries) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +00001007
1008 def has_modules (self):
1009 return self.has_pure_modules() or self.has_ext_modules()
1010
Greg Ward51def7d2000-05-27 01:36:14 +00001011 def has_headers (self):
1012 return self.headers and len(self.headers) > 0
1013
Greg Ward44a61bb2000-05-20 15:06:48 +00001014 def has_scripts (self):
1015 return self.scripts and len(self.scripts) > 0
1016
1017 def has_data_files (self):
1018 return self.data_files and len(self.data_files) > 0
1019
Greg Wardfe6462c2000-04-04 01:40:52 +00001020 def is_pure (self):
1021 return (self.has_pure_modules() and
1022 not self.has_ext_modules() and
1023 not self.has_c_libraries())
1024
Greg Ward82715e12000-04-21 02:28:14 +00001025 # -- Metadata query methods ----------------------------------------
1026
1027 # If you're looking for 'get_name()', 'get_version()', and so forth,
1028 # they are defined in a sneaky way: the constructor binds self.get_XXX
1029 # to self.metadata.get_XXX. The actual code is in the
1030 # DistributionMetadata class, below.
1031
1032# class Distribution
1033
1034
1035class DistributionMetadata:
1036 """Dummy class to hold the distribution meta-data: name, version,
Greg Wardfd7b91e2000-09-26 01:52:25 +00001037 author, and so forth.
1038 """
Greg Ward82715e12000-04-21 02:28:14 +00001039
Neil Schemenauera8aefe52001-09-03 15:47:21 +00001040 _METHOD_BASENAMES = ("name", "version", "author", "author_email",
1041 "maintainer", "maintainer_email", "url",
1042 "license", "description", "long_description",
1043 "keywords", "platforms", "fullname", "contact",
Andrew M. Kuchlinga52b8522003-03-03 20:07:27 +00001044 "contact_email", "license", "classifiers",
Fred Drakedb7b0022005-03-20 22:19:47 +00001045 "download_url",
1046 # PEP 314
1047 "provides", "requires", "obsoletes",
1048 )
Neil Schemenauera8aefe52001-09-03 15:47:21 +00001049
Greg Ward82715e12000-04-21 02:28:14 +00001050 def __init__ (self):
1051 self.name = None
1052 self.version = None
1053 self.author = None
1054 self.author_email = None
1055 self.maintainer = None
1056 self.maintainer_email = None
1057 self.url = None
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +00001058 self.license = None
Greg Ward82715e12000-04-21 02:28:14 +00001059 self.description = None
Greg Warde5a584e2000-04-26 02:26:55 +00001060 self.long_description = None
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001061 self.keywords = None
1062 self.platforms = None
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +00001063 self.classifiers = None
Andrew M. Kuchling188d85f2003-02-19 14:16:01 +00001064 self.download_url = None
Fred Drakedb7b0022005-03-20 22:19:47 +00001065 # PEP 314
1066 self.provides = None
1067 self.requires = None
1068 self.obsoletes = None
Fred Drakeb94b8492001-12-06 20:51:35 +00001069
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001070 def write_pkg_info (self, base_dir):
1071 """Write the PKG-INFO file into the release tree.
1072 """
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001073 pkg_info = open( os.path.join(base_dir, 'PKG-INFO'), 'w')
1074
Fred Drakedb7b0022005-03-20 22:19:47 +00001075 self.write_pkg_file(pkg_info)
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +00001076
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001077 pkg_info.close()
Fred Drakeb94b8492001-12-06 20:51:35 +00001078
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001079 # write_pkg_info ()
Fred Drakeb94b8492001-12-06 20:51:35 +00001080
Fred Drakedb7b0022005-03-20 22:19:47 +00001081 def write_pkg_file (self, file):
1082 """Write the PKG-INFO format data to a file object.
1083 """
1084 version = '1.0'
1085 if self.provides or self.requires or self.obsoletes:
1086 version = '1.1'
1087
1088 file.write('Metadata-Version: %s\n' % version)
1089 file.write('Name: %s\n' % self.get_name() )
1090 file.write('Version: %s\n' % self.get_version() )
1091 file.write('Summary: %s\n' % self.get_description() )
1092 file.write('Home-page: %s\n' % self.get_url() )
1093 file.write('Author: %s\n' % self.get_contact() )
1094 file.write('Author-email: %s\n' % self.get_contact_email() )
1095 file.write('License: %s\n' % self.get_license() )
1096 if self.download_url:
1097 file.write('Download-URL: %s\n' % self.download_url)
1098
1099 long_desc = rfc822_escape( self.get_long_description() )
1100 file.write('Description: %s\n' % long_desc)
1101
1102 keywords = string.join( self.get_keywords(), ',')
1103 if keywords:
1104 file.write('Keywords: %s\n' % keywords )
1105
1106 self._write_list(file, 'Platform', self.get_platforms())
1107 self._write_list(file, 'Classifier', self.get_classifiers())
1108
1109 # PEP 314
1110 self._write_list(file, 'Requires', self.get_requires())
1111 self._write_list(file, 'Provides', self.get_provides())
1112 self._write_list(file, 'Obsoletes', self.get_obsoletes())
1113
1114 def _write_list (self, file, name, values):
1115 for value in values:
1116 file.write('%s: %s\n' % (name, value))
1117
Greg Ward82715e12000-04-21 02:28:14 +00001118 # -- Metadata query methods ----------------------------------------
1119
Greg Wardfe6462c2000-04-04 01:40:52 +00001120 def get_name (self):
1121 return self.name or "UNKNOWN"
1122
Greg Ward82715e12000-04-21 02:28:14 +00001123 def get_version(self):
Thomas Hellerbcd89752001-12-06 20:44:19 +00001124 return self.version or "0.0.0"
Greg Wardfe6462c2000-04-04 01:40:52 +00001125
Greg Ward82715e12000-04-21 02:28:14 +00001126 def get_fullname (self):
1127 return "%s-%s" % (self.get_name(), self.get_version())
1128
1129 def get_author(self):
1130 return self.author or "UNKNOWN"
1131
1132 def get_author_email(self):
1133 return self.author_email or "UNKNOWN"
1134
1135 def get_maintainer(self):
1136 return self.maintainer or "UNKNOWN"
1137
1138 def get_maintainer_email(self):
1139 return self.maintainer_email or "UNKNOWN"
1140
1141 def get_contact(self):
1142 return (self.maintainer or
1143 self.author or
1144 "UNKNOWN")
1145
1146 def get_contact_email(self):
1147 return (self.maintainer_email or
1148 self.author_email or
1149 "UNKNOWN")
1150
1151 def get_url(self):
1152 return self.url or "UNKNOWN"
1153
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +00001154 def get_license(self):
1155 return self.license or "UNKNOWN"
1156 get_licence = get_license
Fred Drakeb94b8492001-12-06 20:51:35 +00001157
Greg Ward82715e12000-04-21 02:28:14 +00001158 def get_description(self):
1159 return self.description or "UNKNOWN"
Greg Warde5a584e2000-04-26 02:26:55 +00001160
1161 def get_long_description(self):
1162 return self.long_description or "UNKNOWN"
1163
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001164 def get_keywords(self):
1165 return self.keywords or []
1166
1167 def get_platforms(self):
1168 return self.platforms or ["UNKNOWN"]
1169
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +00001170 def get_classifiers(self):
1171 return self.classifiers or []
1172
Andrew M. Kuchling188d85f2003-02-19 14:16:01 +00001173 def get_download_url(self):
1174 return self.download_url or "UNKNOWN"
1175
Fred Drakedb7b0022005-03-20 22:19:47 +00001176 # PEP 314
1177
1178 def get_requires(self):
1179 return self.requires or []
1180
1181 def set_requires(self, value):
1182 import distutils.versionpredicate
1183 for v in value:
1184 distutils.versionpredicate.VersionPredicate(v)
1185 self.requires = value
1186
1187 def get_provides(self):
1188 return self.provides or []
1189
1190 def set_provides(self, value):
1191 value = [v.strip() for v in value]
1192 for v in value:
1193 import distutils.versionpredicate
Fred Drake227e8ff2005-03-21 06:36:32 +00001194 distutils.versionpredicate.split_provision(v)
Fred Drakedb7b0022005-03-20 22:19:47 +00001195 self.provides = value
1196
1197 def get_obsoletes(self):
1198 return self.obsoletes or []
1199
1200 def set_obsoletes(self, value):
1201 import distutils.versionpredicate
1202 for v in value:
1203 distutils.versionpredicate.VersionPredicate(v)
1204 self.obsoletes = value
1205
Greg Ward82715e12000-04-21 02:28:14 +00001206# class DistributionMetadata
Greg Wardfe6462c2000-04-04 01:40:52 +00001207
Greg Ward2ff78872000-06-24 00:23:20 +00001208
1209def fix_help_options (options):
1210 """Convert a 4-tuple 'help_options' list as found in various command
1211 classes to the 3-tuple form required by FancyGetopt.
1212 """
1213 new_options = []
1214 for help_tuple in options:
1215 new_options.append(help_tuple[0:3])
1216 return new_options
1217
1218
Greg Wardfe6462c2000-04-04 01:40:52 +00001219if __name__ == "__main__":
Greg Wardfd7b91e2000-09-26 01:52:25 +00001220 dist = Distribution()
Greg Wardfe6462c2000-04-04 01:40:52 +00001221 print "ok"