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