blob: ca7a2f9952fa3b7753920b899b7917bc1b8ad313 [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 Rossume2b70bc2006-08-18 22:13:04 +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:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000293 print(indent + header)
Greg Wardc32d9a62000-05-28 23:53:06 +0000294 indent = indent + " "
295
296 if not commands:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000297 print(indent + "no commands known yet")
Greg Wardc32d9a62000-05-28 23:53:06 +0000298 return
299
300 for cmd_name in commands:
301 opt_dict = self.command_options.get(cmd_name)
302 if opt_dict is None:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000303 print(indent + "no option dict for '%s' command" % cmd_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000304 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000305 print(indent + "option dict for '%s' command:" % cmd_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000306 out = pformat(opt_dict)
307 for line in string.split(out, "\n"):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000308 print(indent + " " + line)
Greg Wardc32d9a62000-05-28 23:53:06 +0000309
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
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000346 if 'HOME' in os.environ:
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000347 user_file = os.path.join(os.environ.get('HOME'), user_filename)
Gregory P. Smith14263542000-05-12 00:41:33 +0000348 if os.path.isfile(user_file):
349 files.append(user_file)
350
Gregory P. Smith14263542000-05-12 00:41:33 +0000351 # All platforms support local setup.cfg
352 local_file = "setup.cfg"
353 if os.path.isfile(local_file):
354 files.append(local_file)
355
356 return files
357
358 # find_config_files ()
359
360
361 def parse_config_files (self, filenames=None):
362
363 from ConfigParser import ConfigParser
364
365 if filenames is None:
366 filenames = self.find_config_files()
367
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000368 if DEBUG: print("Distribution.parse_config_files():")
Greg Ward47460772000-05-23 03:47:35 +0000369
Gregory P. Smith14263542000-05-12 00:41:33 +0000370 parser = ConfigParser()
Greg Wardd5d8a992000-05-23 01:42:17 +0000371 for filename in filenames:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000372 if DEBUG: print(" reading", filename)
Greg Wardd5d8a992000-05-23 01:42:17 +0000373 parser.read(filename)
374 for section in parser.sections():
375 options = parser.options(section)
Greg Ward0e48cfd2000-05-26 01:00:15 +0000376 opt_dict = self.get_option_dict(section)
Gregory P. Smith14263542000-05-12 00:41:33 +0000377
Greg Wardd5d8a992000-05-23 01:42:17 +0000378 for opt in options:
379 if opt != '__name__':
Greg Wardceb9e222000-09-25 01:23:52 +0000380 val = parser.get(section,opt)
381 opt = string.replace(opt, '-', '_')
382 opt_dict[opt] = (filename, val)
Gregory P. Smith14263542000-05-12 00:41:33 +0000383
Greg Ward47460772000-05-23 03:47:35 +0000384 # Make the ConfigParser forget everything (so we retain
Fred Drakef06116d2004-02-17 22:35:19 +0000385 # the original filenames that options come from)
Greg Ward47460772000-05-23 03:47:35 +0000386 parser.__init__()
Gregory P. Smith14263542000-05-12 00:41:33 +0000387
Greg Wardceb9e222000-09-25 01:23:52 +0000388 # If there was a "global" section in the config file, use it
389 # to set Distribution options.
390
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000391 if 'global' in self.command_options:
Greg Wardceb9e222000-09-25 01:23:52 +0000392 for (opt, (src, val)) in self.command_options['global'].items():
393 alias = self.negative_opt.get(opt)
394 try:
395 if alias:
396 setattr(self, alias, not strtobool(val))
397 elif opt in ('verbose', 'dry_run'): # ugh!
398 setattr(self, opt, strtobool(val))
Fred Draked04573f2004-08-03 16:37:40 +0000399 else:
400 setattr(self, opt, val)
Guido van Rossumb940e112007-01-10 16:19:56 +0000401 except ValueError as msg:
Greg Wardceb9e222000-09-25 01:23:52 +0000402 raise DistutilsOptionError, msg
403
404 # parse_config_files ()
405
Gregory P. Smith14263542000-05-12 00:41:33 +0000406
Greg Wardd5d8a992000-05-23 01:42:17 +0000407 # -- Command-line parsing methods ----------------------------------
408
Greg Ward9821bf42000-08-29 01:15:18 +0000409 def parse_command_line (self):
410 """Parse the setup script's command line, taken from the
411 'script_args' instance attribute (which defaults to 'sys.argv[1:]'
412 -- see 'setup()' in core.py). This list is first processed for
413 "global options" -- options that set attributes of the Distribution
414 instance. Then, it is alternately scanned for Distutils commands
415 and options for that command. Each new command terminates the
416 options for the previous command. The allowed options for a
417 command are determined by the 'user_options' attribute of the
418 command class -- thus, we have to be able to load command classes
419 in order to parse the command line. Any error in that 'options'
420 attribute raises DistutilsGetoptError; any error on the
421 command-line raises DistutilsArgError. If no Distutils commands
422 were found on the command line, raises DistutilsArgError. Return
Greg Wardceb9e222000-09-25 01:23:52 +0000423 true if command-line was successfully parsed and we should carry
Greg Ward9821bf42000-08-29 01:15:18 +0000424 on with executing commands; false if no errors but we shouldn't
425 execute commands (currently, this only happens if user asks for
426 help).
Greg Wardd5d8a992000-05-23 01:42:17 +0000427 """
Andrew M. Kuchling3f819ec2001-01-15 16:09:35 +0000428 #
Fred Drake981a1782001-08-10 18:59:30 +0000429 # We now have enough information to show the Macintosh dialog
430 # that allows the user to interactively specify the "command line".
Andrew M. Kuchling3f819ec2001-01-15 16:09:35 +0000431 #
Fred Draked04573f2004-08-03 16:37:40 +0000432 toplevel_options = self._get_toplevel_options()
Andrew M. Kuchling3f819ec2001-01-15 16:09:35 +0000433 if sys.platform == 'mac':
434 import EasyDialogs
435 cmdlist = self.get_command_list()
436 self.script_args = EasyDialogs.GetArgv(
Fred Draked04573f2004-08-03 16:37:40 +0000437 toplevel_options + self.display_options, cmdlist)
Fred Drakeb94b8492001-12-06 20:51:35 +0000438
Greg Wardfe6462c2000-04-04 01:40:52 +0000439 # We have to parse the command line a bit at a time -- global
440 # options, then the first command, then its options, and so on --
441 # because each command will be handled by a different class, and
Greg Wardd5d8a992000-05-23 01:42:17 +0000442 # the options that are valid for a particular class aren't known
443 # until we have loaded the command class, which doesn't happen
444 # until we know what the command is.
Greg Wardfe6462c2000-04-04 01:40:52 +0000445
446 self.commands = []
Fred Draked04573f2004-08-03 16:37:40 +0000447 parser = FancyGetopt(toplevel_options + self.display_options)
Greg Wardfd7b91e2000-09-26 01:52:25 +0000448 parser.set_negative_aliases(self.negative_opt)
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +0000449 parser.set_aliases({'licence': 'license'})
Greg Wardfd7b91e2000-09-26 01:52:25 +0000450 args = parser.getopt(args=self.script_args, object=self)
Greg Ward82715e12000-04-21 02:28:14 +0000451 option_order = parser.get_option_order()
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000452 log.set_verbosity(self.verbose)
Greg Wardfe6462c2000-04-04 01:40:52 +0000453
Greg Ward82715e12000-04-21 02:28:14 +0000454 # for display options we return immediately
455 if self.handle_display_options(option_order):
Greg Wardfe6462c2000-04-04 01:40:52 +0000456 return
Fred Drakeb94b8492001-12-06 20:51:35 +0000457
Greg Wardfe6462c2000-04-04 01:40:52 +0000458 while args:
Greg Wardd5d8a992000-05-23 01:42:17 +0000459 args = self._parse_command_opts(parser, args)
460 if args is None: # user asked for help (and got it)
Greg Wardfe6462c2000-04-04 01:40:52 +0000461 return
Greg Wardfe6462c2000-04-04 01:40:52 +0000462
Greg Wardd5d8a992000-05-23 01:42:17 +0000463 # Handle the cases of --help as a "global" option, ie.
464 # "setup.py --help" and "setup.py --help command ...". For the
465 # former, we show global options (--verbose, --dry-run, etc.)
466 # and display-only options (--name, --version, etc.); for the
467 # latter, we omit the display-only options and show help for
468 # each command listed on the command line.
Greg Wardfe6462c2000-04-04 01:40:52 +0000469 if self.help:
Greg Wardd5d8a992000-05-23 01:42:17 +0000470 self._show_help(parser,
471 display_options=len(self.commands) == 0,
472 commands=self.commands)
Greg Wardfe6462c2000-04-04 01:40:52 +0000473 return
474
475 # Oops, no commands found -- an end-user error
476 if not self.commands:
477 raise DistutilsArgError, "no commands supplied"
478
479 # All is well: return true
480 return 1
481
482 # parse_command_line()
483
Fred Draked04573f2004-08-03 16:37:40 +0000484 def _get_toplevel_options (self):
485 """Return the non-display options recognized at the top level.
486
487 This includes options that are recognized *only* at the top
488 level as well as options recognized for commands.
489 """
490 return self.global_options + [
491 ("command-packages=", None,
492 "list of packages that provide distutils commands"),
493 ]
494
Greg Wardd5d8a992000-05-23 01:42:17 +0000495 def _parse_command_opts (self, parser, args):
Greg Wardd5d8a992000-05-23 01:42:17 +0000496 """Parse the command-line options for a single command.
497 'parser' must be a FancyGetopt instance; 'args' must be the list
498 of arguments, starting with the current command (whose options
499 we are about to parse). Returns a new version of 'args' with
500 the next command at the front of the list; will be the empty
501 list if there are no more commands on the command line. Returns
502 None if the user asked for help on this command.
503 """
504 # late import because of mutual dependence between these modules
505 from distutils.cmd import Command
506
507 # Pull the current command from the head of the command line
508 command = args[0]
Greg Wardfd7b91e2000-09-26 01:52:25 +0000509 if not command_re.match(command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000510 raise SystemExit, "invalid command name '%s'" % command
Greg Wardfd7b91e2000-09-26 01:52:25 +0000511 self.commands.append(command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000512
513 # Dig up the command class that implements this command, so we
514 # 1) know that it's a valid command, and 2) know which options
515 # it takes.
516 try:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000517 cmd_class = self.get_command_class(command)
Guido van Rossumb940e112007-01-10 16:19:56 +0000518 except DistutilsModuleError as msg:
Greg Wardd5d8a992000-05-23 01:42:17 +0000519 raise DistutilsArgError, msg
520
521 # Require that the command class be derived from Command -- want
522 # to be sure that the basic "command" interface is implemented.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000523 if not issubclass(cmd_class, Command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000524 raise DistutilsClassError, \
525 "command class %s must subclass Command" % cmd_class
526
527 # Also make sure that the command object provides a list of its
528 # known options.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000529 if not (hasattr(cmd_class, 'user_options') and
530 type(cmd_class.user_options) is ListType):
Greg Wardd5d8a992000-05-23 01:42:17 +0000531 raise DistutilsClassError, \
532 ("command class %s must provide " +
533 "'user_options' attribute (a list of tuples)") % \
534 cmd_class
535
536 # If the command class has a list of negative alias options,
537 # merge it in with the global negative aliases.
538 negative_opt = self.negative_opt
Greg Wardfd7b91e2000-09-26 01:52:25 +0000539 if hasattr(cmd_class, 'negative_opt'):
540 negative_opt = copy(negative_opt)
541 negative_opt.update(cmd_class.negative_opt)
Greg Wardd5d8a992000-05-23 01:42:17 +0000542
Greg Wardfa9ff762000-10-14 04:06:40 +0000543 # Check for help_options in command class. They have a different
544 # format (tuple of four) so we need to preprocess them here.
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000545 if (hasattr(cmd_class, 'help_options') and
Greg Wardfd7b91e2000-09-26 01:52:25 +0000546 type(cmd_class.help_options) is ListType):
Greg Ward2ff78872000-06-24 00:23:20 +0000547 help_options = fix_help_options(cmd_class.help_options)
548 else:
Greg Ward55fced32000-06-24 01:22:41 +0000549 help_options = []
Greg Ward2ff78872000-06-24 00:23:20 +0000550
Greg Ward9d17a7a2000-06-07 03:00:06 +0000551
Greg Wardd5d8a992000-05-23 01:42:17 +0000552 # All commands support the global options too, just by adding
553 # in 'global_options'.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000554 parser.set_option_table(self.global_options +
555 cmd_class.user_options +
556 help_options)
557 parser.set_negative_aliases(negative_opt)
558 (args, opts) = parser.getopt(args[1:])
Greg Ward47460772000-05-23 03:47:35 +0000559 if hasattr(opts, 'help') and opts.help:
Greg Wardd5d8a992000-05-23 01:42:17 +0000560 self._show_help(parser, display_options=0, commands=[cmd_class])
561 return
562
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000563 if (hasattr(cmd_class, 'help_options') and
Greg Wardfd7b91e2000-09-26 01:52:25 +0000564 type(cmd_class.help_options) is ListType):
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000565 help_option_found=0
566 for (help_option, short, desc, func) in cmd_class.help_options:
567 if hasattr(opts, parser.get_attr_name(help_option)):
568 help_option_found=1
Greg Wardfa9ff762000-10-14 04:06:40 +0000569 #print "showing help for option %s of command %s" % \
Greg Ward2ff78872000-06-24 00:23:20 +0000570 # (help_option[0],cmd_class)
Greg Ward55fced32000-06-24 01:22:41 +0000571
572 if callable(func):
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000573 func()
Greg Ward55fced32000-06-24 01:22:41 +0000574 else:
Fred Drake981a1782001-08-10 18:59:30 +0000575 raise DistutilsClassError(
Walter Dörwald70a6b492004-02-12 17:35:32 +0000576 "invalid help function %r for help option '%s': "
Fred Drake981a1782001-08-10 18:59:30 +0000577 "must be a callable object (function, etc.)"
Walter Dörwald70a6b492004-02-12 17:35:32 +0000578 % (func, help_option))
Greg Ward55fced32000-06-24 01:22:41 +0000579
Fred Drakeb94b8492001-12-06 20:51:35 +0000580 if help_option_found:
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000581 return
Greg Ward9d17a7a2000-06-07 03:00:06 +0000582
Greg Wardd5d8a992000-05-23 01:42:17 +0000583 # Put the options from the command-line into their official
584 # holding pen, the 'command_options' dictionary.
Greg Ward0e48cfd2000-05-26 01:00:15 +0000585 opt_dict = self.get_option_dict(command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000586 for (name, value) in vars(opts).items():
Greg Ward0e48cfd2000-05-26 01:00:15 +0000587 opt_dict[name] = ("command line", value)
Greg Wardd5d8a992000-05-23 01:42:17 +0000588
589 return args
590
591 # _parse_command_opts ()
592
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000593 def finalize_options (self):
594 """Set final values for all the options on the Distribution
595 instance, analogous to the .finalize_options() method of Command
596 objects.
597 """
598
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000599 keywords = self.metadata.keywords
600 if keywords is not None:
601 if type(keywords) is StringType:
602 keywordlist = string.split(keywords, ',')
603 self.metadata.keywords = map(string.strip, keywordlist)
604
605 platforms = self.metadata.platforms
606 if platforms is not None:
607 if type(platforms) is StringType:
608 platformlist = string.split(platforms, ',')
609 self.metadata.platforms = map(string.strip, platformlist)
610
Greg Wardd5d8a992000-05-23 01:42:17 +0000611 def _show_help (self,
612 parser,
613 global_options=1,
614 display_options=1,
615 commands=[]):
616 """Show help for the setup script command-line in the form of
617 several lists of command-line options. 'parser' should be a
618 FancyGetopt instance; do not expect it to be returned in the
619 same state, as its option table will be reset to make it
620 generate the correct help text.
621
622 If 'global_options' is true, lists the global options:
623 --verbose, --dry-run, etc. If 'display_options' is true, lists
624 the "display-only" options: --name, --version, etc. Finally,
625 lists per-command help for every command name or command class
626 in 'commands'.
627 """
628 # late import because of mutual dependence between these modules
Greg Ward9821bf42000-08-29 01:15:18 +0000629 from distutils.core import gen_usage
Greg Wardd5d8a992000-05-23 01:42:17 +0000630 from distutils.cmd import Command
631
632 if global_options:
Fred Draked04573f2004-08-03 16:37:40 +0000633 if display_options:
634 options = self._get_toplevel_options()
635 else:
636 options = self.global_options
637 parser.set_option_table(options)
Martin v. Löwis8ed338a2005-03-03 08:12:27 +0000638 parser.print_help(self.common_usage + "\nGlobal options:")
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000639 print()
Greg Wardd5d8a992000-05-23 01:42:17 +0000640
641 if display_options:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000642 parser.set_option_table(self.display_options)
643 parser.print_help(
Greg Wardd5d8a992000-05-23 01:42:17 +0000644 "Information display options (just display " +
645 "information, ignore any commands)")
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000646 print()
Greg Wardd5d8a992000-05-23 01:42:17 +0000647
648 for command in self.commands:
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +0000649 if type(command) is ClassType and issubclass(command, Command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000650 klass = command
651 else:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000652 klass = self.get_command_class(command)
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000653 if (hasattr(klass, 'help_options') and
Greg Wardfd7b91e2000-09-26 01:52:25 +0000654 type(klass.help_options) is ListType):
655 parser.set_option_table(klass.user_options +
656 fix_help_options(klass.help_options))
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000657 else:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000658 parser.set_option_table(klass.user_options)
659 parser.print_help("Options for '%s' command:" % klass.__name__)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000660 print()
Greg Wardd5d8a992000-05-23 01:42:17 +0000661
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000662 print(gen_usage(self.script_name))
Greg Wardd5d8a992000-05-23 01:42:17 +0000663 return
664
665 # _show_help ()
Greg Wardfa9ff762000-10-14 04:06:40 +0000666
Greg Wardd5d8a992000-05-23 01:42:17 +0000667
Greg Ward82715e12000-04-21 02:28:14 +0000668 def handle_display_options (self, option_order):
669 """If there were any non-global "display-only" options
Greg Wardd5d8a992000-05-23 01:42:17 +0000670 (--help-commands or the metadata display options) on the command
671 line, display the requested info and return true; else return
672 false.
673 """
Greg Ward9821bf42000-08-29 01:15:18 +0000674 from distutils.core import gen_usage
Greg Ward82715e12000-04-21 02:28:14 +0000675
676 # User just wants a list of commands -- we'll print it out and stop
677 # processing now (ie. if they ran "setup --help-commands foo bar",
678 # we ignore "foo bar").
679 if self.help_commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000680 self.print_commands()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000681 print()
682 print(gen_usage(self.script_name))
Greg Ward82715e12000-04-21 02:28:14 +0000683 return 1
684
685 # If user supplied any of the "display metadata" options, then
686 # display that metadata in the order in which the user supplied the
687 # metadata options.
688 any_display_options = 0
689 is_display_option = {}
690 for option in self.display_options:
691 is_display_option[option[0]] = 1
692
693 for (opt, val) in option_order:
694 if val and is_display_option.get(opt):
Greg Ward2f2b6c62000-09-25 01:58:07 +0000695 opt = translate_longopt(opt)
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000696 value = getattr(self.metadata, "get_"+opt)()
697 if opt in ['keywords', 'platforms']:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000698 print(string.join(value, ','))
Fred Drakedb7b0022005-03-20 22:19:47 +0000699 elif opt in ('classifiers', 'provides', 'requires',
700 'obsoletes'):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000701 print(string.join(value, '\n'))
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000702 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000703 print(value)
Greg Ward82715e12000-04-21 02:28:14 +0000704 any_display_options = 1
705
706 return any_display_options
707
708 # handle_display_options()
Greg Wardfe6462c2000-04-04 01:40:52 +0000709
710 def print_command_list (self, commands, header, max_length):
711 """Print a subset of the list of all commands -- used by
Greg Wardd5d8a992000-05-23 01:42:17 +0000712 'print_commands()'.
713 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000714
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000715 print(header + ":")
Greg Wardfe6462c2000-04-04 01:40:52 +0000716
717 for cmd in commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000718 klass = self.cmdclass.get(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000719 if not klass:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000720 klass = self.get_command_class(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000721 try:
722 description = klass.description
723 except AttributeError:
724 description = "(no description available)"
725
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000726 print(" %-*s %s" % (max_length, cmd, description))
Greg Wardfe6462c2000-04-04 01:40:52 +0000727
728 # print_command_list ()
729
730
731 def print_commands (self):
Greg Wardd5d8a992000-05-23 01:42:17 +0000732 """Print out a help message listing all available commands with a
733 description of each. The list is divided into "standard commands"
734 (listed in distutils.command.__all__) and "extra commands"
735 (mentioned in self.cmdclass, but not a standard command). The
736 descriptions come from the command class attribute
737 'description'.
738 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000739
740 import distutils.command
741 std_commands = distutils.command.__all__
742 is_std = {}
743 for cmd in std_commands:
744 is_std[cmd] = 1
745
746 extra_commands = []
747 for cmd in self.cmdclass.keys():
748 if not is_std.get(cmd):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000749 extra_commands.append(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000750
751 max_length = 0
752 for cmd in (std_commands + extra_commands):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000753 if len(cmd) > max_length:
754 max_length = len(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000755
Greg Wardfd7b91e2000-09-26 01:52:25 +0000756 self.print_command_list(std_commands,
757 "Standard commands",
758 max_length)
Greg Wardfe6462c2000-04-04 01:40:52 +0000759 if extra_commands:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000760 print()
Greg Wardfd7b91e2000-09-26 01:52:25 +0000761 self.print_command_list(extra_commands,
762 "Extra commands",
763 max_length)
Greg Wardfe6462c2000-04-04 01:40:52 +0000764
765 # print_commands ()
Greg Wardfe6462c2000-04-04 01:40:52 +0000766
Greg Wardf6fc8752000-11-11 02:47:11 +0000767 def get_command_list (self):
768 """Get a list of (command, description) tuples.
769 The list is divided into "standard commands" (listed in
770 distutils.command.__all__) and "extra commands" (mentioned in
771 self.cmdclass, but not a standard command). The descriptions come
772 from the command class attribute 'description'.
773 """
774 # Currently this is only used on Mac OS, for the Mac-only GUI
775 # Distutils interface (by Jack Jansen)
776
777 import distutils.command
778 std_commands = distutils.command.__all__
779 is_std = {}
780 for cmd in std_commands:
781 is_std[cmd] = 1
782
783 extra_commands = []
784 for cmd in self.cmdclass.keys():
785 if not is_std.get(cmd):
786 extra_commands.append(cmd)
787
788 rv = []
789 for cmd in (std_commands + extra_commands):
790 klass = self.cmdclass.get(cmd)
791 if not klass:
792 klass = self.get_command_class(cmd)
793 try:
794 description = klass.description
795 except AttributeError:
796 description = "(no description available)"
797 rv.append((cmd, description))
798 return rv
Greg Wardfe6462c2000-04-04 01:40:52 +0000799
800 # -- Command class/object methods ----------------------------------
801
Fred Draked04573f2004-08-03 16:37:40 +0000802 def get_command_packages (self):
803 """Return a list of packages from which commands are loaded."""
804 pkgs = self.command_packages
805 if not isinstance(pkgs, type([])):
806 pkgs = string.split(pkgs or "", ",")
807 for i in range(len(pkgs)):
808 pkgs[i] = string.strip(pkgs[i])
809 pkgs = filter(None, pkgs)
810 if "distutils.command" not in pkgs:
811 pkgs.insert(0, "distutils.command")
812 self.command_packages = pkgs
813 return pkgs
814
Greg Wardd5d8a992000-05-23 01:42:17 +0000815 def get_command_class (self, command):
816 """Return the class that implements the Distutils command named by
817 'command'. First we check the 'cmdclass' dictionary; if the
818 command is mentioned there, we fetch the class object from the
819 dictionary and return it. Otherwise we load the command module
820 ("distutils.command." + command) and fetch the command class from
821 the module. The loaded class is also stored in 'cmdclass'
822 to speed future calls to 'get_command_class()'.
Greg Wardfe6462c2000-04-04 01:40:52 +0000823
Gregory P. Smith14263542000-05-12 00:41:33 +0000824 Raises DistutilsModuleError if the expected module could not be
Greg Wardd5d8a992000-05-23 01:42:17 +0000825 found, or if that module does not define the expected class.
826 """
827 klass = self.cmdclass.get(command)
828 if klass:
829 return klass
Greg Wardfe6462c2000-04-04 01:40:52 +0000830
Fred Draked04573f2004-08-03 16:37:40 +0000831 for pkgname in self.get_command_packages():
832 module_name = "%s.%s" % (pkgname, command)
833 klass_name = command
Greg Wardfe6462c2000-04-04 01:40:52 +0000834
Fred Draked04573f2004-08-03 16:37:40 +0000835 try:
836 __import__ (module_name)
837 module = sys.modules[module_name]
838 except ImportError:
839 continue
Greg Wardfe6462c2000-04-04 01:40:52 +0000840
Fred Draked04573f2004-08-03 16:37:40 +0000841 try:
842 klass = getattr(module, klass_name)
843 except AttributeError:
844 raise DistutilsModuleError, \
845 "invalid command '%s' (no class '%s' in module '%s')" \
846 % (command, klass_name, module_name)
Greg Wardfe6462c2000-04-04 01:40:52 +0000847
Fred Draked04573f2004-08-03 16:37:40 +0000848 self.cmdclass[command] = klass
849 return klass
850
851 raise DistutilsModuleError("invalid command '%s'" % command)
852
Greg Wardfe6462c2000-04-04 01:40:52 +0000853
Greg Wardd5d8a992000-05-23 01:42:17 +0000854 # get_command_class ()
Greg Wardfe6462c2000-04-04 01:40:52 +0000855
Greg Wardd5d8a992000-05-23 01:42:17 +0000856 def get_command_obj (self, command, create=1):
857 """Return the command object for 'command'. Normally this object
Greg Ward612eb9f2000-07-27 02:13:20 +0000858 is cached on a previous call to 'get_command_obj()'; if no command
Greg Wardd5d8a992000-05-23 01:42:17 +0000859 object for 'command' is in the cache, then we either create and
860 return it (if 'create' is true) or return None.
861 """
862 cmd_obj = self.command_obj.get(command)
Greg Wardfe6462c2000-04-04 01:40:52 +0000863 if not cmd_obj and create:
Greg Ward2bd3f422000-06-02 01:59:33 +0000864 if DEBUG:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000865 print("Distribution.get_command_obj(): " \
866 "creating '%s' command object" % command)
Greg Ward47460772000-05-23 03:47:35 +0000867
Greg Wardd5d8a992000-05-23 01:42:17 +0000868 klass = self.get_command_class(command)
Greg Ward47460772000-05-23 03:47:35 +0000869 cmd_obj = self.command_obj[command] = klass(self)
870 self.have_run[command] = 0
871
872 # Set any options that were supplied in config files
873 # or on the command line. (NB. support for error
874 # reporting is lame here: any errors aren't reported
875 # until 'finalize_options()' is called, which means
876 # we won't report the source of the error.)
877 options = self.command_options.get(command)
878 if options:
Greg Wardc32d9a62000-05-28 23:53:06 +0000879 self._set_command_options(cmd_obj, options)
Greg Wardfe6462c2000-04-04 01:40:52 +0000880
881 return cmd_obj
882
Greg Wardc32d9a62000-05-28 23:53:06 +0000883 def _set_command_options (self, command_obj, option_dict=None):
Greg Wardc32d9a62000-05-28 23:53:06 +0000884 """Set the options for 'command_obj' from 'option_dict'. Basically
885 this means copying elements of a dictionary ('option_dict') to
886 attributes of an instance ('command').
887
Greg Wardceb9e222000-09-25 01:23:52 +0000888 'command_obj' must be a Command instance. If 'option_dict' is not
Greg Wardc32d9a62000-05-28 23:53:06 +0000889 supplied, uses the standard option dictionary for this command
890 (from 'self.command_options').
891 """
Greg Wardc32d9a62000-05-28 23:53:06 +0000892 command_name = command_obj.get_command_name()
893 if option_dict is None:
894 option_dict = self.get_option_dict(command_name)
895
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000896 if DEBUG: print(" setting options for '%s' command:" % command_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000897 for (option, (source, value)) in option_dict.items():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000898 if DEBUG: print(" %s = %s (from %s)" % (option, value, source))
Greg Wardceb9e222000-09-25 01:23:52 +0000899 try:
Greg Ward2f2b6c62000-09-25 01:58:07 +0000900 bool_opts = map(translate_longopt, command_obj.boolean_options)
Greg Wardceb9e222000-09-25 01:23:52 +0000901 except AttributeError:
902 bool_opts = []
903 try:
904 neg_opt = command_obj.negative_opt
905 except AttributeError:
906 neg_opt = {}
907
908 try:
Greg Ward2c08cf02000-09-27 00:15:37 +0000909 is_string = type(value) is StringType
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000910 if option in neg_opt and is_string:
Greg Wardceb9e222000-09-25 01:23:52 +0000911 setattr(command_obj, neg_opt[option], not strtobool(value))
Greg Ward2c08cf02000-09-27 00:15:37 +0000912 elif option in bool_opts and is_string:
Greg Wardceb9e222000-09-25 01:23:52 +0000913 setattr(command_obj, option, strtobool(value))
914 elif hasattr(command_obj, option):
915 setattr(command_obj, option, value)
916 else:
917 raise DistutilsOptionError, \
918 ("error in %s: command '%s' has no such option '%s'"
919 % (source, command_name, option))
Guido van Rossumb940e112007-01-10 16:19:56 +0000920 except ValueError as msg:
Greg Wardceb9e222000-09-25 01:23:52 +0000921 raise DistutilsOptionError, msg
Greg Wardc32d9a62000-05-28 23:53:06 +0000922
Greg Wardf449ea52000-09-16 15:23:28 +0000923 def reinitialize_command (self, command, reinit_subcommands=0):
Greg Wardc32d9a62000-05-28 23:53:06 +0000924 """Reinitializes a command to the state it was in when first
925 returned by 'get_command_obj()': ie., initialized but not yet
Greg Ward7d9c7052000-06-28 01:25:27 +0000926 finalized. This provides the opportunity to sneak option
Greg Wardc32d9a62000-05-28 23:53:06 +0000927 values in programmatically, overriding or supplementing
928 user-supplied values from the config files and command line.
929 You'll have to re-finalize the command object (by calling
930 'finalize_options()' or 'ensure_finalized()') before using it for
Fred Drakeb94b8492001-12-06 20:51:35 +0000931 real.
Greg Wardc32d9a62000-05-28 23:53:06 +0000932
Greg Wardf449ea52000-09-16 15:23:28 +0000933 'command' should be a command name (string) or command object. If
934 'reinit_subcommands' is true, also reinitializes the command's
935 sub-commands, as declared by the 'sub_commands' class attribute (if
936 it has one). See the "install" command for an example. Only
937 reinitializes the sub-commands that actually matter, ie. those
938 whose test predicates return true.
939
Greg Wardc32d9a62000-05-28 23:53:06 +0000940 Returns the reinitialized command object.
941 """
942 from distutils.cmd import Command
943 if not isinstance(command, Command):
944 command_name = command
945 command = self.get_command_obj(command_name)
946 else:
947 command_name = command.get_command_name()
948
949 if not command.finalized:
Greg Ward282c7a02000-06-01 01:09:47 +0000950 return command
Greg Wardc32d9a62000-05-28 23:53:06 +0000951 command.initialize_options()
952 command.finalized = 0
Greg Ward43955c92000-06-06 02:52:36 +0000953 self.have_run[command_name] = 0
Greg Wardc32d9a62000-05-28 23:53:06 +0000954 self._set_command_options(command)
Greg Wardf449ea52000-09-16 15:23:28 +0000955
Greg Wardf449ea52000-09-16 15:23:28 +0000956 if reinit_subcommands:
Greg Wardf449ea52000-09-16 15:23:28 +0000957 for sub in command.get_sub_commands():
Fred Drakeb94b8492001-12-06 20:51:35 +0000958 self.reinitialize_command(sub, reinit_subcommands)
Greg Wardf449ea52000-09-16 15:23:28 +0000959
Greg Wardc32d9a62000-05-28 23:53:06 +0000960 return command
961
Fred Drakeb94b8492001-12-06 20:51:35 +0000962
Greg Wardfe6462c2000-04-04 01:40:52 +0000963 # -- Methods that operate on the Distribution ----------------------
964
965 def announce (self, msg, level=1):
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000966 log.debug(msg)
Greg Wardfe6462c2000-04-04 01:40:52 +0000967
968 def run_commands (self):
Greg Ward82715e12000-04-21 02:28:14 +0000969 """Run each command that was seen on the setup script command line.
Greg Wardd5d8a992000-05-23 01:42:17 +0000970 Uses the list of commands found and cache of command objects
Greg Wardfd7b91e2000-09-26 01:52:25 +0000971 created by 'get_command_obj()'.
972 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000973 for cmd in self.commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000974 self.run_command(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000975
976
Greg Wardfe6462c2000-04-04 01:40:52 +0000977 # -- Methods that operate on its Commands --------------------------
978
979 def run_command (self, command):
Greg Wardfe6462c2000-04-04 01:40:52 +0000980 """Do whatever it takes to run a command (including nothing at all,
Greg Wardd5d8a992000-05-23 01:42:17 +0000981 if the command has already been run). Specifically: if we have
982 already created and run the command named by 'command', return
983 silently without doing anything. If the command named by 'command'
984 doesn't even have a command object yet, create one. Then invoke
985 'run()' on that command object (or an existing one).
986 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000987 # Already been here, done that? then return silently.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000988 if self.have_run.get(command):
Greg Wardfe6462c2000-04-04 01:40:52 +0000989 return
990
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000991 log.info("running %s", command)
Greg Wardfd7b91e2000-09-26 01:52:25 +0000992 cmd_obj = self.get_command_obj(command)
993 cmd_obj.ensure_finalized()
994 cmd_obj.run()
Greg Wardfe6462c2000-04-04 01:40:52 +0000995 self.have_run[command] = 1
996
997
Greg Wardfe6462c2000-04-04 01:40:52 +0000998 # -- Distribution query methods ------------------------------------
999
1000 def has_pure_modules (self):
Greg Wardfd7b91e2000-09-26 01:52:25 +00001001 return len(self.packages or self.py_modules or []) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +00001002
1003 def has_ext_modules (self):
Greg Wardfd7b91e2000-09-26 01:52:25 +00001004 return self.ext_modules and len(self.ext_modules) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +00001005
1006 def has_c_libraries (self):
Greg Wardfd7b91e2000-09-26 01:52:25 +00001007 return self.libraries and len(self.libraries) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +00001008
1009 def has_modules (self):
1010 return self.has_pure_modules() or self.has_ext_modules()
1011
Greg Ward51def7d2000-05-27 01:36:14 +00001012 def has_headers (self):
1013 return self.headers and len(self.headers) > 0
1014
Greg Ward44a61bb2000-05-20 15:06:48 +00001015 def has_scripts (self):
1016 return self.scripts and len(self.scripts) > 0
1017
1018 def has_data_files (self):
1019 return self.data_files and len(self.data_files) > 0
1020
Greg Wardfe6462c2000-04-04 01:40:52 +00001021 def is_pure (self):
1022 return (self.has_pure_modules() and
1023 not self.has_ext_modules() and
1024 not self.has_c_libraries())
1025
Greg Ward82715e12000-04-21 02:28:14 +00001026 # -- Metadata query methods ----------------------------------------
1027
1028 # If you're looking for 'get_name()', 'get_version()', and so forth,
1029 # they are defined in a sneaky way: the constructor binds self.get_XXX
1030 # to self.metadata.get_XXX. The actual code is in the
1031 # DistributionMetadata class, below.
1032
1033# class Distribution
1034
1035
1036class DistributionMetadata:
1037 """Dummy class to hold the distribution meta-data: name, version,
Greg Wardfd7b91e2000-09-26 01:52:25 +00001038 author, and so forth.
1039 """
Greg Ward82715e12000-04-21 02:28:14 +00001040
Neil Schemenauera8aefe52001-09-03 15:47:21 +00001041 _METHOD_BASENAMES = ("name", "version", "author", "author_email",
1042 "maintainer", "maintainer_email", "url",
1043 "license", "description", "long_description",
1044 "keywords", "platforms", "fullname", "contact",
Andrew M. Kuchlinga52b8522003-03-03 20:07:27 +00001045 "contact_email", "license", "classifiers",
Fred Drakedb7b0022005-03-20 22:19:47 +00001046 "download_url",
1047 # PEP 314
1048 "provides", "requires", "obsoletes",
1049 )
Neil Schemenauera8aefe52001-09-03 15:47:21 +00001050
Greg Ward82715e12000-04-21 02:28:14 +00001051 def __init__ (self):
1052 self.name = None
1053 self.version = None
1054 self.author = None
1055 self.author_email = None
1056 self.maintainer = None
1057 self.maintainer_email = None
1058 self.url = None
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +00001059 self.license = None
Greg Ward82715e12000-04-21 02:28:14 +00001060 self.description = None
Greg Warde5a584e2000-04-26 02:26:55 +00001061 self.long_description = None
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001062 self.keywords = None
1063 self.platforms = None
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +00001064 self.classifiers = None
Andrew M. Kuchling188d85f2003-02-19 14:16:01 +00001065 self.download_url = None
Fred Drakedb7b0022005-03-20 22:19:47 +00001066 # PEP 314
1067 self.provides = None
1068 self.requires = None
1069 self.obsoletes = None
Fred Drakeb94b8492001-12-06 20:51:35 +00001070
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001071 def write_pkg_info (self, base_dir):
1072 """Write the PKG-INFO file into the release tree.
1073 """
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001074 pkg_info = open( os.path.join(base_dir, 'PKG-INFO'), 'w')
1075
Fred Drakedb7b0022005-03-20 22:19:47 +00001076 self.write_pkg_file(pkg_info)
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +00001077
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001078 pkg_info.close()
Fred Drakeb94b8492001-12-06 20:51:35 +00001079
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001080 # write_pkg_info ()
Fred Drakeb94b8492001-12-06 20:51:35 +00001081
Fred Drakedb7b0022005-03-20 22:19:47 +00001082 def write_pkg_file (self, file):
1083 """Write the PKG-INFO format data to a file object.
1084 """
1085 version = '1.0'
1086 if self.provides or self.requires or self.obsoletes:
1087 version = '1.1'
1088
1089 file.write('Metadata-Version: %s\n' % version)
1090 file.write('Name: %s\n' % self.get_name() )
1091 file.write('Version: %s\n' % self.get_version() )
1092 file.write('Summary: %s\n' % self.get_description() )
1093 file.write('Home-page: %s\n' % self.get_url() )
1094 file.write('Author: %s\n' % self.get_contact() )
1095 file.write('Author-email: %s\n' % self.get_contact_email() )
1096 file.write('License: %s\n' % self.get_license() )
1097 if self.download_url:
1098 file.write('Download-URL: %s\n' % self.download_url)
1099
1100 long_desc = rfc822_escape( self.get_long_description() )
1101 file.write('Description: %s\n' % long_desc)
1102
1103 keywords = string.join( self.get_keywords(), ',')
1104 if keywords:
1105 file.write('Keywords: %s\n' % keywords )
1106
1107 self._write_list(file, 'Platform', self.get_platforms())
1108 self._write_list(file, 'Classifier', self.get_classifiers())
1109
1110 # PEP 314
1111 self._write_list(file, 'Requires', self.get_requires())
1112 self._write_list(file, 'Provides', self.get_provides())
1113 self._write_list(file, 'Obsoletes', self.get_obsoletes())
1114
1115 def _write_list (self, file, name, values):
1116 for value in values:
1117 file.write('%s: %s\n' % (name, value))
1118
Greg Ward82715e12000-04-21 02:28:14 +00001119 # -- Metadata query methods ----------------------------------------
1120
Greg Wardfe6462c2000-04-04 01:40:52 +00001121 def get_name (self):
1122 return self.name or "UNKNOWN"
1123
Greg Ward82715e12000-04-21 02:28:14 +00001124 def get_version(self):
Thomas Hellerbcd89752001-12-06 20:44:19 +00001125 return self.version or "0.0.0"
Greg Wardfe6462c2000-04-04 01:40:52 +00001126
Greg Ward82715e12000-04-21 02:28:14 +00001127 def get_fullname (self):
1128 return "%s-%s" % (self.get_name(), self.get_version())
1129
1130 def get_author(self):
1131 return self.author or "UNKNOWN"
1132
1133 def get_author_email(self):
1134 return self.author_email or "UNKNOWN"
1135
1136 def get_maintainer(self):
1137 return self.maintainer or "UNKNOWN"
1138
1139 def get_maintainer_email(self):
1140 return self.maintainer_email or "UNKNOWN"
1141
1142 def get_contact(self):
1143 return (self.maintainer or
1144 self.author or
1145 "UNKNOWN")
1146
1147 def get_contact_email(self):
1148 return (self.maintainer_email or
1149 self.author_email or
1150 "UNKNOWN")
1151
1152 def get_url(self):
1153 return self.url or "UNKNOWN"
1154
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +00001155 def get_license(self):
1156 return self.license or "UNKNOWN"
1157 get_licence = get_license
Fred Drakeb94b8492001-12-06 20:51:35 +00001158
Greg Ward82715e12000-04-21 02:28:14 +00001159 def get_description(self):
1160 return self.description or "UNKNOWN"
Greg Warde5a584e2000-04-26 02:26:55 +00001161
1162 def get_long_description(self):
1163 return self.long_description or "UNKNOWN"
1164
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001165 def get_keywords(self):
1166 return self.keywords or []
1167
1168 def get_platforms(self):
1169 return self.platforms or ["UNKNOWN"]
1170
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +00001171 def get_classifiers(self):
1172 return self.classifiers or []
1173
Andrew M. Kuchling188d85f2003-02-19 14:16:01 +00001174 def get_download_url(self):
1175 return self.download_url or "UNKNOWN"
1176
Fred Drakedb7b0022005-03-20 22:19:47 +00001177 # PEP 314
1178
1179 def get_requires(self):
1180 return self.requires or []
1181
1182 def set_requires(self, value):
1183 import distutils.versionpredicate
1184 for v in value:
1185 distutils.versionpredicate.VersionPredicate(v)
1186 self.requires = value
1187
1188 def get_provides(self):
1189 return self.provides or []
1190
1191 def set_provides(self, value):
1192 value = [v.strip() for v in value]
1193 for v in value:
1194 import distutils.versionpredicate
Fred Drake227e8ff2005-03-21 06:36:32 +00001195 distutils.versionpredicate.split_provision(v)
Fred Drakedb7b0022005-03-20 22:19:47 +00001196 self.provides = value
1197
1198 def get_obsoletes(self):
1199 return self.obsoletes or []
1200
1201 def set_obsoletes(self, value):
1202 import distutils.versionpredicate
1203 for v in value:
1204 distutils.versionpredicate.VersionPredicate(v)
1205 self.obsoletes = value
1206
Greg Ward82715e12000-04-21 02:28:14 +00001207# class DistributionMetadata
Greg Wardfe6462c2000-04-04 01:40:52 +00001208
Greg Ward2ff78872000-06-24 00:23:20 +00001209
1210def fix_help_options (options):
1211 """Convert a 4-tuple 'help_options' list as found in various command
1212 classes to the 3-tuple form required by FancyGetopt.
1213 """
1214 new_options = []
1215 for help_tuple in options:
1216 new_options.append(help_tuple[0:3])
1217 return new_options
1218
1219
Greg Wardfe6462c2000-04-04 01:40:52 +00001220if __name__ == "__main__":
Greg Wardfd7b91e2000-09-26 01:52:25 +00001221 dist = Distribution()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001222 print("ok")