blob: f7fac08918b6d8b252fb59487f4eac664dca1a6c [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
Neal Norwitz9d72bb42007-04-17 08:48:32 +00007import sys, os, re
Andrew M. Kuchlingff4ad9a2002-10-31 13:22:41 +00008
9try:
10 import warnings
Andrew M. Kuchlingccf4e422002-10-31 13:39:33 +000011except ImportError:
Andrew M. Kuchlingff4ad9a2002-10-31 13:22:41 +000012 warnings = None
13
Tarek Ziadé36797272010-07-22 12:50:05 +000014from distutils.errors import *
Greg Ward2f2b6c62000-09-25 01:58:07 +000015from distutils.fancy_getopt import FancyGetopt, translate_longopt
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +000016from distutils.util import check_environ, strtobool, rfc822_escape
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000017from distutils import log
Jeremy Hyltonfcd73532002-09-11 16:31:53 +000018from distutils.debug import DEBUG
Greg Wardfe6462c2000-04-04 01:40:52 +000019
20# Regex to define acceptable Distutils command names. This is not *quite*
21# the same as a Python NAME -- I don't allow leading underscores. The fact
22# that they're very similar is no coincidence; the default naming scheme is
23# to look for a Python module named after the command.
24command_re = re.compile (r'^[a-zA-Z]([a-zA-Z0-9_]*)$')
25
26
27class Distribution:
Greg Ward8ff5a3f2000-06-02 00:44:53 +000028 """The core of the Distutils. Most of the work hiding behind 'setup'
29 is really done within a Distribution instance, which farms the work out
30 to the Distutils commands specified on the command line.
Greg Wardfe6462c2000-04-04 01:40:52 +000031
Greg Ward8ff5a3f2000-06-02 00:44:53 +000032 Setup scripts will almost never instantiate Distribution directly,
33 unless the 'setup()' function is totally inadequate to their needs.
34 However, it is conceivable that a setup script might wish to subclass
35 Distribution for some specialized purpose, and then pass the subclass
36 to 'setup()' as the 'distclass' keyword argument. If so, it is
37 necessary to respect the expectations that 'setup' has of Distribution.
38 See the code for 'setup()', in core.py, for details.
39 """
Greg Wardfe6462c2000-04-04 01:40:52 +000040
41
42 # 'global_options' describes the command-line options that may be
Greg Ward82715e12000-04-21 02:28:14 +000043 # supplied to the setup script prior to any actual commands.
44 # Eg. "./setup.py -n" or "./setup.py --quiet" both take advantage of
Greg Wardfe6462c2000-04-04 01:40:52 +000045 # these global options. This list should be kept to a bare minimum,
46 # since every global option is also valid as a command option -- and we
47 # don't want to pollute the commands with too many options that they
48 # have minimal control over.
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000049 # The fourth entry for verbose means that it can be repeated.
50 global_options = [('verbose', 'v', "run verbosely (default)", 1),
Greg Wardd5d8a992000-05-23 01:42:17 +000051 ('quiet', 'q', "run quietly (turns verbosity off)"),
52 ('dry-run', 'n', "don't actually do anything"),
53 ('help', 'h', "show detailed help message"),
Tarek Ziadé36797272010-07-22 12:50:05 +000054 ]
Greg Ward82715e12000-04-21 02:28:14 +000055
Martin v. Löwis8ed338a2005-03-03 08:12:27 +000056 # 'common_usage' is a short (2-3 line) string describing the common
57 # usage of the setup script.
58 common_usage = """\
59Common commands: (see '--help-commands' for more)
60
61 setup.py build will build the package underneath 'build/'
62 setup.py install will install the package
63"""
64
Greg Ward82715e12000-04-21 02:28:14 +000065 # options that are not propagated to the commands
66 display_options = [
67 ('help-commands', None,
68 "list all available commands"),
69 ('name', None,
70 "print package name"),
71 ('version', 'V',
72 "print package version"),
73 ('fullname', None,
74 "print <package name>-<version>"),
75 ('author', None,
76 "print the author's name"),
77 ('author-email', None,
78 "print the author's email address"),
79 ('maintainer', None,
80 "print the maintainer's name"),
81 ('maintainer-email', None,
82 "print the maintainer's email address"),
83 ('contact', None,
Greg Wardd5d8a992000-05-23 01:42:17 +000084 "print the maintainer's name if known, else the author's"),
Greg Ward82715e12000-04-21 02:28:14 +000085 ('contact-email', None,
Greg Wardd5d8a992000-05-23 01:42:17 +000086 "print the maintainer's email address if known, else the author's"),
Greg Ward82715e12000-04-21 02:28:14 +000087 ('url', None,
88 "print the URL for this package"),
Greg Ward82715e12000-04-21 02:28:14 +000089 ('license', None,
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +000090 "print the license of the package"),
91 ('licence', None,
92 "alias for --license"),
Greg Ward82715e12000-04-21 02:28:14 +000093 ('description', None,
94 "print the package description"),
Greg Warde5a584e2000-04-26 02:26:55 +000095 ('long-description', None,
96 "print the long package description"),
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +000097 ('platforms', None,
98 "print the list of platforms"),
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +000099 ('classifiers', None,
100 "print the list of classifiers"),
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000101 ('keywords', None,
102 "print the list of keywords"),
Fred Drakedb7b0022005-03-20 22:19:47 +0000103 ('provides', None,
104 "print the list of packages/modules provided"),
105 ('requires', None,
106 "print the list of packages/modules required"),
107 ('obsoletes', None,
108 "print the list of packages/modules made obsolete")
Greg Ward82715e12000-04-21 02:28:14 +0000109 ]
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000110 display_option_names = [translate_longopt(x[0]) for x in display_options]
Greg Ward82715e12000-04-21 02:28:14 +0000111
112 # negative options are options that exclude other options
Greg Wardfe6462c2000-04-04 01:40:52 +0000113 negative_opt = {'quiet': 'verbose'}
114
115
116 # -- Creation/initialization methods -------------------------------
Fred Drakeb94b8492001-12-06 20:51:35 +0000117
Greg Wardfe6462c2000-04-04 01:40:52 +0000118 def __init__ (self, attrs=None):
119 """Construct a new Distribution instance: initialize all the
Greg Ward8ff5a3f2000-06-02 00:44:53 +0000120 attributes of a Distribution, and then use 'attrs' (a dictionary
121 mapping attribute names to values) to assign some of those
122 attributes their "real" values. (Any attributes not mentioned in
123 'attrs' will be assigned to some null value: 0, None, an empty list
124 or dictionary, etc.) Most importantly, initialize the
125 'command_obj' attribute to the empty dictionary; this will be
126 filled in with real command objects by 'parse_command_line()'.
127 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000128
129 # Default values for our command-line options
130 self.verbose = 1
131 self.dry_run = 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000132 self.help = 0
Greg Ward82715e12000-04-21 02:28:14 +0000133 for attr in self.display_option_names:
134 setattr(self, attr, 0)
Greg Wardfe6462c2000-04-04 01:40:52 +0000135
Greg Ward82715e12000-04-21 02:28:14 +0000136 # Store the distribution meta-data (name, version, author, and so
137 # forth) in a separate object -- we're getting to have enough
138 # information here (and enough command-line options) that it's
139 # worth it. Also delegate 'get_XXX()' methods to the 'metadata'
140 # object in a sneaky and underhanded (but efficient!) way.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000141 self.metadata = DistributionMetadata()
Neil Schemenauera8aefe52001-09-03 15:47:21 +0000142 for basename in self.metadata._METHOD_BASENAMES:
Greg Ward4982f982000-04-22 02:52:44 +0000143 method_name = "get_" + basename
144 setattr(self, method_name, getattr(self.metadata, method_name))
Greg Wardfe6462c2000-04-04 01:40:52 +0000145
146 # 'cmdclass' maps command names to class objects, so we
147 # can 1) quickly figure out which class to instantiate when
148 # we need to create a new command object, and 2) have a way
Greg Ward82715e12000-04-21 02:28:14 +0000149 # for the setup script to override command classes
Greg Wardfe6462c2000-04-04 01:40:52 +0000150 self.cmdclass = {}
151
Fred Draked04573f2004-08-03 16:37:40 +0000152 # 'command_packages' is a list of packages in which commands
153 # are searched for. The factory for command 'foo' is expected
154 # to be named 'foo' in the module 'foo' in one of the packages
155 # named here. This list is searched from the left; an error
156 # is raised if no named package provides the command being
157 # searched for. (Always access using get_command_packages().)
158 self.command_packages = None
159
Greg Ward9821bf42000-08-29 01:15:18 +0000160 # 'script_name' and 'script_args' are usually set to sys.argv[0]
161 # and sys.argv[1:], but they can be overridden when the caller is
162 # not necessarily a setup script run from the command-line.
163 self.script_name = None
164 self.script_args = None
165
Greg Wardd5d8a992000-05-23 01:42:17 +0000166 # 'command_options' is where we store command options between
167 # parsing them (from config files, the command-line, etc.) and when
168 # they are actually needed -- ie. when the command in question is
169 # instantiated. It is a dictionary of dictionaries of 2-tuples:
170 # command_options = { command_name : { option : (source, value) } }
Gregory P. Smith14263542000-05-12 00:41:33 +0000171 self.command_options = {}
172
Martin v. Löwis98da5622005-03-23 18:54:36 +0000173 # 'dist_files' is the list of (command, pyversion, file) that
174 # have been created by any dist commands run so far. This is
175 # filled regardless of whether the run is dry or not. pyversion
176 # gives sysconfig.get_python_version() if the dist file is
177 # specific to a Python version, 'any' if it is good for all
178 # Python versions on the target platform, and '' for a source
179 # file. pyversion should not be used to specify minimum or
180 # maximum required Python versions; use the metainfo for that
181 # instead.
Martin v. Löwis55f1bb82005-03-21 20:56:35 +0000182 self.dist_files = []
183
Greg Wardfe6462c2000-04-04 01:40:52 +0000184 # These options are really the business of various commands, rather
185 # than of the Distribution itself. We provide aliases for them in
186 # Distribution as a convenience to the developer.
Greg Wardfe6462c2000-04-04 01:40:52 +0000187 self.packages = None
Fred Drake0eb32a62004-06-11 21:50:33 +0000188 self.package_data = {}
Greg Wardfe6462c2000-04-04 01:40:52 +0000189 self.package_dir = None
190 self.py_modules = None
191 self.libraries = None
Greg Ward51def7d2000-05-27 01:36:14 +0000192 self.headers = None
Greg Wardfe6462c2000-04-04 01:40:52 +0000193 self.ext_modules = None
194 self.ext_package = None
195 self.include_dirs = None
196 self.extra_path = None
Gregory P. Smithb2e3bb32000-05-12 00:52:23 +0000197 self.scripts = None
Gregory P. Smith6a901dd2000-05-13 03:09:50 +0000198 self.data_files = None
Tarek Ziadé13f7c3b2009-01-09 00:15:45 +0000199 self.password = ''
Greg Wardfe6462c2000-04-04 01:40:52 +0000200
201 # And now initialize bookkeeping stuff that can't be supplied by
202 # the caller at all. 'command_obj' maps command names to
203 # Command instances -- that's how we enforce that every command
204 # class is a singleton.
205 self.command_obj = {}
206
207 # 'have_run' maps command names to boolean values; it keeps track
208 # of whether we have actually run a particular command, to make it
209 # cheap to "run" a command whenever we think we might need to -- if
210 # it's already been done, no need for expensive filesystem
211 # operations, we just check the 'have_run' dictionary and carry on.
212 # It's only safe to query 'have_run' for a command class that has
213 # been instantiated -- a false value will be inserted when the
214 # command object is created, and replaced with a true value when
Greg Ward612eb9f2000-07-27 02:13:20 +0000215 # the command is successfully run. Thus it's probably best to use
Greg Wardfe6462c2000-04-04 01:40:52 +0000216 # '.get()' rather than a straight lookup.
217 self.have_run = {}
218
219 # Now we'll use the attrs dictionary (ultimately, keyword args from
Greg Ward82715e12000-04-21 02:28:14 +0000220 # the setup script) to possibly override any or all of these
221 # distribution options.
222
Greg Wardfe6462c2000-04-04 01:40:52 +0000223 if attrs:
Greg Wardfe6462c2000-04-04 01:40:52 +0000224 # Pull out the set of command options and work on them
225 # specifically. Note that this order guarantees that aliased
226 # command options will override any supplied redundantly
227 # through the general options dictionary.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000228 options = attrs.get('options')
Tarek Ziadé4450dcf2008-12-29 22:38:38 +0000229 if options is not None:
Greg Wardfe6462c2000-04-04 01:40:52 +0000230 del attrs['options']
231 for (command, cmd_options) in options.items():
Greg Ward0e48cfd2000-05-26 01:00:15 +0000232 opt_dict = self.get_option_dict(command)
233 for (opt, val) in cmd_options.items():
234 opt_dict[opt] = ("setup script", val)
Greg Wardfe6462c2000-04-04 01:40:52 +0000235
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000236 if 'licence' in attrs:
Andrew M. Kuchlinga52b8522003-03-03 20:07:27 +0000237 attrs['license'] = attrs['licence']
238 del attrs['licence']
239 msg = "'licence' distribution option is deprecated; use 'license'"
240 if warnings is not None:
241 warnings.warn(msg)
242 else:
243 sys.stderr.write(msg + "\n")
244
Greg Wardfe6462c2000-04-04 01:40:52 +0000245 # Now work on the rest of the attributes. Any attribute that's
246 # not already defined is invalid!
Tarek Ziadéf11be752009-06-01 22:36:26 +0000247 for (key, val) in attrs.items():
Fred Drakedb7b0022005-03-20 22:19:47 +0000248 if hasattr(self.metadata, "set_" + key):
249 getattr(self.metadata, "set_" + key)(val)
250 elif hasattr(self.metadata, key):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000251 setattr(self.metadata, key, val)
252 elif hasattr(self, key):
253 setattr(self, key, val)
Anthony Baxter73cc8472004-10-13 13:22:34 +0000254 else:
Andrew M. Kuchlingff4ad9a2002-10-31 13:22:41 +0000255 msg = "Unknown distribution option: %s" % repr(key)
256 if warnings is not None:
257 warnings.warn(msg)
258 else:
259 sys.stderr.write(msg + "\n")
Greg Wardfe6462c2000-04-04 01:40:52 +0000260
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000261 self.finalize_options()
Fred Drakeb94b8492001-12-06 20:51:35 +0000262
Tarek Ziadé188789d2009-05-16 18:37:32 +0000263 def get_option_dict(self, command):
Greg Ward0e48cfd2000-05-26 01:00:15 +0000264 """Get the option dictionary for a given command. If that
265 command's option dictionary hasn't been created yet, then create it
266 and return the new dictionary; otherwise, return the existing
267 option dictionary.
268 """
Greg Ward0e48cfd2000-05-26 01:00:15 +0000269 dict = self.command_options.get(command)
270 if dict is None:
271 dict = self.command_options[command] = {}
272 return dict
273
Tarek Ziadé188789d2009-05-16 18:37:32 +0000274 def dump_option_dicts(self, header=None, commands=None, indent=""):
Greg Wardc32d9a62000-05-28 23:53:06 +0000275 from pprint import pformat
276
277 if commands is None: # dump all command option dicts
Guido van Rossumd4ee1672007-10-15 01:27:53 +0000278 commands = sorted(self.command_options.keys())
Greg Wardc32d9a62000-05-28 23:53:06 +0000279
280 if header is not None:
Tarek Ziadéf11be752009-06-01 22:36:26 +0000281 self.announce(indent + header)
Greg Wardc32d9a62000-05-28 23:53:06 +0000282 indent = indent + " "
283
284 if not commands:
Tarek Ziadéf11be752009-06-01 22:36:26 +0000285 self.announce(indent + "no commands known yet")
Greg Wardc32d9a62000-05-28 23:53:06 +0000286 return
287
288 for cmd_name in commands:
289 opt_dict = self.command_options.get(cmd_name)
290 if opt_dict is None:
Tarek Ziadéf11be752009-06-01 22:36:26 +0000291 self.announce(indent +
292 "no option dict for '%s' command" % cmd_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000293 else:
Tarek Ziadéf11be752009-06-01 22:36:26 +0000294 self.announce(indent +
295 "option dict for '%s' command:" % cmd_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000296 out = pformat(opt_dict)
Tarek Ziadéf11be752009-06-01 22:36:26 +0000297 for line in out.split('\n'):
298 self.announce(indent + " " + line)
Greg Wardc32d9a62000-05-28 23:53:06 +0000299
Greg Wardd5d8a992000-05-23 01:42:17 +0000300 # -- Config file finding/parsing methods ---------------------------
301
Tarek Ziadé188789d2009-05-16 18:37:32 +0000302 def find_config_files(self):
Gregory P. Smith14263542000-05-12 00:41:33 +0000303 """Find as many configuration files as should be processed for this
304 platform, and return a list of filenames in the order in which they
305 should be parsed. The filenames returned are guaranteed to exist
306 (modulo nasty race conditions).
307
Andrew M. Kuchlingd303b612001-12-06 16:32:05 +0000308 There are three possible config files: distutils.cfg in the
309 Distutils installation directory (ie. where the top-level
310 Distutils __inst__.py file lives), a file in the user's home
311 directory named .pydistutils.cfg on Unix and pydistutils.cfg
Tarek Ziadé36797272010-07-22 12:50:05 +0000312 on Windows/Mac, and setup.cfg in the current directory.
Greg Wardd5d8a992000-05-23 01:42:17 +0000313 """
Gregory P. Smith14263542000-05-12 00:41:33 +0000314 files = []
Greg Wardacf3f6a2000-06-07 02:26:19 +0000315 check_environ()
Gregory P. Smith14263542000-05-12 00:41:33 +0000316
Greg Ward11696872000-06-07 02:29:03 +0000317 # Where to look for the system-wide Distutils config file
318 sys_dir = os.path.dirname(sys.modules['distutils'].__file__)
319
320 # Look for the system config file
321 sys_file = os.path.join(sys_dir, "distutils.cfg")
Greg Wardacf3f6a2000-06-07 02:26:19 +0000322 if os.path.isfile(sys_file):
323 files.append(sys_file)
Gregory P. Smith14263542000-05-12 00:41:33 +0000324
Greg Ward11696872000-06-07 02:29:03 +0000325 # What to call the per-user config file
326 if os.name == 'posix':
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000327 user_filename = ".pydistutils.cfg"
328 else:
329 user_filename = "pydistutils.cfg"
Greg Wardfa9ff762000-10-14 04:06:40 +0000330
Greg Ward11696872000-06-07 02:29:03 +0000331 # And look for the user config file
Tarek Ziadé36797272010-07-22 12:50:05 +0000332 user_file = os.path.join(os.path.expanduser('~'), user_filename)
333 if os.path.isfile(user_file):
334 files.append(user_file)
Gregory P. Smith14263542000-05-12 00:41:33 +0000335
Gregory P. Smith14263542000-05-12 00:41:33 +0000336 # All platforms support local setup.cfg
337 local_file = "setup.cfg"
338 if os.path.isfile(local_file):
339 files.append(local_file)
340
341 return files
342
Tarek Ziadé188789d2009-05-16 18:37:32 +0000343 def parse_config_files(self, filenames=None):
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000344 from configparser import ConfigParser
Gregory P. Smith14263542000-05-12 00:41:33 +0000345
Georg Brandl521ed522013-05-12 12:36:07 +0200346 # Ignore install directory options if we have a venv
347 if sys.prefix != sys.base_prefix:
348 ignore_options = [
349 'install-base', 'install-platbase', 'install-lib',
350 'install-platlib', 'install-purelib', 'install-headers',
351 'install-scripts', 'install-data', 'prefix', 'exec-prefix',
352 'home', 'user', 'root']
353 else:
354 ignore_options = []
355
356 ignore_options = frozenset(ignore_options)
357
Gregory P. Smith14263542000-05-12 00:41:33 +0000358 if filenames is None:
359 filenames = self.find_config_files()
360
Tarek Ziadéf11be752009-06-01 22:36:26 +0000361 if DEBUG:
362 self.announce("Distribution.parse_config_files():")
Greg Ward47460772000-05-23 03:47:35 +0000363
Gregory P. Smith14263542000-05-12 00:41:33 +0000364 parser = ConfigParser()
Greg Wardd5d8a992000-05-23 01:42:17 +0000365 for filename in filenames:
Tarek Ziadéf11be752009-06-01 22:36:26 +0000366 if DEBUG:
Tarek Ziadé31d46072009-09-21 13:55:19 +0000367 self.announce(" reading %s" % filename)
Greg Wardd5d8a992000-05-23 01:42:17 +0000368 parser.read(filename)
369 for section in parser.sections():
370 options = parser.options(section)
Greg Ward0e48cfd2000-05-26 01:00:15 +0000371 opt_dict = self.get_option_dict(section)
Gregory P. Smith14263542000-05-12 00:41:33 +0000372
Greg Wardd5d8a992000-05-23 01:42:17 +0000373 for opt in options:
Georg Brandl521ed522013-05-12 12:36:07 +0200374 if opt != '__name__' and opt not in ignore_options:
Greg Wardceb9e222000-09-25 01:23:52 +0000375 val = parser.get(section,opt)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000376 opt = opt.replace('-', '_')
Greg Wardceb9e222000-09-25 01:23:52 +0000377 opt_dict[opt] = (filename, val)
Gregory P. Smith14263542000-05-12 00:41:33 +0000378
Greg Ward47460772000-05-23 03:47:35 +0000379 # Make the ConfigParser forget everything (so we retain
Fred Drakef06116d2004-02-17 22:35:19 +0000380 # the original filenames that options come from)
Greg Ward47460772000-05-23 03:47:35 +0000381 parser.__init__()
Gregory P. Smith14263542000-05-12 00:41:33 +0000382
Greg Wardceb9e222000-09-25 01:23:52 +0000383 # If there was a "global" section in the config file, use it
384 # to set Distribution options.
385
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000386 if 'global' in self.command_options:
Greg Wardceb9e222000-09-25 01:23:52 +0000387 for (opt, (src, val)) in self.command_options['global'].items():
388 alias = self.negative_opt.get(opt)
389 try:
390 if alias:
391 setattr(self, alias, not strtobool(val))
392 elif opt in ('verbose', 'dry_run'): # ugh!
393 setattr(self, opt, strtobool(val))
Fred Draked04573f2004-08-03 16:37:40 +0000394 else:
395 setattr(self, opt, val)
Guido van Rossumb940e112007-01-10 16:19:56 +0000396 except ValueError as msg:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000397 raise DistutilsOptionError(msg)
Greg Wardceb9e222000-09-25 01:23:52 +0000398
Greg Wardd5d8a992000-05-23 01:42:17 +0000399 # -- Command-line parsing methods ----------------------------------
400
Tarek Ziadé188789d2009-05-16 18:37:32 +0000401 def parse_command_line(self):
Greg Ward9821bf42000-08-29 01:15:18 +0000402 """Parse the setup script's command line, taken from the
403 'script_args' instance attribute (which defaults to 'sys.argv[1:]'
404 -- see 'setup()' in core.py). This list is first processed for
405 "global options" -- options that set attributes of the Distribution
406 instance. Then, it is alternately scanned for Distutils commands
407 and options for that command. Each new command terminates the
408 options for the previous command. The allowed options for a
409 command are determined by the 'user_options' attribute of the
410 command class -- thus, we have to be able to load command classes
411 in order to parse the command line. Any error in that 'options'
412 attribute raises DistutilsGetoptError; any error on the
413 command-line raises DistutilsArgError. If no Distutils commands
414 were found on the command line, raises DistutilsArgError. Return
Greg Wardceb9e222000-09-25 01:23:52 +0000415 true if command-line was successfully parsed and we should carry
Greg Ward9821bf42000-08-29 01:15:18 +0000416 on with executing commands; false if no errors but we shouldn't
417 execute commands (currently, this only happens if user asks for
418 help).
Greg Wardd5d8a992000-05-23 01:42:17 +0000419 """
Andrew M. Kuchling3f819ec2001-01-15 16:09:35 +0000420 #
Fred Drake981a1782001-08-10 18:59:30 +0000421 # We now have enough information to show the Macintosh dialog
422 # that allows the user to interactively specify the "command line".
Andrew M. Kuchling3f819ec2001-01-15 16:09:35 +0000423 #
Fred Draked04573f2004-08-03 16:37:40 +0000424 toplevel_options = self._get_toplevel_options()
Fred Drakeb94b8492001-12-06 20:51:35 +0000425
Greg Wardfe6462c2000-04-04 01:40:52 +0000426 # We have to parse the command line a bit at a time -- global
427 # options, then the first command, then its options, and so on --
428 # because each command will be handled by a different class, and
Greg Wardd5d8a992000-05-23 01:42:17 +0000429 # the options that are valid for a particular class aren't known
430 # until we have loaded the command class, which doesn't happen
431 # until we know what the command is.
Greg Wardfe6462c2000-04-04 01:40:52 +0000432
433 self.commands = []
Fred Draked04573f2004-08-03 16:37:40 +0000434 parser = FancyGetopt(toplevel_options + self.display_options)
Greg Wardfd7b91e2000-09-26 01:52:25 +0000435 parser.set_negative_aliases(self.negative_opt)
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +0000436 parser.set_aliases({'licence': 'license'})
Greg Wardfd7b91e2000-09-26 01:52:25 +0000437 args = parser.getopt(args=self.script_args, object=self)
Greg Ward82715e12000-04-21 02:28:14 +0000438 option_order = parser.get_option_order()
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000439 log.set_verbosity(self.verbose)
Greg Wardfe6462c2000-04-04 01:40:52 +0000440
Greg Ward82715e12000-04-21 02:28:14 +0000441 # for display options we return immediately
442 if self.handle_display_options(option_order):
Greg Wardfe6462c2000-04-04 01:40:52 +0000443 return
Greg Wardfe6462c2000-04-04 01:40:52 +0000444 while args:
Greg Wardd5d8a992000-05-23 01:42:17 +0000445 args = self._parse_command_opts(parser, args)
446 if args is None: # user asked for help (and got it)
Greg Wardfe6462c2000-04-04 01:40:52 +0000447 return
Greg Wardfe6462c2000-04-04 01:40:52 +0000448
Greg Wardd5d8a992000-05-23 01:42:17 +0000449 # Handle the cases of --help as a "global" option, ie.
450 # "setup.py --help" and "setup.py --help command ...". For the
451 # former, we show global options (--verbose, --dry-run, etc.)
452 # and display-only options (--name, --version, etc.); for the
453 # latter, we omit the display-only options and show help for
454 # each command listed on the command line.
Greg Wardfe6462c2000-04-04 01:40:52 +0000455 if self.help:
Greg Wardd5d8a992000-05-23 01:42:17 +0000456 self._show_help(parser,
457 display_options=len(self.commands) == 0,
458 commands=self.commands)
Greg Wardfe6462c2000-04-04 01:40:52 +0000459 return
460
461 # Oops, no commands found -- an end-user error
462 if not self.commands:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000463 raise DistutilsArgError("no commands supplied")
Greg Wardfe6462c2000-04-04 01:40:52 +0000464
465 # All is well: return true
Collin Winter5b7e9d72007-08-30 03:52:21 +0000466 return True
Greg Wardfe6462c2000-04-04 01:40:52 +0000467
Tarek Ziadé188789d2009-05-16 18:37:32 +0000468 def _get_toplevel_options(self):
Fred Draked04573f2004-08-03 16:37:40 +0000469 """Return the non-display options recognized at the top level.
470
471 This includes options that are recognized *only* at the top
472 level as well as options recognized for commands.
473 """
474 return self.global_options + [
475 ("command-packages=", None,
476 "list of packages that provide distutils commands"),
477 ]
478
Tarek Ziadé188789d2009-05-16 18:37:32 +0000479 def _parse_command_opts(self, parser, args):
Greg Wardd5d8a992000-05-23 01:42:17 +0000480 """Parse the command-line options for a single command.
481 'parser' must be a FancyGetopt instance; 'args' must be the list
482 of arguments, starting with the current command (whose options
483 we are about to parse). Returns a new version of 'args' with
484 the next command at the front of the list; will be the empty
485 list if there are no more commands on the command line. Returns
486 None if the user asked for help on this command.
487 """
488 # late import because of mutual dependence between these modules
489 from distutils.cmd import Command
490
491 # Pull the current command from the head of the command line
492 command = args[0]
Greg Wardfd7b91e2000-09-26 01:52:25 +0000493 if not command_re.match(command):
Collin Winter5b7e9d72007-08-30 03:52:21 +0000494 raise SystemExit("invalid command name '%s'" % command)
Greg Wardfd7b91e2000-09-26 01:52:25 +0000495 self.commands.append(command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000496
497 # Dig up the command class that implements this command, so we
498 # 1) know that it's a valid command, and 2) know which options
499 # it takes.
500 try:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000501 cmd_class = self.get_command_class(command)
Guido van Rossumb940e112007-01-10 16:19:56 +0000502 except DistutilsModuleError as msg:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000503 raise DistutilsArgError(msg)
Greg Wardd5d8a992000-05-23 01:42:17 +0000504
505 # Require that the command class be derived from Command -- want
506 # to be sure that the basic "command" interface is implemented.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000507 if not issubclass(cmd_class, Command):
Collin Winter5b7e9d72007-08-30 03:52:21 +0000508 raise DistutilsClassError(
509 "command class %s must subclass Command" % cmd_class)
Greg Wardd5d8a992000-05-23 01:42:17 +0000510
511 # Also make sure that the command object provides a list of its
512 # known options.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000513 if not (hasattr(cmd_class, 'user_options') and
Guido van Rossum13257902007-06-07 23:15:56 +0000514 isinstance(cmd_class.user_options, list)):
Collin Winter5b7e9d72007-08-30 03:52:21 +0000515 raise DistutilsClassError(("command class %s must provide " +
Greg Wardd5d8a992000-05-23 01:42:17 +0000516 "'user_options' attribute (a list of tuples)") % \
Collin Winter5b7e9d72007-08-30 03:52:21 +0000517 cmd_class)
Greg Wardd5d8a992000-05-23 01:42:17 +0000518
519 # If the command class has a list of negative alias options,
520 # merge it in with the global negative aliases.
521 negative_opt = self.negative_opt
Greg Wardfd7b91e2000-09-26 01:52:25 +0000522 if hasattr(cmd_class, 'negative_opt'):
Antoine Pitrou56a00de2009-05-15 17:34:21 +0000523 negative_opt = negative_opt.copy()
Greg Wardfd7b91e2000-09-26 01:52:25 +0000524 negative_opt.update(cmd_class.negative_opt)
Greg Wardd5d8a992000-05-23 01:42:17 +0000525
Greg Wardfa9ff762000-10-14 04:06:40 +0000526 # Check for help_options in command class. They have a different
527 # format (tuple of four) so we need to preprocess them here.
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000528 if (hasattr(cmd_class, 'help_options') and
Guido van Rossum13257902007-06-07 23:15:56 +0000529 isinstance(cmd_class.help_options, list)):
Greg Ward2ff78872000-06-24 00:23:20 +0000530 help_options = fix_help_options(cmd_class.help_options)
531 else:
Greg Ward55fced32000-06-24 01:22:41 +0000532 help_options = []
Greg Ward2ff78872000-06-24 00:23:20 +0000533
Greg Ward9d17a7a2000-06-07 03:00:06 +0000534
Greg Wardd5d8a992000-05-23 01:42:17 +0000535 # All commands support the global options too, just by adding
536 # in 'global_options'.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000537 parser.set_option_table(self.global_options +
538 cmd_class.user_options +
539 help_options)
540 parser.set_negative_aliases(negative_opt)
541 (args, opts) = parser.getopt(args[1:])
Greg Ward47460772000-05-23 03:47:35 +0000542 if hasattr(opts, 'help') and opts.help:
Greg Wardd5d8a992000-05-23 01:42:17 +0000543 self._show_help(parser, display_options=0, commands=[cmd_class])
544 return
545
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000546 if (hasattr(cmd_class, 'help_options') and
Guido van Rossum13257902007-06-07 23:15:56 +0000547 isinstance(cmd_class.help_options, list)):
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000548 help_option_found=0
549 for (help_option, short, desc, func) in cmd_class.help_options:
550 if hasattr(opts, parser.get_attr_name(help_option)):
551 help_option_found=1
Florent Xicluna5d1155c2011-10-28 14:45:05 +0200552 if callable(func):
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000553 func()
Greg Ward55fced32000-06-24 01:22:41 +0000554 else:
Fred Drake981a1782001-08-10 18:59:30 +0000555 raise DistutilsClassError(
Walter Dörwald70a6b492004-02-12 17:35:32 +0000556 "invalid help function %r for help option '%s': "
Fred Drake981a1782001-08-10 18:59:30 +0000557 "must be a callable object (function, etc.)"
Walter Dörwald70a6b492004-02-12 17:35:32 +0000558 % (func, help_option))
Greg Ward55fced32000-06-24 01:22:41 +0000559
Fred Drakeb94b8492001-12-06 20:51:35 +0000560 if help_option_found:
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000561 return
Greg Ward9d17a7a2000-06-07 03:00:06 +0000562
Greg Wardd5d8a992000-05-23 01:42:17 +0000563 # Put the options from the command-line into their official
564 # holding pen, the 'command_options' dictionary.
Greg Ward0e48cfd2000-05-26 01:00:15 +0000565 opt_dict = self.get_option_dict(command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000566 for (name, value) in vars(opts).items():
Greg Ward0e48cfd2000-05-26 01:00:15 +0000567 opt_dict[name] = ("command line", value)
Greg Wardd5d8a992000-05-23 01:42:17 +0000568
569 return args
570
Tarek Ziadé188789d2009-05-16 18:37:32 +0000571 def finalize_options(self):
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000572 """Set final values for all the options on the Distribution
573 instance, analogous to the .finalize_options() method of Command
574 objects.
575 """
Tarek Ziadéf11be752009-06-01 22:36:26 +0000576 for attr in ('keywords', 'platforms'):
577 value = getattr(self.metadata, attr)
578 if value is None:
579 continue
580 if isinstance(value, str):
581 value = [elm.strip() for elm in value.split(',')]
582 setattr(self.metadata, attr, value)
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000583
Tarek Ziadé188789d2009-05-16 18:37:32 +0000584 def _show_help(self, parser, global_options=1, display_options=1,
585 commands=[]):
Greg Wardd5d8a992000-05-23 01:42:17 +0000586 """Show help for the setup script command-line in the form of
587 several lists of command-line options. 'parser' should be a
588 FancyGetopt instance; do not expect it to be returned in the
589 same state, as its option table will be reset to make it
590 generate the correct help text.
591
592 If 'global_options' is true, lists the global options:
593 --verbose, --dry-run, etc. If 'display_options' is true, lists
594 the "display-only" options: --name, --version, etc. Finally,
595 lists per-command help for every command name or command class
596 in 'commands'.
597 """
598 # late import because of mutual dependence between these modules
Greg Ward9821bf42000-08-29 01:15:18 +0000599 from distutils.core import gen_usage
Greg Wardd5d8a992000-05-23 01:42:17 +0000600 from distutils.cmd import Command
601
602 if global_options:
Fred Draked04573f2004-08-03 16:37:40 +0000603 if display_options:
604 options = self._get_toplevel_options()
605 else:
606 options = self.global_options
607 parser.set_option_table(options)
Martin v. Löwis8ed338a2005-03-03 08:12:27 +0000608 parser.print_help(self.common_usage + "\nGlobal options:")
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000609 print('')
Greg Wardd5d8a992000-05-23 01:42:17 +0000610
611 if display_options:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000612 parser.set_option_table(self.display_options)
613 parser.print_help(
Greg Wardd5d8a992000-05-23 01:42:17 +0000614 "Information display options (just display " +
615 "information, ignore any commands)")
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000616 print('')
Greg Wardd5d8a992000-05-23 01:42:17 +0000617
618 for command in self.commands:
Guido van Rossum13257902007-06-07 23:15:56 +0000619 if isinstance(command, type) and issubclass(command, Command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000620 klass = command
621 else:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000622 klass = self.get_command_class(command)
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000623 if (hasattr(klass, 'help_options') and
Guido van Rossum13257902007-06-07 23:15:56 +0000624 isinstance(klass.help_options, list)):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000625 parser.set_option_table(klass.user_options +
626 fix_help_options(klass.help_options))
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000627 else:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000628 parser.set_option_table(klass.user_options)
629 parser.print_help("Options for '%s' command:" % klass.__name__)
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000630 print('')
Greg Wardd5d8a992000-05-23 01:42:17 +0000631
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000632 print(gen_usage(self.script_name))
Greg Wardd5d8a992000-05-23 01:42:17 +0000633
Tarek Ziadé188789d2009-05-16 18:37:32 +0000634 def handle_display_options(self, option_order):
Greg Ward82715e12000-04-21 02:28:14 +0000635 """If there were any non-global "display-only" options
Greg Wardd5d8a992000-05-23 01:42:17 +0000636 (--help-commands or the metadata display options) on the command
637 line, display the requested info and return true; else return
638 false.
639 """
Greg Ward9821bf42000-08-29 01:15:18 +0000640 from distutils.core import gen_usage
Greg Ward82715e12000-04-21 02:28:14 +0000641
642 # User just wants a list of commands -- we'll print it out and stop
643 # processing now (ie. if they ran "setup --help-commands foo bar",
644 # we ignore "foo bar").
645 if self.help_commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000646 self.print_commands()
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000647 print('')
648 print(gen_usage(self.script_name))
Greg Ward82715e12000-04-21 02:28:14 +0000649 return 1
650
651 # If user supplied any of the "display metadata" options, then
652 # display that metadata in the order in which the user supplied the
653 # metadata options.
654 any_display_options = 0
655 is_display_option = {}
656 for option in self.display_options:
657 is_display_option[option[0]] = 1
658
659 for (opt, val) in option_order:
660 if val and is_display_option.get(opt):
Greg Ward2f2b6c62000-09-25 01:58:07 +0000661 opt = translate_longopt(opt)
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000662 value = getattr(self.metadata, "get_"+opt)()
663 if opt in ['keywords', 'platforms']:
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000664 print(','.join(value))
Fred Drakedb7b0022005-03-20 22:19:47 +0000665 elif opt in ('classifiers', 'provides', 'requires',
666 'obsoletes'):
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000667 print('\n'.join(value))
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000668 else:
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000669 print(value)
Greg Ward82715e12000-04-21 02:28:14 +0000670 any_display_options = 1
671
672 return any_display_options
673
Tarek Ziadé188789d2009-05-16 18:37:32 +0000674 def print_command_list(self, commands, header, max_length):
Greg Wardfe6462c2000-04-04 01:40:52 +0000675 """Print a subset of the list of all commands -- used by
Greg Wardd5d8a992000-05-23 01:42:17 +0000676 'print_commands()'.
677 """
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000678 print(header + ":")
Greg Wardfe6462c2000-04-04 01:40:52 +0000679
680 for cmd in commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000681 klass = self.cmdclass.get(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000682 if not klass:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000683 klass = self.get_command_class(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000684 try:
685 description = klass.description
686 except AttributeError:
687 description = "(no description available)"
688
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000689 print(" %-*s %s" % (max_length, cmd, description))
Greg Wardfe6462c2000-04-04 01:40:52 +0000690
Tarek Ziadé188789d2009-05-16 18:37:32 +0000691 def print_commands(self):
Greg Wardd5d8a992000-05-23 01:42:17 +0000692 """Print out a help message listing all available commands with a
693 description of each. The list is divided into "standard commands"
694 (listed in distutils.command.__all__) and "extra commands"
695 (mentioned in self.cmdclass, but not a standard command). The
696 descriptions come from the command class attribute
697 'description'.
698 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000699 import distutils.command
700 std_commands = distutils.command.__all__
701 is_std = {}
702 for cmd in std_commands:
703 is_std[cmd] = 1
704
705 extra_commands = []
706 for cmd in self.cmdclass.keys():
707 if not is_std.get(cmd):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000708 extra_commands.append(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000709
710 max_length = 0
711 for cmd in (std_commands + extra_commands):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000712 if len(cmd) > max_length:
713 max_length = len(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000714
Greg Wardfd7b91e2000-09-26 01:52:25 +0000715 self.print_command_list(std_commands,
716 "Standard commands",
717 max_length)
Greg Wardfe6462c2000-04-04 01:40:52 +0000718 if extra_commands:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000719 print()
Greg Wardfd7b91e2000-09-26 01:52:25 +0000720 self.print_command_list(extra_commands,
721 "Extra commands",
722 max_length)
Greg Wardfe6462c2000-04-04 01:40:52 +0000723
Tarek Ziadé188789d2009-05-16 18:37:32 +0000724 def get_command_list(self):
Greg Wardf6fc8752000-11-11 02:47:11 +0000725 """Get a list of (command, description) tuples.
726 The list is divided into "standard commands" (listed in
727 distutils.command.__all__) and "extra commands" (mentioned in
728 self.cmdclass, but not a standard command). The descriptions come
729 from the command class attribute 'description'.
730 """
731 # Currently this is only used on Mac OS, for the Mac-only GUI
732 # Distutils interface (by Jack Jansen)
Greg Wardf6fc8752000-11-11 02:47:11 +0000733 import distutils.command
734 std_commands = distutils.command.__all__
735 is_std = {}
736 for cmd in std_commands:
737 is_std[cmd] = 1
738
739 extra_commands = []
740 for cmd in self.cmdclass.keys():
741 if not is_std.get(cmd):
742 extra_commands.append(cmd)
743
744 rv = []
745 for cmd in (std_commands + extra_commands):
746 klass = self.cmdclass.get(cmd)
747 if not klass:
748 klass = self.get_command_class(cmd)
749 try:
750 description = klass.description
751 except AttributeError:
752 description = "(no description available)"
753 rv.append((cmd, description))
754 return rv
Greg Wardfe6462c2000-04-04 01:40:52 +0000755
756 # -- Command class/object methods ----------------------------------
757
Tarek Ziadé188789d2009-05-16 18:37:32 +0000758 def get_command_packages(self):
Fred Draked04573f2004-08-03 16:37:40 +0000759 """Return a list of packages from which commands are loaded."""
760 pkgs = self.command_packages
Tarek Ziadéf11be752009-06-01 22:36:26 +0000761 if not isinstance(pkgs, list):
762 if pkgs is None:
763 pkgs = ''
764 pkgs = [pkg.strip() for pkg in pkgs.split(',') if pkg != '']
Fred Draked04573f2004-08-03 16:37:40 +0000765 if "distutils.command" not in pkgs:
766 pkgs.insert(0, "distutils.command")
767 self.command_packages = pkgs
768 return pkgs
769
Tarek Ziadé188789d2009-05-16 18:37:32 +0000770 def get_command_class(self, command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000771 """Return the class that implements the Distutils command named by
772 'command'. First we check the 'cmdclass' dictionary; if the
773 command is mentioned there, we fetch the class object from the
774 dictionary and return it. Otherwise we load the command module
775 ("distutils.command." + command) and fetch the command class from
776 the module. The loaded class is also stored in 'cmdclass'
777 to speed future calls to 'get_command_class()'.
Greg Wardfe6462c2000-04-04 01:40:52 +0000778
Gregory P. Smith14263542000-05-12 00:41:33 +0000779 Raises DistutilsModuleError if the expected module could not be
Greg Wardd5d8a992000-05-23 01:42:17 +0000780 found, or if that module does not define the expected class.
781 """
782 klass = self.cmdclass.get(command)
783 if klass:
784 return klass
Greg Wardfe6462c2000-04-04 01:40:52 +0000785
Fred Draked04573f2004-08-03 16:37:40 +0000786 for pkgname in self.get_command_packages():
787 module_name = "%s.%s" % (pkgname, command)
788 klass_name = command
Greg Wardfe6462c2000-04-04 01:40:52 +0000789
Fred Draked04573f2004-08-03 16:37:40 +0000790 try:
791 __import__ (module_name)
792 module = sys.modules[module_name]
793 except ImportError:
794 continue
Greg Wardfe6462c2000-04-04 01:40:52 +0000795
Fred Draked04573f2004-08-03 16:37:40 +0000796 try:
797 klass = getattr(module, klass_name)
798 except AttributeError:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000799 raise DistutilsModuleError(
800 "invalid command '%s' (no class '%s' in module '%s')"
801 % (command, klass_name, module_name))
Greg Wardfe6462c2000-04-04 01:40:52 +0000802
Fred Draked04573f2004-08-03 16:37:40 +0000803 self.cmdclass[command] = klass
804 return klass
805
806 raise DistutilsModuleError("invalid command '%s'" % command)
807
Tarek Ziadé188789d2009-05-16 18:37:32 +0000808 def get_command_obj(self, command, create=1):
Greg Wardd5d8a992000-05-23 01:42:17 +0000809 """Return the command object for 'command'. Normally this object
Greg Ward612eb9f2000-07-27 02:13:20 +0000810 is cached on a previous call to 'get_command_obj()'; if no command
Greg Wardd5d8a992000-05-23 01:42:17 +0000811 object for 'command' is in the cache, then we either create and
812 return it (if 'create' is true) or return None.
813 """
814 cmd_obj = self.command_obj.get(command)
Greg Wardfe6462c2000-04-04 01:40:52 +0000815 if not cmd_obj and create:
Greg Ward2bd3f422000-06-02 01:59:33 +0000816 if DEBUG:
Tarek Ziadéf11be752009-06-01 22:36:26 +0000817 self.announce("Distribution.get_command_obj(): " \
818 "creating '%s' command object" % command)
Greg Ward47460772000-05-23 03:47:35 +0000819
Greg Wardd5d8a992000-05-23 01:42:17 +0000820 klass = self.get_command_class(command)
Greg Ward47460772000-05-23 03:47:35 +0000821 cmd_obj = self.command_obj[command] = klass(self)
822 self.have_run[command] = 0
823
824 # Set any options that were supplied in config files
825 # or on the command line. (NB. support for error
826 # reporting is lame here: any errors aren't reported
827 # until 'finalize_options()' is called, which means
828 # we won't report the source of the error.)
829 options = self.command_options.get(command)
830 if options:
Greg Wardc32d9a62000-05-28 23:53:06 +0000831 self._set_command_options(cmd_obj, options)
Greg Wardfe6462c2000-04-04 01:40:52 +0000832
833 return cmd_obj
834
Tarek Ziadé188789d2009-05-16 18:37:32 +0000835 def _set_command_options(self, command_obj, option_dict=None):
Greg Wardc32d9a62000-05-28 23:53:06 +0000836 """Set the options for 'command_obj' from 'option_dict'. Basically
837 this means copying elements of a dictionary ('option_dict') to
838 attributes of an instance ('command').
839
Greg Wardceb9e222000-09-25 01:23:52 +0000840 'command_obj' must be a Command instance. If 'option_dict' is not
Greg Wardc32d9a62000-05-28 23:53:06 +0000841 supplied, uses the standard option dictionary for this command
842 (from 'self.command_options').
843 """
Greg Wardc32d9a62000-05-28 23:53:06 +0000844 command_name = command_obj.get_command_name()
845 if option_dict is None:
846 option_dict = self.get_option_dict(command_name)
847
Tarek Ziadéf11be752009-06-01 22:36:26 +0000848 if DEBUG:
849 self.announce(" setting options for '%s' command:" % command_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000850 for (option, (source, value)) in option_dict.items():
Tarek Ziadéf11be752009-06-01 22:36:26 +0000851 if DEBUG:
852 self.announce(" %s = %s (from %s)" % (option, value,
853 source))
Greg Wardceb9e222000-09-25 01:23:52 +0000854 try:
Amaury Forgeot d'Arc61cb0872008-07-26 20:09:45 +0000855 bool_opts = [translate_longopt(o)
856 for o in command_obj.boolean_options]
Greg Wardceb9e222000-09-25 01:23:52 +0000857 except AttributeError:
858 bool_opts = []
859 try:
860 neg_opt = command_obj.negative_opt
861 except AttributeError:
862 neg_opt = {}
863
864 try:
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000865 is_string = isinstance(value, str)
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000866 if option in neg_opt and is_string:
Greg Wardceb9e222000-09-25 01:23:52 +0000867 setattr(command_obj, neg_opt[option], not strtobool(value))
Greg Ward2c08cf02000-09-27 00:15:37 +0000868 elif option in bool_opts and is_string:
Greg Wardceb9e222000-09-25 01:23:52 +0000869 setattr(command_obj, option, strtobool(value))
870 elif hasattr(command_obj, option):
871 setattr(command_obj, option, value)
872 else:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000873 raise DistutilsOptionError(
874 "error in %s: command '%s' has no such option '%s'"
875 % (source, command_name, option))
Guido van Rossumb940e112007-01-10 16:19:56 +0000876 except ValueError as msg:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000877 raise DistutilsOptionError(msg)
Greg Wardc32d9a62000-05-28 23:53:06 +0000878
Tarek Ziadé188789d2009-05-16 18:37:32 +0000879 def reinitialize_command(self, command, reinit_subcommands=0):
Greg Wardc32d9a62000-05-28 23:53:06 +0000880 """Reinitializes a command to the state it was in when first
881 returned by 'get_command_obj()': ie., initialized but not yet
Greg Ward7d9c7052000-06-28 01:25:27 +0000882 finalized. This provides the opportunity to sneak option
Greg Wardc32d9a62000-05-28 23:53:06 +0000883 values in programmatically, overriding or supplementing
884 user-supplied values from the config files and command line.
885 You'll have to re-finalize the command object (by calling
886 'finalize_options()' or 'ensure_finalized()') before using it for
Fred Drakeb94b8492001-12-06 20:51:35 +0000887 real.
Greg Wardc32d9a62000-05-28 23:53:06 +0000888
Greg Wardf449ea52000-09-16 15:23:28 +0000889 'command' should be a command name (string) or command object. If
890 'reinit_subcommands' is true, also reinitializes the command's
891 sub-commands, as declared by the 'sub_commands' class attribute (if
892 it has one). See the "install" command for an example. Only
893 reinitializes the sub-commands that actually matter, ie. those
894 whose test predicates return true.
895
Greg Wardc32d9a62000-05-28 23:53:06 +0000896 Returns the reinitialized command object.
897 """
898 from distutils.cmd import Command
899 if not isinstance(command, Command):
900 command_name = command
901 command = self.get_command_obj(command_name)
902 else:
903 command_name = command.get_command_name()
904
905 if not command.finalized:
Greg Ward282c7a02000-06-01 01:09:47 +0000906 return command
Greg Wardc32d9a62000-05-28 23:53:06 +0000907 command.initialize_options()
908 command.finalized = 0
Greg Ward43955c92000-06-06 02:52:36 +0000909 self.have_run[command_name] = 0
Greg Wardc32d9a62000-05-28 23:53:06 +0000910 self._set_command_options(command)
Greg Wardf449ea52000-09-16 15:23:28 +0000911
Greg Wardf449ea52000-09-16 15:23:28 +0000912 if reinit_subcommands:
Greg Wardf449ea52000-09-16 15:23:28 +0000913 for sub in command.get_sub_commands():
Fred Drakeb94b8492001-12-06 20:51:35 +0000914 self.reinitialize_command(sub, reinit_subcommands)
Greg Wardf449ea52000-09-16 15:23:28 +0000915
Greg Wardc32d9a62000-05-28 23:53:06 +0000916 return command
917
Greg Wardfe6462c2000-04-04 01:40:52 +0000918 # -- Methods that operate on the Distribution ----------------------
919
Tarek Ziadé05bf01a2009-07-04 02:04:21 +0000920 def announce(self, msg, level=log.INFO):
921 log.log(level, msg)
Greg Wardfe6462c2000-04-04 01:40:52 +0000922
Tarek Ziadé188789d2009-05-16 18:37:32 +0000923 def run_commands(self):
Greg Ward82715e12000-04-21 02:28:14 +0000924 """Run each command that was seen on the setup script command line.
Greg Wardd5d8a992000-05-23 01:42:17 +0000925 Uses the list of commands found and cache of command objects
Greg Wardfd7b91e2000-09-26 01:52:25 +0000926 created by 'get_command_obj()'.
927 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000928 for cmd in self.commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000929 self.run_command(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000930
Greg Wardfe6462c2000-04-04 01:40:52 +0000931 # -- Methods that operate on its Commands --------------------------
932
Tarek Ziadé188789d2009-05-16 18:37:32 +0000933 def run_command(self, command):
Greg Wardfe6462c2000-04-04 01:40:52 +0000934 """Do whatever it takes to run a command (including nothing at all,
Greg Wardd5d8a992000-05-23 01:42:17 +0000935 if the command has already been run). Specifically: if we have
936 already created and run the command named by 'command', return
937 silently without doing anything. If the command named by 'command'
938 doesn't even have a command object yet, create one. Then invoke
939 'run()' on that command object (or an existing one).
940 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000941 # Already been here, done that? then return silently.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000942 if self.have_run.get(command):
Greg Wardfe6462c2000-04-04 01:40:52 +0000943 return
944
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000945 log.info("running %s", command)
Greg Wardfd7b91e2000-09-26 01:52:25 +0000946 cmd_obj = self.get_command_obj(command)
947 cmd_obj.ensure_finalized()
948 cmd_obj.run()
Greg Wardfe6462c2000-04-04 01:40:52 +0000949 self.have_run[command] = 1
950
951
Greg Wardfe6462c2000-04-04 01:40:52 +0000952 # -- Distribution query methods ------------------------------------
953
Tarek Ziadé188789d2009-05-16 18:37:32 +0000954 def has_pure_modules(self):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000955 return len(self.packages or self.py_modules or []) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000956
Tarek Ziadé188789d2009-05-16 18:37:32 +0000957 def has_ext_modules(self):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000958 return self.ext_modules and len(self.ext_modules) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000959
Tarek Ziadé188789d2009-05-16 18:37:32 +0000960 def has_c_libraries(self):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000961 return self.libraries and len(self.libraries) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000962
Tarek Ziadé188789d2009-05-16 18:37:32 +0000963 def has_modules(self):
Greg Wardfe6462c2000-04-04 01:40:52 +0000964 return self.has_pure_modules() or self.has_ext_modules()
965
Tarek Ziadé188789d2009-05-16 18:37:32 +0000966 def has_headers(self):
Greg Ward51def7d2000-05-27 01:36:14 +0000967 return self.headers and len(self.headers) > 0
968
Tarek Ziadé188789d2009-05-16 18:37:32 +0000969 def has_scripts(self):
Greg Ward44a61bb2000-05-20 15:06:48 +0000970 return self.scripts and len(self.scripts) > 0
971
Tarek Ziadé188789d2009-05-16 18:37:32 +0000972 def has_data_files(self):
Greg Ward44a61bb2000-05-20 15:06:48 +0000973 return self.data_files and len(self.data_files) > 0
974
Tarek Ziadé188789d2009-05-16 18:37:32 +0000975 def is_pure(self):
Greg Wardfe6462c2000-04-04 01:40:52 +0000976 return (self.has_pure_modules() and
977 not self.has_ext_modules() and
978 not self.has_c_libraries())
979
Greg Ward82715e12000-04-21 02:28:14 +0000980 # -- Metadata query methods ----------------------------------------
981
982 # If you're looking for 'get_name()', 'get_version()', and so forth,
983 # they are defined in a sneaky way: the constructor binds self.get_XXX
984 # to self.metadata.get_XXX. The actual code is in the
985 # DistributionMetadata class, below.
986
Greg Ward82715e12000-04-21 02:28:14 +0000987class DistributionMetadata:
988 """Dummy class to hold the distribution meta-data: name, version,
Greg Wardfd7b91e2000-09-26 01:52:25 +0000989 author, and so forth.
990 """
Greg Ward82715e12000-04-21 02:28:14 +0000991
Neil Schemenauera8aefe52001-09-03 15:47:21 +0000992 _METHOD_BASENAMES = ("name", "version", "author", "author_email",
993 "maintainer", "maintainer_email", "url",
994 "license", "description", "long_description",
995 "keywords", "platforms", "fullname", "contact",
Andrew M. Kuchlinga52b8522003-03-03 20:07:27 +0000996 "contact_email", "license", "classifiers",
Fred Drakedb7b0022005-03-20 22:19:47 +0000997 "download_url",
998 # PEP 314
999 "provides", "requires", "obsoletes",
1000 )
Neil Schemenauera8aefe52001-09-03 15:47:21 +00001001
Tarek Ziadé36797272010-07-22 12:50:05 +00001002 def __init__ (self):
1003 self.name = None
1004 self.version = None
1005 self.author = None
1006 self.author_email = None
Greg Ward82715e12000-04-21 02:28:14 +00001007 self.maintainer = None
1008 self.maintainer_email = None
Tarek Ziadé36797272010-07-22 12:50:05 +00001009 self.url = None
1010 self.license = None
1011 self.description = None
1012 self.long_description = None
1013 self.keywords = None
1014 self.platforms = None
1015 self.classifiers = None
1016 self.download_url = None
1017 # PEP 314
1018 self.provides = None
1019 self.requires = None
1020 self.obsoletes = None
Fred Drakeb94b8492001-12-06 20:51:35 +00001021
Tarek Ziadé188789d2009-05-16 18:37:32 +00001022 def write_pkg_info(self, base_dir):
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001023 """Write the PKG-INFO file into the release tree.
1024 """
Victor Stinnera1bea6e2011-09-05 23:44:56 +02001025 with open(os.path.join(base_dir, 'PKG-INFO'), 'w',
1026 encoding='UTF-8') as pkg_info:
Éric Araujobee5cef2010-11-05 23:51:56 +00001027 self.write_pkg_file(pkg_info)
Fred Drakeb94b8492001-12-06 20:51:35 +00001028
Tarek Ziadé188789d2009-05-16 18:37:32 +00001029 def write_pkg_file(self, file):
Fred Drakedb7b0022005-03-20 22:19:47 +00001030 """Write the PKG-INFO format data to a file object.
1031 """
1032 version = '1.0'
Éric Araujo13e8c8e2011-09-10 01:51:40 +02001033 if (self.provides or self.requires or self.obsoletes or
1034 self.classifiers or self.download_url):
Fred Drakedb7b0022005-03-20 22:19:47 +00001035 version = '1.1'
1036
1037 file.write('Metadata-Version: %s\n' % version)
1038 file.write('Name: %s\n' % self.get_name() )
1039 file.write('Version: %s\n' % self.get_version() )
1040 file.write('Summary: %s\n' % self.get_description() )
1041 file.write('Home-page: %s\n' % self.get_url() )
1042 file.write('Author: %s\n' % self.get_contact() )
1043 file.write('Author-email: %s\n' % self.get_contact_email() )
1044 file.write('License: %s\n' % self.get_license() )
1045 if self.download_url:
1046 file.write('Download-URL: %s\n' % self.download_url)
1047
Tarek Ziadéf11be752009-06-01 22:36:26 +00001048 long_desc = rfc822_escape(self.get_long_description())
Fred Drakedb7b0022005-03-20 22:19:47 +00001049 file.write('Description: %s\n' % long_desc)
1050
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001051 keywords = ','.join(self.get_keywords())
Fred Drakedb7b0022005-03-20 22:19:47 +00001052 if keywords:
1053 file.write('Keywords: %s\n' % keywords )
1054
1055 self._write_list(file, 'Platform', self.get_platforms())
1056 self._write_list(file, 'Classifier', self.get_classifiers())
1057
1058 # PEP 314
1059 self._write_list(file, 'Requires', self.get_requires())
1060 self._write_list(file, 'Provides', self.get_provides())
1061 self._write_list(file, 'Obsoletes', self.get_obsoletes())
1062
Tarek Ziadé188789d2009-05-16 18:37:32 +00001063 def _write_list(self, file, name, values):
Fred Drakedb7b0022005-03-20 22:19:47 +00001064 for value in values:
1065 file.write('%s: %s\n' % (name, value))
1066
Greg Ward82715e12000-04-21 02:28:14 +00001067 # -- Metadata query methods ----------------------------------------
1068
Tarek Ziadé188789d2009-05-16 18:37:32 +00001069 def get_name(self):
Greg Wardfe6462c2000-04-04 01:40:52 +00001070 return self.name or "UNKNOWN"
1071
Greg Ward82715e12000-04-21 02:28:14 +00001072 def get_version(self):
Thomas Hellerbcd89752001-12-06 20:44:19 +00001073 return self.version or "0.0.0"
Greg Wardfe6462c2000-04-04 01:40:52 +00001074
Tarek Ziadé188789d2009-05-16 18:37:32 +00001075 def get_fullname(self):
Greg Ward82715e12000-04-21 02:28:14 +00001076 return "%s-%s" % (self.get_name(), self.get_version())
1077
1078 def get_author(self):
1079 return self.author or "UNKNOWN"
1080
1081 def get_author_email(self):
1082 return self.author_email or "UNKNOWN"
1083
1084 def get_maintainer(self):
1085 return self.maintainer or "UNKNOWN"
1086
1087 def get_maintainer_email(self):
1088 return self.maintainer_email or "UNKNOWN"
1089
1090 def get_contact(self):
Tarek Ziadé188789d2009-05-16 18:37:32 +00001091 return self.maintainer or self.author or "UNKNOWN"
Greg Ward82715e12000-04-21 02:28:14 +00001092
1093 def get_contact_email(self):
Tarek Ziadé188789d2009-05-16 18:37:32 +00001094 return self.maintainer_email or self.author_email or "UNKNOWN"
Greg Ward82715e12000-04-21 02:28:14 +00001095
1096 def get_url(self):
1097 return self.url or "UNKNOWN"
1098
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +00001099 def get_license(self):
1100 return self.license or "UNKNOWN"
1101 get_licence = get_license
Fred Drakeb94b8492001-12-06 20:51:35 +00001102
Greg Ward82715e12000-04-21 02:28:14 +00001103 def get_description(self):
1104 return self.description or "UNKNOWN"
Greg Warde5a584e2000-04-26 02:26:55 +00001105
1106 def get_long_description(self):
1107 return self.long_description or "UNKNOWN"
1108
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001109 def get_keywords(self):
1110 return self.keywords or []
1111
1112 def get_platforms(self):
1113 return self.platforms or ["UNKNOWN"]
1114
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +00001115 def get_classifiers(self):
1116 return self.classifiers or []
1117
Andrew M. Kuchling188d85f2003-02-19 14:16:01 +00001118 def get_download_url(self):
1119 return self.download_url or "UNKNOWN"
1120
Fred Drakedb7b0022005-03-20 22:19:47 +00001121 # PEP 314
Fred Drakedb7b0022005-03-20 22:19:47 +00001122 def get_requires(self):
1123 return self.requires or []
1124
1125 def set_requires(self, value):
1126 import distutils.versionpredicate
1127 for v in value:
1128 distutils.versionpredicate.VersionPredicate(v)
1129 self.requires = value
1130
1131 def get_provides(self):
1132 return self.provides or []
1133
1134 def set_provides(self, value):
1135 value = [v.strip() for v in value]
1136 for v in value:
1137 import distutils.versionpredicate
Fred Drake227e8ff2005-03-21 06:36:32 +00001138 distutils.versionpredicate.split_provision(v)
Fred Drakedb7b0022005-03-20 22:19:47 +00001139 self.provides = value
1140
1141 def get_obsoletes(self):
1142 return self.obsoletes or []
1143
1144 def set_obsoletes(self, value):
1145 import distutils.versionpredicate
1146 for v in value:
1147 distutils.versionpredicate.VersionPredicate(v)
1148 self.obsoletes = value
1149
Tarek Ziadé188789d2009-05-16 18:37:32 +00001150def fix_help_options(options):
Greg Ward2ff78872000-06-24 00:23:20 +00001151 """Convert a 4-tuple 'help_options' list as found in various command
1152 classes to the 3-tuple form required by FancyGetopt.
1153 """
1154 new_options = []
1155 for help_tuple in options:
1156 new_options.append(help_tuple[0:3])
1157 return new_options