blob: 8f614765efc2b1343020a3d4e0b4f86714b85ada [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
Neal Norwitz9d72bb42007-04-17 08:48:32 +000011import sys, os, re
Greg Wardfe6462c2000-04-04 01:40:52 +000012from copy import copy
Andrew M. Kuchlingff4ad9a2002-10-31 13:22:41 +000013
14try:
15 import warnings
Andrew M. Kuchlingccf4e422002-10-31 13:39:33 +000016except ImportError:
Andrew M. Kuchlingff4ad9a2002-10-31 13:22:41 +000017 warnings = None
18
Greg Wardfe6462c2000-04-04 01:40:52 +000019from distutils.errors import *
Greg Ward2f2b6c62000-09-25 01:58:07 +000020from distutils.fancy_getopt import FancyGetopt, translate_longopt
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +000021from distutils.util import check_environ, strtobool, rfc822_escape
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000022from distutils import log
Jeremy Hyltonfcd73532002-09-11 16:31:53 +000023from distutils.debug import DEBUG
Greg Wardfe6462c2000-04-04 01:40:52 +000024
25# Regex to define acceptable Distutils command names. This is not *quite*
26# the same as a Python NAME -- I don't allow leading underscores. The fact
27# that they're very similar is no coincidence; the default naming scheme is
28# to look for a Python module named after the command.
29command_re = re.compile (r'^[a-zA-Z]([a-zA-Z0-9_]*)$')
30
31
32class Distribution:
Greg Ward8ff5a3f2000-06-02 00:44:53 +000033 """The core of the Distutils. Most of the work hiding behind 'setup'
34 is really done within a Distribution instance, which farms the work out
35 to the Distutils commands specified on the command line.
Greg Wardfe6462c2000-04-04 01:40:52 +000036
Greg Ward8ff5a3f2000-06-02 00:44:53 +000037 Setup scripts will almost never instantiate Distribution directly,
38 unless the 'setup()' function is totally inadequate to their needs.
39 However, it is conceivable that a setup script might wish to subclass
40 Distribution for some specialized purpose, and then pass the subclass
41 to 'setup()' as the 'distclass' keyword argument. If so, it is
42 necessary to respect the expectations that 'setup' has of Distribution.
43 See the code for 'setup()', in core.py, for details.
44 """
Greg Wardfe6462c2000-04-04 01:40:52 +000045
46
47 # 'global_options' describes the command-line options that may be
Greg Ward82715e12000-04-21 02:28:14 +000048 # supplied to the setup script prior to any actual commands.
49 # Eg. "./setup.py -n" or "./setup.py --quiet" both take advantage of
Greg Wardfe6462c2000-04-04 01:40:52 +000050 # these global options. This list should be kept to a bare minimum,
51 # since every global option is also valid as a command option -- and we
52 # don't want to pollute the commands with too many options that they
53 # have minimal control over.
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000054 # The fourth entry for verbose means that it can be repeated.
55 global_options = [('verbose', 'v', "run verbosely (default)", 1),
Greg Wardd5d8a992000-05-23 01:42:17 +000056 ('quiet', 'q', "run quietly (turns verbosity off)"),
57 ('dry-run', 'n', "don't actually do anything"),
58 ('help', 'h', "show detailed help message"),
Greg Wardfe6462c2000-04-04 01:40:52 +000059 ]
Greg Ward82715e12000-04-21 02:28:14 +000060
Martin v. Löwis8ed338a2005-03-03 08:12:27 +000061 # 'common_usage' is a short (2-3 line) string describing the common
62 # usage of the setup script.
63 common_usage = """\
64Common commands: (see '--help-commands' for more)
65
66 setup.py build will build the package underneath 'build/'
67 setup.py install will install the package
68"""
69
Greg Ward82715e12000-04-21 02:28:14 +000070 # options that are not propagated to the commands
71 display_options = [
72 ('help-commands', None,
73 "list all available commands"),
74 ('name', None,
75 "print package name"),
76 ('version', 'V',
77 "print package version"),
78 ('fullname', None,
79 "print <package name>-<version>"),
80 ('author', None,
81 "print the author's name"),
82 ('author-email', None,
83 "print the author's email address"),
84 ('maintainer', None,
85 "print the maintainer's name"),
86 ('maintainer-email', None,
87 "print the maintainer's email address"),
88 ('contact', None,
Greg Wardd5d8a992000-05-23 01:42:17 +000089 "print the maintainer's name if known, else the author's"),
Greg Ward82715e12000-04-21 02:28:14 +000090 ('contact-email', None,
Greg Wardd5d8a992000-05-23 01:42:17 +000091 "print the maintainer's email address if known, else the author's"),
Greg Ward82715e12000-04-21 02:28:14 +000092 ('url', None,
93 "print the URL for this package"),
Greg Ward82715e12000-04-21 02:28:14 +000094 ('license', None,
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +000095 "print the license of the package"),
96 ('licence', None,
97 "alias for --license"),
Greg Ward82715e12000-04-21 02:28:14 +000098 ('description', None,
99 "print the package description"),
Greg Warde5a584e2000-04-26 02:26:55 +0000100 ('long-description', None,
101 "print the long package description"),
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000102 ('platforms', None,
103 "print the list of platforms"),
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +0000104 ('classifiers', None,
105 "print the list of classifiers"),
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000106 ('keywords', None,
107 "print the list of keywords"),
Fred Drakedb7b0022005-03-20 22:19:47 +0000108 ('provides', None,
109 "print the list of packages/modules provided"),
110 ('requires', None,
111 "print the list of packages/modules required"),
112 ('obsoletes', None,
113 "print the list of packages/modules made obsolete")
Greg Ward82715e12000-04-21 02:28:14 +0000114 ]
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000115 display_option_names = [translate_longopt(x[0]) for x in display_options]
Greg Ward82715e12000-04-21 02:28:14 +0000116
117 # negative options are options that exclude other options
Greg Wardfe6462c2000-04-04 01:40:52 +0000118 negative_opt = {'quiet': 'verbose'}
119
120
121 # -- Creation/initialization methods -------------------------------
Fred Drakeb94b8492001-12-06 20:51:35 +0000122
Greg Wardfe6462c2000-04-04 01:40:52 +0000123 def __init__ (self, attrs=None):
124 """Construct a new Distribution instance: initialize all the
Greg Ward8ff5a3f2000-06-02 00:44:53 +0000125 attributes of a Distribution, and then use 'attrs' (a dictionary
126 mapping attribute names to values) to assign some of those
127 attributes their "real" values. (Any attributes not mentioned in
128 'attrs' will be assigned to some null value: 0, None, an empty list
129 or dictionary, etc.) Most importantly, initialize the
130 'command_obj' attribute to the empty dictionary; this will be
131 filled in with real command objects by 'parse_command_line()'.
132 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000133
134 # Default values for our command-line options
135 self.verbose = 1
136 self.dry_run = 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000137 self.help = 0
Greg Ward82715e12000-04-21 02:28:14 +0000138 for attr in self.display_option_names:
139 setattr(self, attr, 0)
Greg Wardfe6462c2000-04-04 01:40:52 +0000140
Greg Ward82715e12000-04-21 02:28:14 +0000141 # Store the distribution meta-data (name, version, author, and so
142 # forth) in a separate object -- we're getting to have enough
143 # information here (and enough command-line options) that it's
144 # worth it. Also delegate 'get_XXX()' methods to the 'metadata'
145 # object in a sneaky and underhanded (but efficient!) way.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000146 self.metadata = DistributionMetadata()
Neil Schemenauera8aefe52001-09-03 15:47:21 +0000147 for basename in self.metadata._METHOD_BASENAMES:
Greg Ward4982f982000-04-22 02:52:44 +0000148 method_name = "get_" + basename
149 setattr(self, method_name, getattr(self.metadata, method_name))
Greg Wardfe6462c2000-04-04 01:40:52 +0000150
151 # 'cmdclass' maps command names to class objects, so we
152 # can 1) quickly figure out which class to instantiate when
153 # we need to create a new command object, and 2) have a way
Greg Ward82715e12000-04-21 02:28:14 +0000154 # for the setup script to override command classes
Greg Wardfe6462c2000-04-04 01:40:52 +0000155 self.cmdclass = {}
156
Fred Draked04573f2004-08-03 16:37:40 +0000157 # 'command_packages' is a list of packages in which commands
158 # are searched for. The factory for command 'foo' is expected
159 # to be named 'foo' in the module 'foo' in one of the packages
160 # named here. This list is searched from the left; an error
161 # is raised if no named package provides the command being
162 # searched for. (Always access using get_command_packages().)
163 self.command_packages = None
164
Greg Ward9821bf42000-08-29 01:15:18 +0000165 # 'script_name' and 'script_args' are usually set to sys.argv[0]
166 # and sys.argv[1:], but they can be overridden when the caller is
167 # not necessarily a setup script run from the command-line.
168 self.script_name = None
169 self.script_args = None
170
Greg Wardd5d8a992000-05-23 01:42:17 +0000171 # 'command_options' is where we store command options between
172 # parsing them (from config files, the command-line, etc.) and when
173 # they are actually needed -- ie. when the command in question is
174 # instantiated. It is a dictionary of dictionaries of 2-tuples:
175 # command_options = { command_name : { option : (source, value) } }
Gregory P. Smith14263542000-05-12 00:41:33 +0000176 self.command_options = {}
177
Martin v. Löwis98da5622005-03-23 18:54:36 +0000178 # 'dist_files' is the list of (command, pyversion, file) that
179 # have been created by any dist commands run so far. This is
180 # filled regardless of whether the run is dry or not. pyversion
181 # gives sysconfig.get_python_version() if the dist file is
182 # specific to a Python version, 'any' if it is good for all
183 # Python versions on the target platform, and '' for a source
184 # file. pyversion should not be used to specify minimum or
185 # maximum required Python versions; use the metainfo for that
186 # instead.
Martin v. Löwis55f1bb82005-03-21 20:56:35 +0000187 self.dist_files = []
188
Greg Wardfe6462c2000-04-04 01:40:52 +0000189 # These options are really the business of various commands, rather
190 # than of the Distribution itself. We provide aliases for them in
191 # Distribution as a convenience to the developer.
Greg Wardfe6462c2000-04-04 01:40:52 +0000192 self.packages = None
Fred Drake0eb32a62004-06-11 21:50:33 +0000193 self.package_data = {}
Greg Wardfe6462c2000-04-04 01:40:52 +0000194 self.package_dir = None
195 self.py_modules = None
196 self.libraries = None
Greg Ward51def7d2000-05-27 01:36:14 +0000197 self.headers = None
Greg Wardfe6462c2000-04-04 01:40:52 +0000198 self.ext_modules = None
199 self.ext_package = None
200 self.include_dirs = None
201 self.extra_path = None
Gregory P. Smithb2e3bb32000-05-12 00:52:23 +0000202 self.scripts = None
Gregory P. Smith6a901dd2000-05-13 03:09:50 +0000203 self.data_files = None
Greg Wardfe6462c2000-04-04 01:40:52 +0000204
205 # And now initialize bookkeeping stuff that can't be supplied by
206 # the caller at all. 'command_obj' maps command names to
207 # Command instances -- that's how we enforce that every command
208 # class is a singleton.
209 self.command_obj = {}
210
211 # 'have_run' maps command names to boolean values; it keeps track
212 # of whether we have actually run a particular command, to make it
213 # cheap to "run" a command whenever we think we might need to -- if
214 # it's already been done, no need for expensive filesystem
215 # operations, we just check the 'have_run' dictionary and carry on.
216 # It's only safe to query 'have_run' for a command class that has
217 # been instantiated -- a false value will be inserted when the
218 # command object is created, and replaced with a true value when
Greg Ward612eb9f2000-07-27 02:13:20 +0000219 # the command is successfully run. Thus it's probably best to use
Greg Wardfe6462c2000-04-04 01:40:52 +0000220 # '.get()' rather than a straight lookup.
221 self.have_run = {}
222
223 # Now we'll use the attrs dictionary (ultimately, keyword args from
Greg Ward82715e12000-04-21 02:28:14 +0000224 # the setup script) to possibly override any or all of these
225 # distribution options.
226
Greg Wardfe6462c2000-04-04 01:40:52 +0000227 if attrs:
Greg Wardfe6462c2000-04-04 01:40:52 +0000228 # Pull out the set of command options and work on them
229 # specifically. Note that this order guarantees that aliased
230 # command options will override any supplied redundantly
231 # through the general options dictionary.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000232 options = attrs.get('options')
Greg Wardfe6462c2000-04-04 01:40:52 +0000233 if options:
234 del attrs['options']
235 for (command, cmd_options) in options.items():
Greg Ward0e48cfd2000-05-26 01:00:15 +0000236 opt_dict = self.get_option_dict(command)
237 for (opt, val) in cmd_options.items():
238 opt_dict[opt] = ("setup script", val)
Greg Wardfe6462c2000-04-04 01:40:52 +0000239
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000240 if 'licence' in attrs:
Andrew M. Kuchlinga52b8522003-03-03 20:07:27 +0000241 attrs['license'] = attrs['licence']
242 del attrs['licence']
243 msg = "'licence' distribution option is deprecated; use 'license'"
244 if warnings is not None:
245 warnings.warn(msg)
246 else:
247 sys.stderr.write(msg + "\n")
248
Greg Wardfe6462c2000-04-04 01:40:52 +0000249 # Now work on the rest of the attributes. Any attribute that's
250 # not already defined is invalid!
251 for (key,val) in attrs.items():
Fred Drakedb7b0022005-03-20 22:19:47 +0000252 if hasattr(self.metadata, "set_" + key):
253 getattr(self.metadata, "set_" + key)(val)
254 elif hasattr(self.metadata, key):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000255 setattr(self.metadata, key, val)
256 elif hasattr(self, key):
257 setattr(self, key, val)
Anthony Baxter73cc8472004-10-13 13:22:34 +0000258 else:
Andrew M. Kuchlingff4ad9a2002-10-31 13:22:41 +0000259 msg = "Unknown distribution option: %s" % repr(key)
260 if warnings is not None:
261 warnings.warn(msg)
262 else:
263 sys.stderr.write(msg + "\n")
Greg Wardfe6462c2000-04-04 01:40:52 +0000264
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000265 self.finalize_options()
Fred Drakeb94b8492001-12-06 20:51:35 +0000266
Greg Wardfe6462c2000-04-04 01:40:52 +0000267 # __init__ ()
268
269
Greg Ward0e48cfd2000-05-26 01:00:15 +0000270 def get_option_dict (self, command):
271 """Get the option dictionary for a given command. If that
272 command's option dictionary hasn't been created yet, then create it
273 and return the new dictionary; otherwise, return the existing
274 option dictionary.
275 """
276
277 dict = self.command_options.get(command)
278 if dict is None:
279 dict = self.command_options[command] = {}
280 return dict
281
282
Greg Wardc32d9a62000-05-28 23:53:06 +0000283 def dump_option_dicts (self, header=None, commands=None, indent=""):
284 from pprint import pformat
285
286 if commands is None: # dump all command option dicts
287 commands = self.command_options.keys()
288 commands.sort()
289
290 if header is not None:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000291 print(indent + header)
Greg Wardc32d9a62000-05-28 23:53:06 +0000292 indent = indent + " "
293
294 if not commands:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000295 print(indent + "no commands known yet")
Greg Wardc32d9a62000-05-28 23:53:06 +0000296 return
297
298 for cmd_name in commands:
299 opt_dict = self.command_options.get(cmd_name)
300 if opt_dict is None:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000301 print(indent + "no option dict for '%s' command" % cmd_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000302 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000303 print(indent + "option dict for '%s' command:" % cmd_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000304 out = pformat(opt_dict)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000305 for line in out.split("\n"):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000306 print(indent + " " + line)
Greg Wardc32d9a62000-05-28 23:53:06 +0000307
308 # dump_option_dicts ()
Fred Drakeb94b8492001-12-06 20:51:35 +0000309
Greg Wardc32d9a62000-05-28 23:53:06 +0000310
311
Greg Wardd5d8a992000-05-23 01:42:17 +0000312 # -- Config file finding/parsing methods ---------------------------
313
Gregory P. Smith14263542000-05-12 00:41:33 +0000314 def find_config_files (self):
315 """Find as many configuration files as should be processed for this
316 platform, and return a list of filenames in the order in which they
317 should be parsed. The filenames returned are guaranteed to exist
318 (modulo nasty race conditions).
319
Andrew M. Kuchlingd303b612001-12-06 16:32:05 +0000320 There are three possible config files: distutils.cfg in the
321 Distutils installation directory (ie. where the top-level
322 Distutils __inst__.py file lives), a file in the user's home
323 directory named .pydistutils.cfg on Unix and pydistutils.cfg
324 on Windows/Mac, and setup.cfg in the current directory.
Greg Wardd5d8a992000-05-23 01:42:17 +0000325 """
Gregory P. Smith14263542000-05-12 00:41:33 +0000326 files = []
Greg Wardacf3f6a2000-06-07 02:26:19 +0000327 check_environ()
Gregory P. Smith14263542000-05-12 00:41:33 +0000328
Greg Ward11696872000-06-07 02:29:03 +0000329 # Where to look for the system-wide Distutils config file
330 sys_dir = os.path.dirname(sys.modules['distutils'].__file__)
331
332 # Look for the system config file
333 sys_file = os.path.join(sys_dir, "distutils.cfg")
Greg Wardacf3f6a2000-06-07 02:26:19 +0000334 if os.path.isfile(sys_file):
335 files.append(sys_file)
Gregory P. Smith14263542000-05-12 00:41:33 +0000336
Greg Ward11696872000-06-07 02:29:03 +0000337 # What to call the per-user config file
338 if os.name == 'posix':
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000339 user_filename = ".pydistutils.cfg"
340 else:
341 user_filename = "pydistutils.cfg"
Greg Wardfa9ff762000-10-14 04:06:40 +0000342
Greg Ward11696872000-06-07 02:29:03 +0000343 # And look for the user config file
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000344 if 'HOME' in os.environ:
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000345 user_file = os.path.join(os.environ.get('HOME'), user_filename)
Gregory P. Smith14263542000-05-12 00:41:33 +0000346 if os.path.isfile(user_file):
347 files.append(user_file)
348
Gregory P. Smith14263542000-05-12 00:41:33 +0000349 # All platforms support local setup.cfg
350 local_file = "setup.cfg"
351 if os.path.isfile(local_file):
352 files.append(local_file)
353
354 return files
355
356 # find_config_files ()
357
358
359 def parse_config_files (self, filenames=None):
360
361 from ConfigParser import ConfigParser
362
363 if filenames is None:
364 filenames = self.find_config_files()
365
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000366 if DEBUG: print("Distribution.parse_config_files():")
Greg Ward47460772000-05-23 03:47:35 +0000367
Gregory P. Smith14263542000-05-12 00:41:33 +0000368 parser = ConfigParser()
Greg Wardd5d8a992000-05-23 01:42:17 +0000369 for filename in filenames:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000370 if DEBUG: print(" reading", filename)
Greg Wardd5d8a992000-05-23 01:42:17 +0000371 parser.read(filename)
372 for section in parser.sections():
373 options = parser.options(section)
Greg Ward0e48cfd2000-05-26 01:00:15 +0000374 opt_dict = self.get_option_dict(section)
Gregory P. Smith14263542000-05-12 00:41:33 +0000375
Greg Wardd5d8a992000-05-23 01:42:17 +0000376 for opt in options:
377 if opt != '__name__':
Greg Wardceb9e222000-09-25 01:23:52 +0000378 val = parser.get(section,opt)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000379 opt = opt.replace('-', '_')
Greg Wardceb9e222000-09-25 01:23:52 +0000380 opt_dict[opt] = (filename, val)
Gregory P. Smith14263542000-05-12 00:41:33 +0000381
Greg Ward47460772000-05-23 03:47:35 +0000382 # Make the ConfigParser forget everything (so we retain
Fred Drakef06116d2004-02-17 22:35:19 +0000383 # the original filenames that options come from)
Greg Ward47460772000-05-23 03:47:35 +0000384 parser.__init__()
Gregory P. Smith14263542000-05-12 00:41:33 +0000385
Greg Wardceb9e222000-09-25 01:23:52 +0000386 # If there was a "global" section in the config file, use it
387 # to set Distribution options.
388
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000389 if 'global' in self.command_options:
Greg Wardceb9e222000-09-25 01:23:52 +0000390 for (opt, (src, val)) in self.command_options['global'].items():
391 alias = self.negative_opt.get(opt)
392 try:
393 if alias:
394 setattr(self, alias, not strtobool(val))
395 elif opt in ('verbose', 'dry_run'): # ugh!
396 setattr(self, opt, strtobool(val))
Fred Draked04573f2004-08-03 16:37:40 +0000397 else:
398 setattr(self, opt, val)
Guido van Rossumb940e112007-01-10 16:19:56 +0000399 except ValueError as msg:
Greg Wardceb9e222000-09-25 01:23:52 +0000400 raise DistutilsOptionError, msg
401
402 # parse_config_files ()
403
Gregory P. Smith14263542000-05-12 00:41:33 +0000404
Greg Wardd5d8a992000-05-23 01:42:17 +0000405 # -- Command-line parsing methods ----------------------------------
406
Greg Ward9821bf42000-08-29 01:15:18 +0000407 def parse_command_line (self):
408 """Parse the setup script's command line, taken from the
409 'script_args' instance attribute (which defaults to 'sys.argv[1:]'
410 -- see 'setup()' in core.py). This list is first processed for
411 "global options" -- options that set attributes of the Distribution
412 instance. Then, it is alternately scanned for Distutils commands
413 and options for that command. Each new command terminates the
414 options for the previous command. The allowed options for a
415 command are determined by the 'user_options' attribute of the
416 command class -- thus, we have to be able to load command classes
417 in order to parse the command line. Any error in that 'options'
418 attribute raises DistutilsGetoptError; any error on the
419 command-line raises DistutilsArgError. If no Distutils commands
420 were found on the command line, raises DistutilsArgError. Return
Greg Wardceb9e222000-09-25 01:23:52 +0000421 true if command-line was successfully parsed and we should carry
Greg Ward9821bf42000-08-29 01:15:18 +0000422 on with executing commands; false if no errors but we shouldn't
423 execute commands (currently, this only happens if user asks for
424 help).
Greg Wardd5d8a992000-05-23 01:42:17 +0000425 """
Andrew M. Kuchling3f819ec2001-01-15 16:09:35 +0000426 #
Fred Drake981a1782001-08-10 18:59:30 +0000427 # We now have enough information to show the Macintosh dialog
428 # that allows the user to interactively specify the "command line".
Andrew M. Kuchling3f819ec2001-01-15 16:09:35 +0000429 #
Fred Draked04573f2004-08-03 16:37:40 +0000430 toplevel_options = self._get_toplevel_options()
Andrew M. Kuchling3f819ec2001-01-15 16:09:35 +0000431 if sys.platform == 'mac':
432 import EasyDialogs
433 cmdlist = self.get_command_list()
434 self.script_args = EasyDialogs.GetArgv(
Fred Draked04573f2004-08-03 16:37:40 +0000435 toplevel_options + self.display_options, cmdlist)
Fred Drakeb94b8492001-12-06 20:51:35 +0000436
Greg Wardfe6462c2000-04-04 01:40:52 +0000437 # We have to parse the command line a bit at a time -- global
438 # options, then the first command, then its options, and so on --
439 # because each command will be handled by a different class, and
Greg Wardd5d8a992000-05-23 01:42:17 +0000440 # the options that are valid for a particular class aren't known
441 # until we have loaded the command class, which doesn't happen
442 # until we know what the command is.
Greg Wardfe6462c2000-04-04 01:40:52 +0000443
444 self.commands = []
Fred Draked04573f2004-08-03 16:37:40 +0000445 parser = FancyGetopt(toplevel_options + self.display_options)
Greg Wardfd7b91e2000-09-26 01:52:25 +0000446 parser.set_negative_aliases(self.negative_opt)
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +0000447 parser.set_aliases({'licence': 'license'})
Greg Wardfd7b91e2000-09-26 01:52:25 +0000448 args = parser.getopt(args=self.script_args, object=self)
Greg Ward82715e12000-04-21 02:28:14 +0000449 option_order = parser.get_option_order()
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000450 log.set_verbosity(self.verbose)
Greg Wardfe6462c2000-04-04 01:40:52 +0000451
Greg Ward82715e12000-04-21 02:28:14 +0000452 # for display options we return immediately
453 if self.handle_display_options(option_order):
Greg Wardfe6462c2000-04-04 01:40:52 +0000454 return
Fred Drakeb94b8492001-12-06 20:51:35 +0000455
Greg Wardfe6462c2000-04-04 01:40:52 +0000456 while args:
Greg Wardd5d8a992000-05-23 01:42:17 +0000457 args = self._parse_command_opts(parser, args)
458 if args is None: # user asked for help (and got it)
Greg Wardfe6462c2000-04-04 01:40:52 +0000459 return
Greg Wardfe6462c2000-04-04 01:40:52 +0000460
Greg Wardd5d8a992000-05-23 01:42:17 +0000461 # Handle the cases of --help as a "global" option, ie.
462 # "setup.py --help" and "setup.py --help command ...". For the
463 # former, we show global options (--verbose, --dry-run, etc.)
464 # and display-only options (--name, --version, etc.); for the
465 # latter, we omit the display-only options and show help for
466 # each command listed on the command line.
Greg Wardfe6462c2000-04-04 01:40:52 +0000467 if self.help:
Greg Wardd5d8a992000-05-23 01:42:17 +0000468 self._show_help(parser,
469 display_options=len(self.commands) == 0,
470 commands=self.commands)
Greg Wardfe6462c2000-04-04 01:40:52 +0000471 return
472
473 # Oops, no commands found -- an end-user error
474 if not self.commands:
475 raise DistutilsArgError, "no commands supplied"
476
477 # All is well: return true
478 return 1
479
480 # parse_command_line()
481
Fred Draked04573f2004-08-03 16:37:40 +0000482 def _get_toplevel_options (self):
483 """Return the non-display options recognized at the top level.
484
485 This includes options that are recognized *only* at the top
486 level as well as options recognized for commands.
487 """
488 return self.global_options + [
489 ("command-packages=", None,
490 "list of packages that provide distutils commands"),
491 ]
492
Greg Wardd5d8a992000-05-23 01:42:17 +0000493 def _parse_command_opts (self, parser, args):
Greg Wardd5d8a992000-05-23 01:42:17 +0000494 """Parse the command-line options for a single command.
495 'parser' must be a FancyGetopt instance; 'args' must be the list
496 of arguments, starting with the current command (whose options
497 we are about to parse). Returns a new version of 'args' with
498 the next command at the front of the list; will be the empty
499 list if there are no more commands on the command line. Returns
500 None if the user asked for help on this command.
501 """
502 # late import because of mutual dependence between these modules
503 from distutils.cmd import Command
504
505 # Pull the current command from the head of the command line
506 command = args[0]
Greg Wardfd7b91e2000-09-26 01:52:25 +0000507 if not command_re.match(command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000508 raise SystemExit, "invalid command name '%s'" % command
Greg Wardfd7b91e2000-09-26 01:52:25 +0000509 self.commands.append(command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000510
511 # Dig up the command class that implements this command, so we
512 # 1) know that it's a valid command, and 2) know which options
513 # it takes.
514 try:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000515 cmd_class = self.get_command_class(command)
Guido van Rossumb940e112007-01-10 16:19:56 +0000516 except DistutilsModuleError as msg:
Greg Wardd5d8a992000-05-23 01:42:17 +0000517 raise DistutilsArgError, msg
518
519 # Require that the command class be derived from Command -- want
520 # to be sure that the basic "command" interface is implemented.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000521 if not issubclass(cmd_class, Command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000522 raise DistutilsClassError, \
523 "command class %s must subclass Command" % cmd_class
524
525 # Also make sure that the command object provides a list of its
526 # known options.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000527 if not (hasattr(cmd_class, 'user_options') and
Guido van Rossum13257902007-06-07 23:15:56 +0000528 isinstance(cmd_class.user_options, list)):
Greg Wardd5d8a992000-05-23 01:42:17 +0000529 raise DistutilsClassError, \
530 ("command class %s must provide " +
531 "'user_options' attribute (a list of tuples)") % \
532 cmd_class
533
534 # If the command class has a list of negative alias options,
535 # merge it in with the global negative aliases.
536 negative_opt = self.negative_opt
Greg Wardfd7b91e2000-09-26 01:52:25 +0000537 if hasattr(cmd_class, 'negative_opt'):
538 negative_opt = copy(negative_opt)
539 negative_opt.update(cmd_class.negative_opt)
Greg Wardd5d8a992000-05-23 01:42:17 +0000540
Greg Wardfa9ff762000-10-14 04:06:40 +0000541 # Check for help_options in command class. They have a different
542 # format (tuple of four) so we need to preprocess them here.
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000543 if (hasattr(cmd_class, 'help_options') and
Guido van Rossum13257902007-06-07 23:15:56 +0000544 isinstance(cmd_class.help_options, list)):
Greg Ward2ff78872000-06-24 00:23:20 +0000545 help_options = fix_help_options(cmd_class.help_options)
546 else:
Greg Ward55fced32000-06-24 01:22:41 +0000547 help_options = []
Greg Ward2ff78872000-06-24 00:23:20 +0000548
Greg Ward9d17a7a2000-06-07 03:00:06 +0000549
Greg Wardd5d8a992000-05-23 01:42:17 +0000550 # All commands support the global options too, just by adding
551 # in 'global_options'.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000552 parser.set_option_table(self.global_options +
553 cmd_class.user_options +
554 help_options)
555 parser.set_negative_aliases(negative_opt)
556 (args, opts) = parser.getopt(args[1:])
Greg Ward47460772000-05-23 03:47:35 +0000557 if hasattr(opts, 'help') and opts.help:
Greg Wardd5d8a992000-05-23 01:42:17 +0000558 self._show_help(parser, display_options=0, commands=[cmd_class])
559 return
560
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000561 if (hasattr(cmd_class, 'help_options') and
Guido van Rossum13257902007-06-07 23:15:56 +0000562 isinstance(cmd_class.help_options, list)):
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000563 help_option_found=0
564 for (help_option, short, desc, func) in cmd_class.help_options:
565 if hasattr(opts, parser.get_attr_name(help_option)):
566 help_option_found=1
Greg Wardfa9ff762000-10-14 04:06:40 +0000567 #print "showing help for option %s of command %s" % \
Greg Ward2ff78872000-06-24 00:23:20 +0000568 # (help_option[0],cmd_class)
Greg Ward55fced32000-06-24 01:22:41 +0000569
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000570 if hasattr(func, '__call__'):
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000571 func()
Greg Ward55fced32000-06-24 01:22:41 +0000572 else:
Fred Drake981a1782001-08-10 18:59:30 +0000573 raise DistutilsClassError(
Walter Dörwald70a6b492004-02-12 17:35:32 +0000574 "invalid help function %r for help option '%s': "
Fred Drake981a1782001-08-10 18:59:30 +0000575 "must be a callable object (function, etc.)"
Walter Dörwald70a6b492004-02-12 17:35:32 +0000576 % (func, help_option))
Greg Ward55fced32000-06-24 01:22:41 +0000577
Fred Drakeb94b8492001-12-06 20:51:35 +0000578 if help_option_found:
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000579 return
Greg Ward9d17a7a2000-06-07 03:00:06 +0000580
Greg Wardd5d8a992000-05-23 01:42:17 +0000581 # Put the options from the command-line into their official
582 # holding pen, the 'command_options' dictionary.
Greg Ward0e48cfd2000-05-26 01:00:15 +0000583 opt_dict = self.get_option_dict(command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000584 for (name, value) in vars(opts).items():
Greg Ward0e48cfd2000-05-26 01:00:15 +0000585 opt_dict[name] = ("command line", value)
Greg Wardd5d8a992000-05-23 01:42:17 +0000586
587 return args
588
589 # _parse_command_opts ()
590
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000591 def finalize_options (self):
592 """Set final values for all the options on the Distribution
593 instance, analogous to the .finalize_options() method of Command
594 objects.
595 """
596
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000597 keywords = self.metadata.keywords
598 if keywords is not None:
Guido van Rossum572dbf82007-04-27 23:53:51 +0000599 if isinstance(keywords, basestring):
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000600 keywordlist = keywords.split(',')
601 self.metadata.keywords = [x.strip() for x in keywordlist]
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000602
603 platforms = self.metadata.platforms
604 if platforms is not None:
Guido van Rossum572dbf82007-04-27 23:53:51 +0000605 if isinstance(platforms, basestring):
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000606 platformlist = platforms.split(',')
607 self.metadata.platforms = [x.strip() for x in platformlist]
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000608
Greg Wardd5d8a992000-05-23 01:42:17 +0000609 def _show_help (self,
610 parser,
611 global_options=1,
612 display_options=1,
613 commands=[]):
614 """Show help for the setup script command-line in the form of
615 several lists of command-line options. 'parser' should be a
616 FancyGetopt instance; do not expect it to be returned in the
617 same state, as its option table will be reset to make it
618 generate the correct help text.
619
620 If 'global_options' is true, lists the global options:
621 --verbose, --dry-run, etc. If 'display_options' is true, lists
622 the "display-only" options: --name, --version, etc. Finally,
623 lists per-command help for every command name or command class
624 in 'commands'.
625 """
626 # late import because of mutual dependence between these modules
Greg Ward9821bf42000-08-29 01:15:18 +0000627 from distutils.core import gen_usage
Greg Wardd5d8a992000-05-23 01:42:17 +0000628 from distutils.cmd import Command
629
630 if global_options:
Fred Draked04573f2004-08-03 16:37:40 +0000631 if display_options:
632 options = self._get_toplevel_options()
633 else:
634 options = self.global_options
635 parser.set_option_table(options)
Martin v. Löwis8ed338a2005-03-03 08:12:27 +0000636 parser.print_help(self.common_usage + "\nGlobal options:")
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000637 print()
Greg Wardd5d8a992000-05-23 01:42:17 +0000638
639 if display_options:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000640 parser.set_option_table(self.display_options)
641 parser.print_help(
Greg Wardd5d8a992000-05-23 01:42:17 +0000642 "Information display options (just display " +
643 "information, ignore any commands)")
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000644 print()
Greg Wardd5d8a992000-05-23 01:42:17 +0000645
646 for command in self.commands:
Guido van Rossum13257902007-06-07 23:15:56 +0000647 if isinstance(command, type) and issubclass(command, Command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000648 klass = command
649 else:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000650 klass = self.get_command_class(command)
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000651 if (hasattr(klass, 'help_options') and
Guido van Rossum13257902007-06-07 23:15:56 +0000652 isinstance(klass.help_options, list)):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000653 parser.set_option_table(klass.user_options +
654 fix_help_options(klass.help_options))
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000655 else:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000656 parser.set_option_table(klass.user_options)
657 parser.print_help("Options for '%s' command:" % klass.__name__)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000658 print()
Greg Wardd5d8a992000-05-23 01:42:17 +0000659
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000660 print(gen_usage(self.script_name))
Greg Wardd5d8a992000-05-23 01:42:17 +0000661 return
662
663 # _show_help ()
Greg Wardfa9ff762000-10-14 04:06:40 +0000664
Greg Wardd5d8a992000-05-23 01:42:17 +0000665
Greg Ward82715e12000-04-21 02:28:14 +0000666 def handle_display_options (self, option_order):
667 """If there were any non-global "display-only" options
Greg Wardd5d8a992000-05-23 01:42:17 +0000668 (--help-commands or the metadata display options) on the command
669 line, display the requested info and return true; else return
670 false.
671 """
Greg Ward9821bf42000-08-29 01:15:18 +0000672 from distutils.core import gen_usage
Greg Ward82715e12000-04-21 02:28:14 +0000673
674 # User just wants a list of commands -- we'll print it out and stop
675 # processing now (ie. if they ran "setup --help-commands foo bar",
676 # we ignore "foo bar").
677 if self.help_commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000678 self.print_commands()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000679 print()
680 print(gen_usage(self.script_name))
Greg Ward82715e12000-04-21 02:28:14 +0000681 return 1
682
683 # If user supplied any of the "display metadata" options, then
684 # display that metadata in the order in which the user supplied the
685 # metadata options.
686 any_display_options = 0
687 is_display_option = {}
688 for option in self.display_options:
689 is_display_option[option[0]] = 1
690
691 for (opt, val) in option_order:
692 if val and is_display_option.get(opt):
Greg Ward2f2b6c62000-09-25 01:58:07 +0000693 opt = translate_longopt(opt)
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000694 value = getattr(self.metadata, "get_"+opt)()
695 if opt in ['keywords', 'platforms']:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000696 print(','.join(value))
Fred Drakedb7b0022005-03-20 22:19:47 +0000697 elif opt in ('classifiers', 'provides', 'requires',
698 'obsoletes'):
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000699 print('\n'.join(value))
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000700 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000701 print(value)
Greg Ward82715e12000-04-21 02:28:14 +0000702 any_display_options = 1
703
704 return any_display_options
705
706 # handle_display_options()
Greg Wardfe6462c2000-04-04 01:40:52 +0000707
708 def print_command_list (self, commands, header, max_length):
709 """Print a subset of the list of all commands -- used by
Greg Wardd5d8a992000-05-23 01:42:17 +0000710 'print_commands()'.
711 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000712
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000713 print(header + ":")
Greg Wardfe6462c2000-04-04 01:40:52 +0000714
715 for cmd in commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000716 klass = self.cmdclass.get(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000717 if not klass:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000718 klass = self.get_command_class(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000719 try:
720 description = klass.description
721 except AttributeError:
722 description = "(no description available)"
723
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000724 print(" %-*s %s" % (max_length, cmd, description))
Greg Wardfe6462c2000-04-04 01:40:52 +0000725
726 # print_command_list ()
727
728
729 def print_commands (self):
Greg Wardd5d8a992000-05-23 01:42:17 +0000730 """Print out a help message listing all available commands with a
731 description of each. The list is divided into "standard commands"
732 (listed in distutils.command.__all__) and "extra commands"
733 (mentioned in self.cmdclass, but not a standard command). The
734 descriptions come from the command class attribute
735 'description'.
736 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000737
738 import distutils.command
739 std_commands = distutils.command.__all__
740 is_std = {}
741 for cmd in std_commands:
742 is_std[cmd] = 1
743
744 extra_commands = []
745 for cmd in self.cmdclass.keys():
746 if not is_std.get(cmd):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000747 extra_commands.append(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000748
749 max_length = 0
750 for cmd in (std_commands + extra_commands):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000751 if len(cmd) > max_length:
752 max_length = len(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000753
Greg Wardfd7b91e2000-09-26 01:52:25 +0000754 self.print_command_list(std_commands,
755 "Standard commands",
756 max_length)
Greg Wardfe6462c2000-04-04 01:40:52 +0000757 if extra_commands:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000758 print()
Greg Wardfd7b91e2000-09-26 01:52:25 +0000759 self.print_command_list(extra_commands,
760 "Extra commands",
761 max_length)
Greg Wardfe6462c2000-04-04 01:40:52 +0000762
763 # print_commands ()
Greg Wardfe6462c2000-04-04 01:40:52 +0000764
Greg Wardf6fc8752000-11-11 02:47:11 +0000765 def get_command_list (self):
766 """Get a list of (command, description) tuples.
767 The list is divided into "standard commands" (listed in
768 distutils.command.__all__) and "extra commands" (mentioned in
769 self.cmdclass, but not a standard command). The descriptions come
770 from the command class attribute 'description'.
771 """
772 # Currently this is only used on Mac OS, for the Mac-only GUI
773 # Distutils interface (by Jack Jansen)
774
775 import distutils.command
776 std_commands = distutils.command.__all__
777 is_std = {}
778 for cmd in std_commands:
779 is_std[cmd] = 1
780
781 extra_commands = []
782 for cmd in self.cmdclass.keys():
783 if not is_std.get(cmd):
784 extra_commands.append(cmd)
785
786 rv = []
787 for cmd in (std_commands + extra_commands):
788 klass = self.cmdclass.get(cmd)
789 if not klass:
790 klass = self.get_command_class(cmd)
791 try:
792 description = klass.description
793 except AttributeError:
794 description = "(no description available)"
795 rv.append((cmd, description))
796 return rv
Greg Wardfe6462c2000-04-04 01:40:52 +0000797
798 # -- Command class/object methods ----------------------------------
799
Fred Draked04573f2004-08-03 16:37:40 +0000800 def get_command_packages (self):
801 """Return a list of packages from which commands are loaded."""
802 pkgs = self.command_packages
803 if not isinstance(pkgs, type([])):
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000804 pkgs = (pkgs or "").split(",")
Fred Draked04573f2004-08-03 16:37:40 +0000805 for i in range(len(pkgs)):
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000806 pkgs[i] = pkgs[i].strip()
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000807 pkgs = [p for p in pkgs if p]
Fred Draked04573f2004-08-03 16:37:40 +0000808 if "distutils.command" not in pkgs:
809 pkgs.insert(0, "distutils.command")
810 self.command_packages = pkgs
811 return pkgs
812
Greg Wardd5d8a992000-05-23 01:42:17 +0000813 def get_command_class (self, command):
814 """Return the class that implements the Distutils command named by
815 'command'. First we check the 'cmdclass' dictionary; if the
816 command is mentioned there, we fetch the class object from the
817 dictionary and return it. Otherwise we load the command module
818 ("distutils.command." + command) and fetch the command class from
819 the module. The loaded class is also stored in 'cmdclass'
820 to speed future calls to 'get_command_class()'.
Greg Wardfe6462c2000-04-04 01:40:52 +0000821
Gregory P. Smith14263542000-05-12 00:41:33 +0000822 Raises DistutilsModuleError if the expected module could not be
Greg Wardd5d8a992000-05-23 01:42:17 +0000823 found, or if that module does not define the expected class.
824 """
825 klass = self.cmdclass.get(command)
826 if klass:
827 return klass
Greg Wardfe6462c2000-04-04 01:40:52 +0000828
Fred Draked04573f2004-08-03 16:37:40 +0000829 for pkgname in self.get_command_packages():
830 module_name = "%s.%s" % (pkgname, command)
831 klass_name = command
Greg Wardfe6462c2000-04-04 01:40:52 +0000832
Fred Draked04573f2004-08-03 16:37:40 +0000833 try:
834 __import__ (module_name)
835 module = sys.modules[module_name]
836 except ImportError:
837 continue
Greg Wardfe6462c2000-04-04 01:40:52 +0000838
Fred Draked04573f2004-08-03 16:37:40 +0000839 try:
840 klass = getattr(module, klass_name)
841 except AttributeError:
842 raise DistutilsModuleError, \
843 "invalid command '%s' (no class '%s' in module '%s')" \
844 % (command, klass_name, module_name)
Greg Wardfe6462c2000-04-04 01:40:52 +0000845
Fred Draked04573f2004-08-03 16:37:40 +0000846 self.cmdclass[command] = klass
847 return klass
848
849 raise DistutilsModuleError("invalid command '%s'" % command)
850
Greg Wardfe6462c2000-04-04 01:40:52 +0000851
Greg Wardd5d8a992000-05-23 01:42:17 +0000852 # get_command_class ()
Greg Wardfe6462c2000-04-04 01:40:52 +0000853
Greg Wardd5d8a992000-05-23 01:42:17 +0000854 def get_command_obj (self, command, create=1):
855 """Return the command object for 'command'. Normally this object
Greg Ward612eb9f2000-07-27 02:13:20 +0000856 is cached on a previous call to 'get_command_obj()'; if no command
Greg Wardd5d8a992000-05-23 01:42:17 +0000857 object for 'command' is in the cache, then we either create and
858 return it (if 'create' is true) or return None.
859 """
860 cmd_obj = self.command_obj.get(command)
Greg Wardfe6462c2000-04-04 01:40:52 +0000861 if not cmd_obj and create:
Greg Ward2bd3f422000-06-02 01:59:33 +0000862 if DEBUG:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000863 print("Distribution.get_command_obj(): " \
864 "creating '%s' command object" % command)
Greg Ward47460772000-05-23 03:47:35 +0000865
Greg Wardd5d8a992000-05-23 01:42:17 +0000866 klass = self.get_command_class(command)
Greg Ward47460772000-05-23 03:47:35 +0000867 cmd_obj = self.command_obj[command] = klass(self)
868 self.have_run[command] = 0
869
870 # Set any options that were supplied in config files
871 # or on the command line. (NB. support for error
872 # reporting is lame here: any errors aren't reported
873 # until 'finalize_options()' is called, which means
874 # we won't report the source of the error.)
875 options = self.command_options.get(command)
876 if options:
Greg Wardc32d9a62000-05-28 23:53:06 +0000877 self._set_command_options(cmd_obj, options)
Greg Wardfe6462c2000-04-04 01:40:52 +0000878
879 return cmd_obj
880
Greg Wardc32d9a62000-05-28 23:53:06 +0000881 def _set_command_options (self, command_obj, option_dict=None):
Greg Wardc32d9a62000-05-28 23:53:06 +0000882 """Set the options for 'command_obj' from 'option_dict'. Basically
883 this means copying elements of a dictionary ('option_dict') to
884 attributes of an instance ('command').
885
Greg Wardceb9e222000-09-25 01:23:52 +0000886 'command_obj' must be a Command instance. If 'option_dict' is not
Greg Wardc32d9a62000-05-28 23:53:06 +0000887 supplied, uses the standard option dictionary for this command
888 (from 'self.command_options').
889 """
Greg Wardc32d9a62000-05-28 23:53:06 +0000890 command_name = command_obj.get_command_name()
891 if option_dict is None:
892 option_dict = self.get_option_dict(command_name)
893
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000894 if DEBUG: print(" setting options for '%s' command:" % command_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000895 for (option, (source, value)) in option_dict.items():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000896 if DEBUG: print(" %s = %s (from %s)" % (option, value, source))
Greg Wardceb9e222000-09-25 01:23:52 +0000897 try:
Greg Ward2f2b6c62000-09-25 01:58:07 +0000898 bool_opts = map(translate_longopt, command_obj.boolean_options)
Greg Wardceb9e222000-09-25 01:23:52 +0000899 except AttributeError:
900 bool_opts = []
901 try:
902 neg_opt = command_obj.negative_opt
903 except AttributeError:
904 neg_opt = {}
905
906 try:
Guido van Rossum572dbf82007-04-27 23:53:51 +0000907 is_string = isinstance(value, basestring)
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000908 if option in neg_opt and is_string:
Greg Wardceb9e222000-09-25 01:23:52 +0000909 setattr(command_obj, neg_opt[option], not strtobool(value))
Greg Ward2c08cf02000-09-27 00:15:37 +0000910 elif option in bool_opts and is_string:
Greg Wardceb9e222000-09-25 01:23:52 +0000911 setattr(command_obj, option, strtobool(value))
912 elif hasattr(command_obj, option):
913 setattr(command_obj, option, value)
914 else:
915 raise DistutilsOptionError, \
916 ("error in %s: command '%s' has no such option '%s'"
917 % (source, command_name, option))
Guido van Rossumb940e112007-01-10 16:19:56 +0000918 except ValueError as msg:
Greg Wardceb9e222000-09-25 01:23:52 +0000919 raise DistutilsOptionError, msg
Greg Wardc32d9a62000-05-28 23:53:06 +0000920
Greg Wardf449ea52000-09-16 15:23:28 +0000921 def reinitialize_command (self, command, reinit_subcommands=0):
Greg Wardc32d9a62000-05-28 23:53:06 +0000922 """Reinitializes a command to the state it was in when first
923 returned by 'get_command_obj()': ie., initialized but not yet
Greg Ward7d9c7052000-06-28 01:25:27 +0000924 finalized. This provides the opportunity to sneak option
Greg Wardc32d9a62000-05-28 23:53:06 +0000925 values in programmatically, overriding or supplementing
926 user-supplied values from the config files and command line.
927 You'll have to re-finalize the command object (by calling
928 'finalize_options()' or 'ensure_finalized()') before using it for
Fred Drakeb94b8492001-12-06 20:51:35 +0000929 real.
Greg Wardc32d9a62000-05-28 23:53:06 +0000930
Greg Wardf449ea52000-09-16 15:23:28 +0000931 'command' should be a command name (string) or command object. If
932 'reinit_subcommands' is true, also reinitializes the command's
933 sub-commands, as declared by the 'sub_commands' class attribute (if
934 it has one). See the "install" command for an example. Only
935 reinitializes the sub-commands that actually matter, ie. those
936 whose test predicates return true.
937
Greg Wardc32d9a62000-05-28 23:53:06 +0000938 Returns the reinitialized command object.
939 """
940 from distutils.cmd import Command
941 if not isinstance(command, Command):
942 command_name = command
943 command = self.get_command_obj(command_name)
944 else:
945 command_name = command.get_command_name()
946
947 if not command.finalized:
Greg Ward282c7a02000-06-01 01:09:47 +0000948 return command
Greg Wardc32d9a62000-05-28 23:53:06 +0000949 command.initialize_options()
950 command.finalized = 0
Greg Ward43955c92000-06-06 02:52:36 +0000951 self.have_run[command_name] = 0
Greg Wardc32d9a62000-05-28 23:53:06 +0000952 self._set_command_options(command)
Greg Wardf449ea52000-09-16 15:23:28 +0000953
Greg Wardf449ea52000-09-16 15:23:28 +0000954 if reinit_subcommands:
Greg Wardf449ea52000-09-16 15:23:28 +0000955 for sub in command.get_sub_commands():
Fred Drakeb94b8492001-12-06 20:51:35 +0000956 self.reinitialize_command(sub, reinit_subcommands)
Greg Wardf449ea52000-09-16 15:23:28 +0000957
Greg Wardc32d9a62000-05-28 23:53:06 +0000958 return command
959
Fred Drakeb94b8492001-12-06 20:51:35 +0000960
Greg Wardfe6462c2000-04-04 01:40:52 +0000961 # -- Methods that operate on the Distribution ----------------------
962
963 def announce (self, msg, level=1):
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000964 log.debug(msg)
Greg Wardfe6462c2000-04-04 01:40:52 +0000965
966 def run_commands (self):
Greg Ward82715e12000-04-21 02:28:14 +0000967 """Run each command that was seen on the setup script command line.
Greg Wardd5d8a992000-05-23 01:42:17 +0000968 Uses the list of commands found and cache of command objects
Greg Wardfd7b91e2000-09-26 01:52:25 +0000969 created by 'get_command_obj()'.
970 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000971 for cmd in self.commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000972 self.run_command(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000973
974
Greg Wardfe6462c2000-04-04 01:40:52 +0000975 # -- Methods that operate on its Commands --------------------------
976
977 def run_command (self, command):
Greg Wardfe6462c2000-04-04 01:40:52 +0000978 """Do whatever it takes to run a command (including nothing at all,
Greg Wardd5d8a992000-05-23 01:42:17 +0000979 if the command has already been run). Specifically: if we have
980 already created and run the command named by 'command', return
981 silently without doing anything. If the command named by 'command'
982 doesn't even have a command object yet, create one. Then invoke
983 'run()' on that command object (or an existing one).
984 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000985 # Already been here, done that? then return silently.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000986 if self.have_run.get(command):
Greg Wardfe6462c2000-04-04 01:40:52 +0000987 return
988
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000989 log.info("running %s", command)
Greg Wardfd7b91e2000-09-26 01:52:25 +0000990 cmd_obj = self.get_command_obj(command)
991 cmd_obj.ensure_finalized()
992 cmd_obj.run()
Greg Wardfe6462c2000-04-04 01:40:52 +0000993 self.have_run[command] = 1
994
995
Greg Wardfe6462c2000-04-04 01:40:52 +0000996 # -- Distribution query methods ------------------------------------
997
998 def has_pure_modules (self):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000999 return len(self.packages or self.py_modules or []) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +00001000
1001 def has_ext_modules (self):
Greg Wardfd7b91e2000-09-26 01:52:25 +00001002 return self.ext_modules and len(self.ext_modules) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +00001003
1004 def has_c_libraries (self):
Greg Wardfd7b91e2000-09-26 01:52:25 +00001005 return self.libraries and len(self.libraries) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +00001006
1007 def has_modules (self):
1008 return self.has_pure_modules() or self.has_ext_modules()
1009
Greg Ward51def7d2000-05-27 01:36:14 +00001010 def has_headers (self):
1011 return self.headers and len(self.headers) > 0
1012
Greg Ward44a61bb2000-05-20 15:06:48 +00001013 def has_scripts (self):
1014 return self.scripts and len(self.scripts) > 0
1015
1016 def has_data_files (self):
1017 return self.data_files and len(self.data_files) > 0
1018
Greg Wardfe6462c2000-04-04 01:40:52 +00001019 def is_pure (self):
1020 return (self.has_pure_modules() and
1021 not self.has_ext_modules() and
1022 not self.has_c_libraries())
1023
Greg Ward82715e12000-04-21 02:28:14 +00001024 # -- Metadata query methods ----------------------------------------
1025
1026 # If you're looking for 'get_name()', 'get_version()', and so forth,
1027 # they are defined in a sneaky way: the constructor binds self.get_XXX
1028 # to self.metadata.get_XXX. The actual code is in the
1029 # DistributionMetadata class, below.
1030
1031# class Distribution
1032
1033
1034class DistributionMetadata:
1035 """Dummy class to hold the distribution meta-data: name, version,
Greg Wardfd7b91e2000-09-26 01:52:25 +00001036 author, and so forth.
1037 """
Greg Ward82715e12000-04-21 02:28:14 +00001038
Neil Schemenauera8aefe52001-09-03 15:47:21 +00001039 _METHOD_BASENAMES = ("name", "version", "author", "author_email",
1040 "maintainer", "maintainer_email", "url",
1041 "license", "description", "long_description",
1042 "keywords", "platforms", "fullname", "contact",
Andrew M. Kuchlinga52b8522003-03-03 20:07:27 +00001043 "contact_email", "license", "classifiers",
Fred Drakedb7b0022005-03-20 22:19:47 +00001044 "download_url",
1045 # PEP 314
1046 "provides", "requires", "obsoletes",
1047 )
Neil Schemenauera8aefe52001-09-03 15:47:21 +00001048
Greg Ward82715e12000-04-21 02:28:14 +00001049 def __init__ (self):
1050 self.name = None
1051 self.version = None
1052 self.author = None
1053 self.author_email = None
1054 self.maintainer = None
1055 self.maintainer_email = None
1056 self.url = None
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +00001057 self.license = None
Greg Ward82715e12000-04-21 02:28:14 +00001058 self.description = None
Greg Warde5a584e2000-04-26 02:26:55 +00001059 self.long_description = None
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001060 self.keywords = None
1061 self.platforms = None
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +00001062 self.classifiers = None
Andrew M. Kuchling188d85f2003-02-19 14:16:01 +00001063 self.download_url = None
Fred Drakedb7b0022005-03-20 22:19:47 +00001064 # PEP 314
1065 self.provides = None
1066 self.requires = None
1067 self.obsoletes = None
Fred Drakeb94b8492001-12-06 20:51:35 +00001068
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001069 def write_pkg_info (self, base_dir):
1070 """Write the PKG-INFO file into the release tree.
1071 """
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001072 pkg_info = open( os.path.join(base_dir, 'PKG-INFO'), 'w')
1073
Fred Drakedb7b0022005-03-20 22:19:47 +00001074 self.write_pkg_file(pkg_info)
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +00001075
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001076 pkg_info.close()
Fred Drakeb94b8492001-12-06 20:51:35 +00001077
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001078 # write_pkg_info ()
Fred Drakeb94b8492001-12-06 20:51:35 +00001079
Fred Drakedb7b0022005-03-20 22:19:47 +00001080 def write_pkg_file (self, file):
1081 """Write the PKG-INFO format data to a file object.
1082 """
1083 version = '1.0'
1084 if self.provides or self.requires or self.obsoletes:
1085 version = '1.1'
1086
1087 file.write('Metadata-Version: %s\n' % version)
1088 file.write('Name: %s\n' % self.get_name() )
1089 file.write('Version: %s\n' % self.get_version() )
1090 file.write('Summary: %s\n' % self.get_description() )
1091 file.write('Home-page: %s\n' % self.get_url() )
1092 file.write('Author: %s\n' % self.get_contact() )
1093 file.write('Author-email: %s\n' % self.get_contact_email() )
1094 file.write('License: %s\n' % self.get_license() )
1095 if self.download_url:
1096 file.write('Download-URL: %s\n' % self.download_url)
1097
1098 long_desc = rfc822_escape( self.get_long_description() )
1099 file.write('Description: %s\n' % long_desc)
1100
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001101 keywords = ','.join(self.get_keywords())
Fred Drakedb7b0022005-03-20 22:19:47 +00001102 if keywords:
1103 file.write('Keywords: %s\n' % keywords )
1104
1105 self._write_list(file, 'Platform', self.get_platforms())
1106 self._write_list(file, 'Classifier', self.get_classifiers())
1107
1108 # PEP 314
1109 self._write_list(file, 'Requires', self.get_requires())
1110 self._write_list(file, 'Provides', self.get_provides())
1111 self._write_list(file, 'Obsoletes', self.get_obsoletes())
1112
1113 def _write_list (self, file, name, values):
1114 for value in values:
1115 file.write('%s: %s\n' % (name, value))
1116
Greg Ward82715e12000-04-21 02:28:14 +00001117 # -- Metadata query methods ----------------------------------------
1118
Greg Wardfe6462c2000-04-04 01:40:52 +00001119 def get_name (self):
1120 return self.name or "UNKNOWN"
1121
Greg Ward82715e12000-04-21 02:28:14 +00001122 def get_version(self):
Thomas Hellerbcd89752001-12-06 20:44:19 +00001123 return self.version or "0.0.0"
Greg Wardfe6462c2000-04-04 01:40:52 +00001124
Greg Ward82715e12000-04-21 02:28:14 +00001125 def get_fullname (self):
1126 return "%s-%s" % (self.get_name(), self.get_version())
1127
1128 def get_author(self):
1129 return self.author or "UNKNOWN"
1130
1131 def get_author_email(self):
1132 return self.author_email or "UNKNOWN"
1133
1134 def get_maintainer(self):
1135 return self.maintainer or "UNKNOWN"
1136
1137 def get_maintainer_email(self):
1138 return self.maintainer_email or "UNKNOWN"
1139
1140 def get_contact(self):
1141 return (self.maintainer or
1142 self.author or
1143 "UNKNOWN")
1144
1145 def get_contact_email(self):
1146 return (self.maintainer_email or
1147 self.author_email or
1148 "UNKNOWN")
1149
1150 def get_url(self):
1151 return self.url or "UNKNOWN"
1152
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +00001153 def get_license(self):
1154 return self.license or "UNKNOWN"
1155 get_licence = get_license
Fred Drakeb94b8492001-12-06 20:51:35 +00001156
Greg Ward82715e12000-04-21 02:28:14 +00001157 def get_description(self):
1158 return self.description or "UNKNOWN"
Greg Warde5a584e2000-04-26 02:26:55 +00001159
1160 def get_long_description(self):
1161 return self.long_description or "UNKNOWN"
1162
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001163 def get_keywords(self):
1164 return self.keywords or []
1165
1166 def get_platforms(self):
1167 return self.platforms or ["UNKNOWN"]
1168
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +00001169 def get_classifiers(self):
1170 return self.classifiers or []
1171
Andrew M. Kuchling188d85f2003-02-19 14:16:01 +00001172 def get_download_url(self):
1173 return self.download_url or "UNKNOWN"
1174
Fred Drakedb7b0022005-03-20 22:19:47 +00001175 # PEP 314
1176
1177 def get_requires(self):
1178 return self.requires or []
1179
1180 def set_requires(self, value):
1181 import distutils.versionpredicate
1182 for v in value:
1183 distutils.versionpredicate.VersionPredicate(v)
1184 self.requires = value
1185
1186 def get_provides(self):
1187 return self.provides or []
1188
1189 def set_provides(self, value):
1190 value = [v.strip() for v in value]
1191 for v in value:
1192 import distutils.versionpredicate
Fred Drake227e8ff2005-03-21 06:36:32 +00001193 distutils.versionpredicate.split_provision(v)
Fred Drakedb7b0022005-03-20 22:19:47 +00001194 self.provides = value
1195
1196 def get_obsoletes(self):
1197 return self.obsoletes or []
1198
1199 def set_obsoletes(self, value):
1200 import distutils.versionpredicate
1201 for v in value:
1202 distutils.versionpredicate.VersionPredicate(v)
1203 self.obsoletes = value
1204
Greg Ward82715e12000-04-21 02:28:14 +00001205# class DistributionMetadata
Greg Wardfe6462c2000-04-04 01:40:52 +00001206
Greg Ward2ff78872000-06-24 00:23:20 +00001207
1208def fix_help_options (options):
1209 """Convert a 4-tuple 'help_options' list as found in various command
1210 classes to the 3-tuple form required by FancyGetopt.
1211 """
1212 new_options = []
1213 for help_tuple in options:
1214 new_options.append(help_tuple[0:3])
1215 return new_options
1216
1217
Greg Wardfe6462c2000-04-04 01:40:52 +00001218if __name__ == "__main__":
Greg Wardfd7b91e2000-09-26 01:52:25 +00001219 dist = Distribution()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001220 print("ok")