blob: 90af6e2d3bfd09e6378c4be6504c35e2f8d6c5a9 [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
Greg Wardfe6462c2000-04-04 01:40:52 +00007__revision__ = "$Id$"
8
Neal Norwitz9d72bb42007-04-17 08:48:32 +00009import sys, os, re
Andrew M. Kuchlingff4ad9a2002-10-31 13:22:41 +000010
11try:
12 import warnings
Andrew M. Kuchlingccf4e422002-10-31 13:39:33 +000013except ImportError:
Andrew M. Kuchlingff4ad9a2002-10-31 13:22:41 +000014 warnings = None
15
Greg Wardfe6462c2000-04-04 01:40:52 +000016from distutils.errors import *
Greg Ward2f2b6c62000-09-25 01:58:07 +000017from distutils.fancy_getopt import FancyGetopt, translate_longopt
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +000018from distutils.util import check_environ, strtobool, rfc822_escape
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000019from distutils import log
Jeremy Hyltonfcd73532002-09-11 16:31:53 +000020from distutils.debug import DEBUG
Greg Wardfe6462c2000-04-04 01:40:52 +000021
22# Regex to define acceptable Distutils command names. This is not *quite*
23# the same as a Python NAME -- I don't allow leading underscores. The fact
24# that they're very similar is no coincidence; the default naming scheme is
25# to look for a Python module named after the command.
26command_re = re.compile (r'^[a-zA-Z]([a-zA-Z0-9_]*)$')
27
28
29class Distribution:
Greg Ward8ff5a3f2000-06-02 00:44:53 +000030 """The core of the Distutils. Most of the work hiding behind 'setup'
31 is really done within a Distribution instance, which farms the work out
32 to the Distutils commands specified on the command line.
Greg Wardfe6462c2000-04-04 01:40:52 +000033
Greg Ward8ff5a3f2000-06-02 00:44:53 +000034 Setup scripts will almost never instantiate Distribution directly,
35 unless the 'setup()' function is totally inadequate to their needs.
36 However, it is conceivable that a setup script might wish to subclass
37 Distribution for some specialized purpose, and then pass the subclass
38 to 'setup()' as the 'distclass' keyword argument. If so, it is
39 necessary to respect the expectations that 'setup' has of Distribution.
40 See the code for 'setup()', in core.py, for details.
41 """
Greg Wardfe6462c2000-04-04 01:40:52 +000042
43
44 # 'global_options' describes the command-line options that may be
Greg Ward82715e12000-04-21 02:28:14 +000045 # supplied to the setup script prior to any actual commands.
46 # Eg. "./setup.py -n" or "./setup.py --quiet" both take advantage of
Greg Wardfe6462c2000-04-04 01:40:52 +000047 # these global options. This list should be kept to a bare minimum,
48 # since every global option is also valid as a command option -- and we
49 # don't want to pollute the commands with too many options that they
50 # have minimal control over.
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000051 # The fourth entry for verbose means that it can be repeated.
52 global_options = [('verbose', 'v', "run verbosely (default)", 1),
Greg Wardd5d8a992000-05-23 01:42:17 +000053 ('quiet', 'q', "run quietly (turns verbosity off)"),
54 ('dry-run', 'n', "don't actually do anything"),
55 ('help', 'h', "show detailed help message"),
Tarek Ziadéc7c71ff2009-10-27 23:12:01 +000056 ('no-user-cfg', None,
57 'ignore pydistutils.cfg in your home directory'),
58 ]
Greg Ward82715e12000-04-21 02:28:14 +000059
Martin v. Löwis8ed338a2005-03-03 08:12:27 +000060 # 'common_usage' is a short (2-3 line) string describing the common
61 # usage of the setup script.
62 common_usage = """\
63Common commands: (see '--help-commands' for more)
64
65 setup.py build will build the package underneath 'build/'
66 setup.py install will install the package
67"""
68
Greg Ward82715e12000-04-21 02:28:14 +000069 # options that are not propagated to the commands
70 display_options = [
71 ('help-commands', None,
72 "list all available commands"),
73 ('name', None,
74 "print package name"),
75 ('version', 'V',
76 "print package version"),
77 ('fullname', None,
78 "print <package name>-<version>"),
79 ('author', None,
80 "print the author's name"),
81 ('author-email', None,
82 "print the author's email address"),
83 ('maintainer', None,
84 "print the maintainer's name"),
85 ('maintainer-email', None,
86 "print the maintainer's email address"),
87 ('contact', None,
Greg Wardd5d8a992000-05-23 01:42:17 +000088 "print the maintainer's name if known, else the author's"),
Greg Ward82715e12000-04-21 02:28:14 +000089 ('contact-email', None,
Greg Wardd5d8a992000-05-23 01:42:17 +000090 "print the maintainer's email address if known, else the author's"),
Greg Ward82715e12000-04-21 02:28:14 +000091 ('url', None,
92 "print the URL for this package"),
Greg Ward82715e12000-04-21 02:28:14 +000093 ('license', None,
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +000094 "print the license of the package"),
95 ('licence', None,
96 "alias for --license"),
Greg Ward82715e12000-04-21 02:28:14 +000097 ('description', None,
98 "print the package description"),
Greg Warde5a584e2000-04-26 02:26:55 +000099 ('long-description', None,
100 "print the long package description"),
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000101 ('platforms', None,
102 "print the list of platforms"),
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +0000103 ('classifiers', None,
104 "print the list of classifiers"),
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000105 ('keywords', None,
106 "print the list of keywords"),
Fred Drakedb7b0022005-03-20 22:19:47 +0000107 ('provides', None,
108 "print the list of packages/modules provided"),
109 ('requires', None,
110 "print the list of packages/modules required"),
111 ('obsoletes', None,
112 "print the list of packages/modules made obsolete")
Greg Ward82715e12000-04-21 02:28:14 +0000113 ]
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000114 display_option_names = [translate_longopt(x[0]) for x in display_options]
Greg Ward82715e12000-04-21 02:28:14 +0000115
116 # negative options are options that exclude other options
Greg Wardfe6462c2000-04-04 01:40:52 +0000117 negative_opt = {'quiet': 'verbose'}
118
119
120 # -- Creation/initialization methods -------------------------------
Fred Drakeb94b8492001-12-06 20:51:35 +0000121
Greg Wardfe6462c2000-04-04 01:40:52 +0000122 def __init__ (self, attrs=None):
123 """Construct a new Distribution instance: initialize all the
Greg Ward8ff5a3f2000-06-02 00:44:53 +0000124 attributes of a Distribution, and then use 'attrs' (a dictionary
125 mapping attribute names to values) to assign some of those
126 attributes their "real" values. (Any attributes not mentioned in
127 'attrs' will be assigned to some null value: 0, None, an empty list
128 or dictionary, etc.) Most importantly, initialize the
129 'command_obj' attribute to the empty dictionary; this will be
130 filled in with real command objects by 'parse_command_line()'.
131 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000132
133 # Default values for our command-line options
134 self.verbose = 1
135 self.dry_run = 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000136 self.help = 0
Greg Ward82715e12000-04-21 02:28:14 +0000137 for attr in self.display_option_names:
138 setattr(self, attr, 0)
Greg Wardfe6462c2000-04-04 01:40:52 +0000139
Greg Ward82715e12000-04-21 02:28:14 +0000140 # Store the distribution meta-data (name, version, author, and so
141 # forth) in a separate object -- we're getting to have enough
142 # information here (and enough command-line options) that it's
143 # worth it. Also delegate 'get_XXX()' methods to the 'metadata'
144 # object in a sneaky and underhanded (but efficient!) way.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000145 self.metadata = DistributionMetadata()
Neil Schemenauera8aefe52001-09-03 15:47:21 +0000146 for basename in self.metadata._METHOD_BASENAMES:
Greg Ward4982f982000-04-22 02:52:44 +0000147 method_name = "get_" + basename
148 setattr(self, method_name, getattr(self.metadata, method_name))
Greg Wardfe6462c2000-04-04 01:40:52 +0000149
150 # 'cmdclass' maps command names to class objects, so we
151 # can 1) quickly figure out which class to instantiate when
152 # we need to create a new command object, and 2) have a way
Greg Ward82715e12000-04-21 02:28:14 +0000153 # for the setup script to override command classes
Greg Wardfe6462c2000-04-04 01:40:52 +0000154 self.cmdclass = {}
155
Fred Draked04573f2004-08-03 16:37:40 +0000156 # 'command_packages' is a list of packages in which commands
157 # are searched for. The factory for command 'foo' is expected
158 # to be named 'foo' in the module 'foo' in one of the packages
159 # named here. This list is searched from the left; an error
160 # is raised if no named package provides the command being
161 # searched for. (Always access using get_command_packages().)
162 self.command_packages = None
163
Greg Ward9821bf42000-08-29 01:15:18 +0000164 # 'script_name' and 'script_args' are usually set to sys.argv[0]
165 # and sys.argv[1:], but they can be overridden when the caller is
166 # not necessarily a setup script run from the command-line.
167 self.script_name = None
168 self.script_args = None
169
Greg Wardd5d8a992000-05-23 01:42:17 +0000170 # 'command_options' is where we store command options between
171 # parsing them (from config files, the command-line, etc.) and when
172 # they are actually needed -- ie. when the command in question is
173 # instantiated. It is a dictionary of dictionaries of 2-tuples:
174 # command_options = { command_name : { option : (source, value) } }
Gregory P. Smith14263542000-05-12 00:41:33 +0000175 self.command_options = {}
176
Martin v. Löwis98da5622005-03-23 18:54:36 +0000177 # 'dist_files' is the list of (command, pyversion, file) that
178 # have been created by any dist commands run so far. This is
179 # filled regardless of whether the run is dry or not. pyversion
180 # gives sysconfig.get_python_version() if the dist file is
181 # specific to a Python version, 'any' if it is good for all
182 # Python versions on the target platform, and '' for a source
183 # file. pyversion should not be used to specify minimum or
184 # maximum required Python versions; use the metainfo for that
185 # instead.
Martin v. Löwis55f1bb82005-03-21 20:56:35 +0000186 self.dist_files = []
187
Greg Wardfe6462c2000-04-04 01:40:52 +0000188 # These options are really the business of various commands, rather
189 # than of the Distribution itself. We provide aliases for them in
190 # Distribution as a convenience to the developer.
Greg Wardfe6462c2000-04-04 01:40:52 +0000191 self.packages = None
Fred Drake0eb32a62004-06-11 21:50:33 +0000192 self.package_data = {}
Greg Wardfe6462c2000-04-04 01:40:52 +0000193 self.package_dir = None
194 self.py_modules = None
195 self.libraries = None
Greg Ward51def7d2000-05-27 01:36:14 +0000196 self.headers = None
Greg Wardfe6462c2000-04-04 01:40:52 +0000197 self.ext_modules = None
198 self.ext_package = None
199 self.include_dirs = None
200 self.extra_path = None
Gregory P. Smithb2e3bb32000-05-12 00:52:23 +0000201 self.scripts = None
Gregory P. Smith6a901dd2000-05-13 03:09:50 +0000202 self.data_files = None
Tarek Ziadé13f7c3b2009-01-09 00:15:45 +0000203 self.password = ''
Greg Wardfe6462c2000-04-04 01:40:52 +0000204
205 # And now initialize bookkeeping stuff that can't be supplied by
206 # the caller at all. 'command_obj' maps command names to
207 # Command instances -- that's how we enforce that every command
208 # class is a singleton.
209 self.command_obj = {}
210
211 # 'have_run' maps command names to boolean values; it keeps track
212 # of whether we have actually run a particular command, to make it
213 # cheap to "run" a command whenever we think we might need to -- if
214 # it's already been done, no need for expensive filesystem
215 # operations, we just check the 'have_run' dictionary and carry on.
216 # It's only safe to query 'have_run' for a command class that has
217 # been instantiated -- a false value will be inserted when the
218 # command object is created, and replaced with a true value when
Greg Ward612eb9f2000-07-27 02:13:20 +0000219 # the command is successfully run. Thus it's probably best to use
Greg Wardfe6462c2000-04-04 01:40:52 +0000220 # '.get()' rather than a straight lookup.
221 self.have_run = {}
222
223 # Now we'll use the attrs dictionary (ultimately, keyword args from
Greg Ward82715e12000-04-21 02:28:14 +0000224 # the setup script) to possibly override any or all of these
225 # distribution options.
226
Greg Wardfe6462c2000-04-04 01:40:52 +0000227 if attrs:
Greg Wardfe6462c2000-04-04 01:40:52 +0000228 # Pull out the set of command options and work on them
229 # specifically. Note that this order guarantees that aliased
230 # command options will override any supplied redundantly
231 # through the general options dictionary.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000232 options = attrs.get('options')
Tarek Ziadé4450dcf2008-12-29 22:38:38 +0000233 if options is not None:
Greg Wardfe6462c2000-04-04 01:40:52 +0000234 del attrs['options']
235 for (command, cmd_options) in options.items():
Greg Ward0e48cfd2000-05-26 01:00:15 +0000236 opt_dict = self.get_option_dict(command)
237 for (opt, val) in cmd_options.items():
238 opt_dict[opt] = ("setup script", val)
Greg Wardfe6462c2000-04-04 01:40:52 +0000239
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000240 if 'licence' in attrs:
Andrew M. Kuchlinga52b8522003-03-03 20:07:27 +0000241 attrs['license'] = attrs['licence']
242 del attrs['licence']
243 msg = "'licence' distribution option is deprecated; use 'license'"
244 if warnings is not None:
245 warnings.warn(msg)
246 else:
247 sys.stderr.write(msg + "\n")
248
Greg Wardfe6462c2000-04-04 01:40:52 +0000249 # Now work on the rest of the attributes. Any attribute that's
250 # not already defined is invalid!
Tarek Ziadéf11be752009-06-01 22:36:26 +0000251 for (key, val) in attrs.items():
Fred Drakedb7b0022005-03-20 22:19:47 +0000252 if hasattr(self.metadata, "set_" + key):
253 getattr(self.metadata, "set_" + key)(val)
254 elif hasattr(self.metadata, key):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000255 setattr(self.metadata, key, val)
256 elif hasattr(self, key):
257 setattr(self, key, val)
Anthony Baxter73cc8472004-10-13 13:22:34 +0000258 else:
Andrew M. Kuchlingff4ad9a2002-10-31 13:22:41 +0000259 msg = "Unknown distribution option: %s" % repr(key)
260 if warnings is not None:
261 warnings.warn(msg)
262 else:
263 sys.stderr.write(msg + "\n")
Greg Wardfe6462c2000-04-04 01:40:52 +0000264
Tarek Ziadéc7c71ff2009-10-27 23:12:01 +0000265 # no-user-cfg is handled before other command line args
266 # because other args override the config files, and this
267 # one is needed before we can load the config files.
268 # If attrs['script_args'] wasn't passed, assume false.
269 #
270 # This also make sure we just look at the global options
271 self.want_user_cfg = True
272
273 if self.script_args is not None:
274 for arg in self.script_args:
275 if not arg.startswith('-'):
276 break
277 if arg == '--no-user-cfg':
278 self.want_user_cfg = False
279 break
280
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000281 self.finalize_options()
Fred Drakeb94b8492001-12-06 20:51:35 +0000282
Tarek Ziadé188789d2009-05-16 18:37:32 +0000283 def get_option_dict(self, command):
Greg Ward0e48cfd2000-05-26 01:00:15 +0000284 """Get the option dictionary for a given command. If that
285 command's option dictionary hasn't been created yet, then create it
286 and return the new dictionary; otherwise, return the existing
287 option dictionary.
288 """
Greg Ward0e48cfd2000-05-26 01:00:15 +0000289 dict = self.command_options.get(command)
290 if dict is None:
291 dict = self.command_options[command] = {}
292 return dict
293
Tarek Ziadé188789d2009-05-16 18:37:32 +0000294 def dump_option_dicts(self, header=None, commands=None, indent=""):
Greg Wardc32d9a62000-05-28 23:53:06 +0000295 from pprint import pformat
296
297 if commands is None: # dump all command option dicts
Guido van Rossumd4ee1672007-10-15 01:27:53 +0000298 commands = sorted(self.command_options.keys())
Greg Wardc32d9a62000-05-28 23:53:06 +0000299
300 if header is not None:
Tarek Ziadéf11be752009-06-01 22:36:26 +0000301 self.announce(indent + header)
Greg Wardc32d9a62000-05-28 23:53:06 +0000302 indent = indent + " "
303
304 if not commands:
Tarek Ziadéf11be752009-06-01 22:36:26 +0000305 self.announce(indent + "no commands known yet")
Greg Wardc32d9a62000-05-28 23:53:06 +0000306 return
307
308 for cmd_name in commands:
309 opt_dict = self.command_options.get(cmd_name)
310 if opt_dict is None:
Tarek Ziadéf11be752009-06-01 22:36:26 +0000311 self.announce(indent +
312 "no option dict for '%s' command" % cmd_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000313 else:
Tarek Ziadéf11be752009-06-01 22:36:26 +0000314 self.announce(indent +
315 "option dict for '%s' command:" % cmd_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000316 out = pformat(opt_dict)
Tarek Ziadéf11be752009-06-01 22:36:26 +0000317 for line in out.split('\n'):
318 self.announce(indent + " " + line)
Greg Wardc32d9a62000-05-28 23:53:06 +0000319
Greg Wardd5d8a992000-05-23 01:42:17 +0000320 # -- Config file finding/parsing methods ---------------------------
321
Tarek Ziadé188789d2009-05-16 18:37:32 +0000322 def find_config_files(self):
Gregory P. Smith14263542000-05-12 00:41:33 +0000323 """Find as many configuration files as should be processed for this
324 platform, and return a list of filenames in the order in which they
325 should be parsed. The filenames returned are guaranteed to exist
326 (modulo nasty race conditions).
327
Andrew M. Kuchlingd303b612001-12-06 16:32:05 +0000328 There are three possible config files: distutils.cfg in the
329 Distutils installation directory (ie. where the top-level
330 Distutils __inst__.py file lives), a file in the user's home
331 directory named .pydistutils.cfg on Unix and pydistutils.cfg
Tarek Ziadéc7c71ff2009-10-27 23:12:01 +0000332 on Windows/Mac; and setup.cfg in the current directory.
333
334 The file in the user's home directory can be disabled with the
335 --no-user-cfg option.
Greg Wardd5d8a992000-05-23 01:42:17 +0000336 """
Gregory P. Smith14263542000-05-12 00:41:33 +0000337 files = []
Greg Wardacf3f6a2000-06-07 02:26:19 +0000338 check_environ()
Gregory P. Smith14263542000-05-12 00:41:33 +0000339
Greg Ward11696872000-06-07 02:29:03 +0000340 # Where to look for the system-wide Distutils config file
341 sys_dir = os.path.dirname(sys.modules['distutils'].__file__)
342
343 # Look for the system config file
344 sys_file = os.path.join(sys_dir, "distutils.cfg")
Greg Wardacf3f6a2000-06-07 02:26:19 +0000345 if os.path.isfile(sys_file):
346 files.append(sys_file)
Gregory P. Smith14263542000-05-12 00:41:33 +0000347
Greg Ward11696872000-06-07 02:29:03 +0000348 # What to call the per-user config file
349 if os.name == 'posix':
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000350 user_filename = ".pydistutils.cfg"
351 else:
352 user_filename = "pydistutils.cfg"
Greg Wardfa9ff762000-10-14 04:06:40 +0000353
Greg Ward11696872000-06-07 02:29:03 +0000354 # And look for the user config file
Tarek Ziadéc7c71ff2009-10-27 23:12:01 +0000355 if self.want_user_cfg:
356 user_file = os.path.join(os.path.expanduser('~'), user_filename)
357 if os.path.isfile(user_file):
358 files.append(user_file)
Gregory P. Smith14263542000-05-12 00:41:33 +0000359
Gregory P. Smith14263542000-05-12 00:41:33 +0000360 # All platforms support local setup.cfg
361 local_file = "setup.cfg"
362 if os.path.isfile(local_file):
363 files.append(local_file)
364
Tarek Ziadéc7c71ff2009-10-27 23:12:01 +0000365 if DEBUG:
366 self.announce("using config files: %s" % ', '.join(files))
367
Gregory P. Smith14263542000-05-12 00:41:33 +0000368 return files
369
Tarek Ziadé188789d2009-05-16 18:37:32 +0000370 def parse_config_files(self, filenames=None):
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000371 from configparser import ConfigParser
Gregory P. Smith14263542000-05-12 00:41:33 +0000372
373 if filenames is None:
374 filenames = self.find_config_files()
375
Tarek Ziadéf11be752009-06-01 22:36:26 +0000376 if DEBUG:
377 self.announce("Distribution.parse_config_files():")
Greg Ward47460772000-05-23 03:47:35 +0000378
Gregory P. Smith14263542000-05-12 00:41:33 +0000379 parser = ConfigParser()
Greg Wardd5d8a992000-05-23 01:42:17 +0000380 for filename in filenames:
Tarek Ziadéf11be752009-06-01 22:36:26 +0000381 if DEBUG:
Tarek Ziadé31d46072009-09-21 13:55:19 +0000382 self.announce(" reading %s" % filename)
Greg Wardd5d8a992000-05-23 01:42:17 +0000383 parser.read(filename)
384 for section in parser.sections():
385 options = parser.options(section)
Greg Ward0e48cfd2000-05-26 01:00:15 +0000386 opt_dict = self.get_option_dict(section)
Gregory P. Smith14263542000-05-12 00:41:33 +0000387
Greg Wardd5d8a992000-05-23 01:42:17 +0000388 for opt in options:
389 if opt != '__name__':
Greg Wardceb9e222000-09-25 01:23:52 +0000390 val = parser.get(section,opt)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000391 opt = opt.replace('-', '_')
Greg Wardceb9e222000-09-25 01:23:52 +0000392 opt_dict[opt] = (filename, val)
Gregory P. Smith14263542000-05-12 00:41:33 +0000393
Greg Ward47460772000-05-23 03:47:35 +0000394 # Make the ConfigParser forget everything (so we retain
Fred Drakef06116d2004-02-17 22:35:19 +0000395 # the original filenames that options come from)
Greg Ward47460772000-05-23 03:47:35 +0000396 parser.__init__()
Gregory P. Smith14263542000-05-12 00:41:33 +0000397
Greg Wardceb9e222000-09-25 01:23:52 +0000398 # If there was a "global" section in the config file, use it
399 # to set Distribution options.
400
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000401 if 'global' in self.command_options:
Greg Wardceb9e222000-09-25 01:23:52 +0000402 for (opt, (src, val)) in self.command_options['global'].items():
403 alias = self.negative_opt.get(opt)
404 try:
405 if alias:
406 setattr(self, alias, not strtobool(val))
407 elif opt in ('verbose', 'dry_run'): # ugh!
408 setattr(self, opt, strtobool(val))
Fred Draked04573f2004-08-03 16:37:40 +0000409 else:
410 setattr(self, opt, val)
Guido van Rossumb940e112007-01-10 16:19:56 +0000411 except ValueError as msg:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000412 raise DistutilsOptionError(msg)
Greg Wardceb9e222000-09-25 01:23:52 +0000413
Greg Wardd5d8a992000-05-23 01:42:17 +0000414 # -- Command-line parsing methods ----------------------------------
415
Tarek Ziadé188789d2009-05-16 18:37:32 +0000416 def parse_command_line(self):
Greg Ward9821bf42000-08-29 01:15:18 +0000417 """Parse the setup script's command line, taken from the
418 'script_args' instance attribute (which defaults to 'sys.argv[1:]'
419 -- see 'setup()' in core.py). This list is first processed for
420 "global options" -- options that set attributes of the Distribution
421 instance. Then, it is alternately scanned for Distutils commands
422 and options for that command. Each new command terminates the
423 options for the previous command. The allowed options for a
424 command are determined by the 'user_options' attribute of the
425 command class -- thus, we have to be able to load command classes
426 in order to parse the command line. Any error in that 'options'
427 attribute raises DistutilsGetoptError; any error on the
428 command-line raises DistutilsArgError. If no Distutils commands
429 were found on the command line, raises DistutilsArgError. Return
Greg Wardceb9e222000-09-25 01:23:52 +0000430 true if command-line was successfully parsed and we should carry
Greg Ward9821bf42000-08-29 01:15:18 +0000431 on with executing commands; false if no errors but we shouldn't
432 execute commands (currently, this only happens if user asks for
433 help).
Greg Wardd5d8a992000-05-23 01:42:17 +0000434 """
Andrew M. Kuchling3f819ec2001-01-15 16:09:35 +0000435 #
Fred Drake981a1782001-08-10 18:59:30 +0000436 # We now have enough information to show the Macintosh dialog
437 # that allows the user to interactively specify the "command line".
Andrew M. Kuchling3f819ec2001-01-15 16:09:35 +0000438 #
Fred Draked04573f2004-08-03 16:37:40 +0000439 toplevel_options = self._get_toplevel_options()
Fred Drakeb94b8492001-12-06 20:51:35 +0000440
Greg Wardfe6462c2000-04-04 01:40:52 +0000441 # We have to parse the command line a bit at a time -- global
442 # options, then the first command, then its options, and so on --
443 # because each command will be handled by a different class, and
Greg Wardd5d8a992000-05-23 01:42:17 +0000444 # the options that are valid for a particular class aren't known
445 # until we have loaded the command class, which doesn't happen
446 # until we know what the command is.
Greg Wardfe6462c2000-04-04 01:40:52 +0000447
448 self.commands = []
Fred Draked04573f2004-08-03 16:37:40 +0000449 parser = FancyGetopt(toplevel_options + self.display_options)
Greg Wardfd7b91e2000-09-26 01:52:25 +0000450 parser.set_negative_aliases(self.negative_opt)
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +0000451 parser.set_aliases({'licence': 'license'})
Greg Wardfd7b91e2000-09-26 01:52:25 +0000452 args = parser.getopt(args=self.script_args, object=self)
Greg Ward82715e12000-04-21 02:28:14 +0000453 option_order = parser.get_option_order()
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000454 log.set_verbosity(self.verbose)
Greg Wardfe6462c2000-04-04 01:40:52 +0000455
Greg Ward82715e12000-04-21 02:28:14 +0000456 # for display options we return immediately
457 if self.handle_display_options(option_order):
Greg Wardfe6462c2000-04-04 01:40:52 +0000458 return
Greg Wardfe6462c2000-04-04 01:40:52 +0000459 while args:
Greg Wardd5d8a992000-05-23 01:42:17 +0000460 args = self._parse_command_opts(parser, args)
461 if args is None: # user asked for help (and got it)
Greg Wardfe6462c2000-04-04 01:40:52 +0000462 return
Greg Wardfe6462c2000-04-04 01:40:52 +0000463
Greg Wardd5d8a992000-05-23 01:42:17 +0000464 # Handle the cases of --help as a "global" option, ie.
465 # "setup.py --help" and "setup.py --help command ...". For the
466 # former, we show global options (--verbose, --dry-run, etc.)
467 # and display-only options (--name, --version, etc.); for the
468 # latter, we omit the display-only options and show help for
469 # each command listed on the command line.
Greg Wardfe6462c2000-04-04 01:40:52 +0000470 if self.help:
Greg Wardd5d8a992000-05-23 01:42:17 +0000471 self._show_help(parser,
472 display_options=len(self.commands) == 0,
473 commands=self.commands)
Greg Wardfe6462c2000-04-04 01:40:52 +0000474 return
475
476 # Oops, no commands found -- an end-user error
477 if not self.commands:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000478 raise DistutilsArgError("no commands supplied")
Greg Wardfe6462c2000-04-04 01:40:52 +0000479
480 # All is well: return true
Collin Winter5b7e9d72007-08-30 03:52:21 +0000481 return True
Greg Wardfe6462c2000-04-04 01:40:52 +0000482
Tarek Ziadé188789d2009-05-16 18:37:32 +0000483 def _get_toplevel_options(self):
Fred Draked04573f2004-08-03 16:37:40 +0000484 """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
Tarek Ziadé188789d2009-05-16 18:37:32 +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):
Collin Winter5b7e9d72007-08-30 03:52:21 +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:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000518 raise DistutilsArgError(msg)
Greg Wardd5d8a992000-05-23 01:42:17 +0000519
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):
Collin Winter5b7e9d72007-08-30 03:52:21 +0000523 raise DistutilsClassError(
524 "command class %s must subclass Command" % cmd_class)
Greg Wardd5d8a992000-05-23 01:42:17 +0000525
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)):
Collin Winter5b7e9d72007-08-30 03:52:21 +0000530 raise DistutilsClassError(("command class %s must provide " +
Greg Wardd5d8a992000-05-23 01:42:17 +0000531 "'user_options' attribute (a list of tuples)") % \
Collin Winter5b7e9d72007-08-30 03:52:21 +0000532 cmd_class)
Greg Wardd5d8a992000-05-23 01:42:17 +0000533
534 # If the command class has a list of negative alias options,
535 # merge it in with the global negative aliases.
536 negative_opt = self.negative_opt
Greg Wardfd7b91e2000-09-26 01:52:25 +0000537 if hasattr(cmd_class, 'negative_opt'):
Antoine Pitrou56a00de2009-05-15 17:34:21 +0000538 negative_opt = negative_opt.copy()
Greg Wardfd7b91e2000-09-26 01:52:25 +0000539 negative_opt.update(cmd_class.negative_opt)
Greg Wardd5d8a992000-05-23 01:42:17 +0000540
Greg Wardfa9ff762000-10-14 04:06:40 +0000541 # Check for help_options in command class. They have a different
542 # format (tuple of four) so we need to preprocess them here.
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000543 if (hasattr(cmd_class, 'help_options') and
Guido van Rossum13257902007-06-07 23:15:56 +0000544 isinstance(cmd_class.help_options, list)):
Greg Ward2ff78872000-06-24 00:23:20 +0000545 help_options = fix_help_options(cmd_class.help_options)
546 else:
Greg Ward55fced32000-06-24 01:22:41 +0000547 help_options = []
Greg Ward2ff78872000-06-24 00:23:20 +0000548
Greg Ward9d17a7a2000-06-07 03:00:06 +0000549
Greg Wardd5d8a992000-05-23 01:42:17 +0000550 # All commands support the global options too, just by adding
551 # in 'global_options'.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000552 parser.set_option_table(self.global_options +
553 cmd_class.user_options +
554 help_options)
555 parser.set_negative_aliases(negative_opt)
556 (args, opts) = parser.getopt(args[1:])
Greg Ward47460772000-05-23 03:47:35 +0000557 if hasattr(opts, 'help') and opts.help:
Greg Wardd5d8a992000-05-23 01:42:17 +0000558 self._show_help(parser, display_options=0, commands=[cmd_class])
559 return
560
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000561 if (hasattr(cmd_class, 'help_options') and
Guido van Rossum13257902007-06-07 23:15:56 +0000562 isinstance(cmd_class.help_options, list)):
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000563 help_option_found=0
564 for (help_option, short, desc, func) in cmd_class.help_options:
565 if hasattr(opts, parser.get_attr_name(help_option)):
566 help_option_found=1
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000567 if hasattr(func, '__call__'):
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000568 func()
Greg Ward55fced32000-06-24 01:22:41 +0000569 else:
Fred Drake981a1782001-08-10 18:59:30 +0000570 raise DistutilsClassError(
Walter Dörwald70a6b492004-02-12 17:35:32 +0000571 "invalid help function %r for help option '%s': "
Fred Drake981a1782001-08-10 18:59:30 +0000572 "must be a callable object (function, etc.)"
Walter Dörwald70a6b492004-02-12 17:35:32 +0000573 % (func, help_option))
Greg Ward55fced32000-06-24 01:22:41 +0000574
Fred Drakeb94b8492001-12-06 20:51:35 +0000575 if help_option_found:
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000576 return
Greg Ward9d17a7a2000-06-07 03:00:06 +0000577
Greg Wardd5d8a992000-05-23 01:42:17 +0000578 # Put the options from the command-line into their official
579 # holding pen, the 'command_options' dictionary.
Greg Ward0e48cfd2000-05-26 01:00:15 +0000580 opt_dict = self.get_option_dict(command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000581 for (name, value) in vars(opts).items():
Greg Ward0e48cfd2000-05-26 01:00:15 +0000582 opt_dict[name] = ("command line", value)
Greg Wardd5d8a992000-05-23 01:42:17 +0000583
584 return args
585
Tarek Ziadé188789d2009-05-16 18:37:32 +0000586 def finalize_options(self):
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000587 """Set final values for all the options on the Distribution
588 instance, analogous to the .finalize_options() method of Command
589 objects.
590 """
Tarek Ziadéf11be752009-06-01 22:36:26 +0000591 for attr in ('keywords', 'platforms'):
592 value = getattr(self.metadata, attr)
593 if value is None:
594 continue
595 if isinstance(value, str):
596 value = [elm.strip() for elm in value.split(',')]
597 setattr(self.metadata, attr, value)
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000598
Tarek Ziadé188789d2009-05-16 18:37:32 +0000599 def _show_help(self, parser, global_options=1, display_options=1,
600 commands=[]):
Greg Wardd5d8a992000-05-23 01:42:17 +0000601 """Show help for the setup script command-line in the form of
602 several lists of command-line options. 'parser' should be a
603 FancyGetopt instance; do not expect it to be returned in the
604 same state, as its option table will be reset to make it
605 generate the correct help text.
606
607 If 'global_options' is true, lists the global options:
608 --verbose, --dry-run, etc. If 'display_options' is true, lists
609 the "display-only" options: --name, --version, etc. Finally,
610 lists per-command help for every command name or command class
611 in 'commands'.
612 """
613 # late import because of mutual dependence between these modules
Greg Ward9821bf42000-08-29 01:15:18 +0000614 from distutils.core import gen_usage
Greg Wardd5d8a992000-05-23 01:42:17 +0000615 from distutils.cmd import Command
616
617 if global_options:
Fred Draked04573f2004-08-03 16:37:40 +0000618 if display_options:
619 options = self._get_toplevel_options()
620 else:
621 options = self.global_options
622 parser.set_option_table(options)
Martin v. Löwis8ed338a2005-03-03 08:12:27 +0000623 parser.print_help(self.common_usage + "\nGlobal options:")
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000624 print('')
Greg Wardd5d8a992000-05-23 01:42:17 +0000625
626 if display_options:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000627 parser.set_option_table(self.display_options)
628 parser.print_help(
Greg Wardd5d8a992000-05-23 01:42:17 +0000629 "Information display options (just display " +
630 "information, ignore any commands)")
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000631 print('')
Greg Wardd5d8a992000-05-23 01:42:17 +0000632
633 for command in self.commands:
Guido van Rossum13257902007-06-07 23:15:56 +0000634 if isinstance(command, type) and issubclass(command, Command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000635 klass = command
636 else:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000637 klass = self.get_command_class(command)
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000638 if (hasattr(klass, 'help_options') and
Guido van Rossum13257902007-06-07 23:15:56 +0000639 isinstance(klass.help_options, list)):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000640 parser.set_option_table(klass.user_options +
641 fix_help_options(klass.help_options))
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000642 else:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000643 parser.set_option_table(klass.user_options)
644 parser.print_help("Options for '%s' command:" % klass.__name__)
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000645 print('')
Greg Wardd5d8a992000-05-23 01:42:17 +0000646
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000647 print(gen_usage(self.script_name))
Greg Wardd5d8a992000-05-23 01:42:17 +0000648
Tarek Ziadé188789d2009-05-16 18:37:32 +0000649 def handle_display_options(self, option_order):
Greg Ward82715e12000-04-21 02:28:14 +0000650 """If there were any non-global "display-only" options
Greg Wardd5d8a992000-05-23 01:42:17 +0000651 (--help-commands or the metadata display options) on the command
652 line, display the requested info and return true; else return
653 false.
654 """
Greg Ward9821bf42000-08-29 01:15:18 +0000655 from distutils.core import gen_usage
Greg Ward82715e12000-04-21 02:28:14 +0000656
657 # User just wants a list of commands -- we'll print it out and stop
658 # processing now (ie. if they ran "setup --help-commands foo bar",
659 # we ignore "foo bar").
660 if self.help_commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000661 self.print_commands()
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000662 print('')
663 print(gen_usage(self.script_name))
Greg Ward82715e12000-04-21 02:28:14 +0000664 return 1
665
666 # If user supplied any of the "display metadata" options, then
667 # display that metadata in the order in which the user supplied the
668 # metadata options.
669 any_display_options = 0
670 is_display_option = {}
671 for option in self.display_options:
672 is_display_option[option[0]] = 1
673
674 for (opt, val) in option_order:
675 if val and is_display_option.get(opt):
Greg Ward2f2b6c62000-09-25 01:58:07 +0000676 opt = translate_longopt(opt)
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000677 value = getattr(self.metadata, "get_"+opt)()
678 if opt in ['keywords', 'platforms']:
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000679 print(','.join(value))
Fred Drakedb7b0022005-03-20 22:19:47 +0000680 elif opt in ('classifiers', 'provides', 'requires',
681 'obsoletes'):
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000682 print('\n'.join(value))
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +0000683 else:
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000684 print(value)
Greg Ward82715e12000-04-21 02:28:14 +0000685 any_display_options = 1
686
687 return any_display_options
688
Tarek Ziadé188789d2009-05-16 18:37:32 +0000689 def print_command_list(self, commands, header, max_length):
Greg Wardfe6462c2000-04-04 01:40:52 +0000690 """Print a subset of the list of all commands -- used by
Greg Wardd5d8a992000-05-23 01:42:17 +0000691 'print_commands()'.
692 """
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000693 print(header + ":")
Greg Wardfe6462c2000-04-04 01:40:52 +0000694
695 for cmd in commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000696 klass = self.cmdclass.get(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000697 if not klass:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000698 klass = self.get_command_class(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000699 try:
700 description = klass.description
701 except AttributeError:
702 description = "(no description available)"
703
Tarek Ziadé0d3fa832009-07-04 03:00:50 +0000704 print(" %-*s %s" % (max_length, cmd, description))
Greg Wardfe6462c2000-04-04 01:40:52 +0000705
Tarek Ziadé188789d2009-05-16 18:37:32 +0000706 def print_commands(self):
Greg Wardd5d8a992000-05-23 01:42:17 +0000707 """Print out a help message listing all available commands with a
708 description of each. The list is divided into "standard commands"
709 (listed in distutils.command.__all__) and "extra commands"
710 (mentioned in self.cmdclass, but not a standard command). The
711 descriptions come from the command class attribute
712 'description'.
713 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000714 import distutils.command
715 std_commands = distutils.command.__all__
716 is_std = {}
717 for cmd in std_commands:
718 is_std[cmd] = 1
719
720 extra_commands = []
721 for cmd in self.cmdclass.keys():
722 if not is_std.get(cmd):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000723 extra_commands.append(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000724
725 max_length = 0
726 for cmd in (std_commands + extra_commands):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000727 if len(cmd) > max_length:
728 max_length = len(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000729
Greg Wardfd7b91e2000-09-26 01:52:25 +0000730 self.print_command_list(std_commands,
731 "Standard commands",
732 max_length)
Greg Wardfe6462c2000-04-04 01:40:52 +0000733 if extra_commands:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000734 print()
Greg Wardfd7b91e2000-09-26 01:52:25 +0000735 self.print_command_list(extra_commands,
736 "Extra commands",
737 max_length)
Greg Wardfe6462c2000-04-04 01:40:52 +0000738
Tarek Ziadé188789d2009-05-16 18:37:32 +0000739 def get_command_list(self):
Greg Wardf6fc8752000-11-11 02:47:11 +0000740 """Get a list of (command, description) tuples.
741 The list is divided into "standard commands" (listed in
742 distutils.command.__all__) and "extra commands" (mentioned in
743 self.cmdclass, but not a standard command). The descriptions come
744 from the command class attribute 'description'.
745 """
746 # Currently this is only used on Mac OS, for the Mac-only GUI
747 # Distutils interface (by Jack Jansen)
Greg Wardf6fc8752000-11-11 02:47:11 +0000748 import distutils.command
749 std_commands = distutils.command.__all__
750 is_std = {}
751 for cmd in std_commands:
752 is_std[cmd] = 1
753
754 extra_commands = []
755 for cmd in self.cmdclass.keys():
756 if not is_std.get(cmd):
757 extra_commands.append(cmd)
758
759 rv = []
760 for cmd in (std_commands + extra_commands):
761 klass = self.cmdclass.get(cmd)
762 if not klass:
763 klass = self.get_command_class(cmd)
764 try:
765 description = klass.description
766 except AttributeError:
767 description = "(no description available)"
768 rv.append((cmd, description))
769 return rv
Greg Wardfe6462c2000-04-04 01:40:52 +0000770
771 # -- Command class/object methods ----------------------------------
772
Tarek Ziadé188789d2009-05-16 18:37:32 +0000773 def get_command_packages(self):
Fred Draked04573f2004-08-03 16:37:40 +0000774 """Return a list of packages from which commands are loaded."""
775 pkgs = self.command_packages
Tarek Ziadéf11be752009-06-01 22:36:26 +0000776 if not isinstance(pkgs, list):
777 if pkgs is None:
778 pkgs = ''
779 pkgs = [pkg.strip() for pkg in pkgs.split(',') if pkg != '']
Fred Draked04573f2004-08-03 16:37:40 +0000780 if "distutils.command" not in pkgs:
781 pkgs.insert(0, "distutils.command")
782 self.command_packages = pkgs
783 return pkgs
784
Tarek Ziadé188789d2009-05-16 18:37:32 +0000785 def get_command_class(self, command):
Greg Wardd5d8a992000-05-23 01:42:17 +0000786 """Return the class that implements the Distutils command named by
787 'command'. First we check the 'cmdclass' dictionary; if the
788 command is mentioned there, we fetch the class object from the
789 dictionary and return it. Otherwise we load the command module
790 ("distutils.command." + command) and fetch the command class from
791 the module. The loaded class is also stored in 'cmdclass'
792 to speed future calls to 'get_command_class()'.
Greg Wardfe6462c2000-04-04 01:40:52 +0000793
Gregory P. Smith14263542000-05-12 00:41:33 +0000794 Raises DistutilsModuleError if the expected module could not be
Greg Wardd5d8a992000-05-23 01:42:17 +0000795 found, or if that module does not define the expected class.
796 """
797 klass = self.cmdclass.get(command)
798 if klass:
799 return klass
Greg Wardfe6462c2000-04-04 01:40:52 +0000800
Fred Draked04573f2004-08-03 16:37:40 +0000801 for pkgname in self.get_command_packages():
802 module_name = "%s.%s" % (pkgname, command)
803 klass_name = command
Greg Wardfe6462c2000-04-04 01:40:52 +0000804
Fred Draked04573f2004-08-03 16:37:40 +0000805 try:
806 __import__ (module_name)
807 module = sys.modules[module_name]
808 except ImportError:
809 continue
Greg Wardfe6462c2000-04-04 01:40:52 +0000810
Fred Draked04573f2004-08-03 16:37:40 +0000811 try:
812 klass = getattr(module, klass_name)
813 except AttributeError:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000814 raise DistutilsModuleError(
815 "invalid command '%s' (no class '%s' in module '%s')"
816 % (command, klass_name, module_name))
Greg Wardfe6462c2000-04-04 01:40:52 +0000817
Fred Draked04573f2004-08-03 16:37:40 +0000818 self.cmdclass[command] = klass
819 return klass
820
821 raise DistutilsModuleError("invalid command '%s'" % command)
822
Tarek Ziadé188789d2009-05-16 18:37:32 +0000823 def get_command_obj(self, command, create=1):
Greg Wardd5d8a992000-05-23 01:42:17 +0000824 """Return the command object for 'command'. Normally this object
Greg Ward612eb9f2000-07-27 02:13:20 +0000825 is cached on a previous call to 'get_command_obj()'; if no command
Greg Wardd5d8a992000-05-23 01:42:17 +0000826 object for 'command' is in the cache, then we either create and
827 return it (if 'create' is true) or return None.
828 """
829 cmd_obj = self.command_obj.get(command)
Greg Wardfe6462c2000-04-04 01:40:52 +0000830 if not cmd_obj and create:
Greg Ward2bd3f422000-06-02 01:59:33 +0000831 if DEBUG:
Tarek Ziadéf11be752009-06-01 22:36:26 +0000832 self.announce("Distribution.get_command_obj(): " \
833 "creating '%s' command object" % command)
Greg Ward47460772000-05-23 03:47:35 +0000834
Greg Wardd5d8a992000-05-23 01:42:17 +0000835 klass = self.get_command_class(command)
Greg Ward47460772000-05-23 03:47:35 +0000836 cmd_obj = self.command_obj[command] = klass(self)
837 self.have_run[command] = 0
838
839 # Set any options that were supplied in config files
840 # or on the command line. (NB. support for error
841 # reporting is lame here: any errors aren't reported
842 # until 'finalize_options()' is called, which means
843 # we won't report the source of the error.)
844 options = self.command_options.get(command)
845 if options:
Greg Wardc32d9a62000-05-28 23:53:06 +0000846 self._set_command_options(cmd_obj, options)
Greg Wardfe6462c2000-04-04 01:40:52 +0000847
848 return cmd_obj
849
Tarek Ziadé188789d2009-05-16 18:37:32 +0000850 def _set_command_options(self, command_obj, option_dict=None):
Greg Wardc32d9a62000-05-28 23:53:06 +0000851 """Set the options for 'command_obj' from 'option_dict'. Basically
852 this means copying elements of a dictionary ('option_dict') to
853 attributes of an instance ('command').
854
Greg Wardceb9e222000-09-25 01:23:52 +0000855 'command_obj' must be a Command instance. If 'option_dict' is not
Greg Wardc32d9a62000-05-28 23:53:06 +0000856 supplied, uses the standard option dictionary for this command
857 (from 'self.command_options').
858 """
Greg Wardc32d9a62000-05-28 23:53:06 +0000859 command_name = command_obj.get_command_name()
860 if option_dict is None:
861 option_dict = self.get_option_dict(command_name)
862
Tarek Ziadéf11be752009-06-01 22:36:26 +0000863 if DEBUG:
864 self.announce(" setting options for '%s' command:" % command_name)
Greg Wardc32d9a62000-05-28 23:53:06 +0000865 for (option, (source, value)) in option_dict.items():
Tarek Ziadéf11be752009-06-01 22:36:26 +0000866 if DEBUG:
867 self.announce(" %s = %s (from %s)" % (option, value,
868 source))
Greg Wardceb9e222000-09-25 01:23:52 +0000869 try:
Amaury Forgeot d'Arc61cb0872008-07-26 20:09:45 +0000870 bool_opts = [translate_longopt(o)
871 for o in command_obj.boolean_options]
Greg Wardceb9e222000-09-25 01:23:52 +0000872 except AttributeError:
873 bool_opts = []
874 try:
875 neg_opt = command_obj.negative_opt
876 except AttributeError:
877 neg_opt = {}
878
879 try:
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000880 is_string = isinstance(value, str)
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000881 if option in neg_opt and is_string:
Greg Wardceb9e222000-09-25 01:23:52 +0000882 setattr(command_obj, neg_opt[option], not strtobool(value))
Greg Ward2c08cf02000-09-27 00:15:37 +0000883 elif option in bool_opts and is_string:
Greg Wardceb9e222000-09-25 01:23:52 +0000884 setattr(command_obj, option, strtobool(value))
885 elif hasattr(command_obj, option):
886 setattr(command_obj, option, value)
887 else:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000888 raise DistutilsOptionError(
889 "error in %s: command '%s' has no such option '%s'"
890 % (source, command_name, option))
Guido van Rossumb940e112007-01-10 16:19:56 +0000891 except ValueError as msg:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000892 raise DistutilsOptionError(msg)
Greg Wardc32d9a62000-05-28 23:53:06 +0000893
Tarek Ziadé188789d2009-05-16 18:37:32 +0000894 def reinitialize_command(self, command, reinit_subcommands=0):
Greg Wardc32d9a62000-05-28 23:53:06 +0000895 """Reinitializes a command to the state it was in when first
896 returned by 'get_command_obj()': ie., initialized but not yet
Greg Ward7d9c7052000-06-28 01:25:27 +0000897 finalized. This provides the opportunity to sneak option
Greg Wardc32d9a62000-05-28 23:53:06 +0000898 values in programmatically, overriding or supplementing
899 user-supplied values from the config files and command line.
900 You'll have to re-finalize the command object (by calling
901 'finalize_options()' or 'ensure_finalized()') before using it for
Fred Drakeb94b8492001-12-06 20:51:35 +0000902 real.
Greg Wardc32d9a62000-05-28 23:53:06 +0000903
Greg Wardf449ea52000-09-16 15:23:28 +0000904 'command' should be a command name (string) or command object. If
905 'reinit_subcommands' is true, also reinitializes the command's
906 sub-commands, as declared by the 'sub_commands' class attribute (if
907 it has one). See the "install" command for an example. Only
908 reinitializes the sub-commands that actually matter, ie. those
909 whose test predicates return true.
910
Greg Wardc32d9a62000-05-28 23:53:06 +0000911 Returns the reinitialized command object.
912 """
913 from distutils.cmd import Command
914 if not isinstance(command, Command):
915 command_name = command
916 command = self.get_command_obj(command_name)
917 else:
918 command_name = command.get_command_name()
919
920 if not command.finalized:
Greg Ward282c7a02000-06-01 01:09:47 +0000921 return command
Greg Wardc32d9a62000-05-28 23:53:06 +0000922 command.initialize_options()
923 command.finalized = 0
Greg Ward43955c92000-06-06 02:52:36 +0000924 self.have_run[command_name] = 0
Greg Wardc32d9a62000-05-28 23:53:06 +0000925 self._set_command_options(command)
Greg Wardf449ea52000-09-16 15:23:28 +0000926
Greg Wardf449ea52000-09-16 15:23:28 +0000927 if reinit_subcommands:
Greg Wardf449ea52000-09-16 15:23:28 +0000928 for sub in command.get_sub_commands():
Fred Drakeb94b8492001-12-06 20:51:35 +0000929 self.reinitialize_command(sub, reinit_subcommands)
Greg Wardf449ea52000-09-16 15:23:28 +0000930
Greg Wardc32d9a62000-05-28 23:53:06 +0000931 return command
932
Greg Wardfe6462c2000-04-04 01:40:52 +0000933 # -- Methods that operate on the Distribution ----------------------
934
Tarek Ziadé05bf01a2009-07-04 02:04:21 +0000935 def announce(self, msg, level=log.INFO):
936 log.log(level, msg)
Greg Wardfe6462c2000-04-04 01:40:52 +0000937
Tarek Ziadé188789d2009-05-16 18:37:32 +0000938 def run_commands(self):
Greg Ward82715e12000-04-21 02:28:14 +0000939 """Run each command that was seen on the setup script command line.
Greg Wardd5d8a992000-05-23 01:42:17 +0000940 Uses the list of commands found and cache of command objects
Greg Wardfd7b91e2000-09-26 01:52:25 +0000941 created by 'get_command_obj()'.
942 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000943 for cmd in self.commands:
Greg Wardfd7b91e2000-09-26 01:52:25 +0000944 self.run_command(cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000945
Greg Wardfe6462c2000-04-04 01:40:52 +0000946 # -- Methods that operate on its Commands --------------------------
947
Tarek Ziadé188789d2009-05-16 18:37:32 +0000948 def run_command(self, command):
Greg Wardfe6462c2000-04-04 01:40:52 +0000949 """Do whatever it takes to run a command (including nothing at all,
Greg Wardd5d8a992000-05-23 01:42:17 +0000950 if the command has already been run). Specifically: if we have
951 already created and run the command named by 'command', return
952 silently without doing anything. If the command named by 'command'
953 doesn't even have a command object yet, create one. Then invoke
954 'run()' on that command object (or an existing one).
955 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000956 # Already been here, done that? then return silently.
Greg Wardfd7b91e2000-09-26 01:52:25 +0000957 if self.have_run.get(command):
Greg Wardfe6462c2000-04-04 01:40:52 +0000958 return
959
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000960 log.info("running %s", command)
Greg Wardfd7b91e2000-09-26 01:52:25 +0000961 cmd_obj = self.get_command_obj(command)
962 cmd_obj.ensure_finalized()
963 cmd_obj.run()
Greg Wardfe6462c2000-04-04 01:40:52 +0000964 self.have_run[command] = 1
965
966
Greg Wardfe6462c2000-04-04 01:40:52 +0000967 # -- Distribution query methods ------------------------------------
968
Tarek Ziadé188789d2009-05-16 18:37:32 +0000969 def has_pure_modules(self):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000970 return len(self.packages or self.py_modules or []) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000971
Tarek Ziadé188789d2009-05-16 18:37:32 +0000972 def has_ext_modules(self):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000973 return self.ext_modules and len(self.ext_modules) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000974
Tarek Ziadé188789d2009-05-16 18:37:32 +0000975 def has_c_libraries(self):
Greg Wardfd7b91e2000-09-26 01:52:25 +0000976 return self.libraries and len(self.libraries) > 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000977
Tarek Ziadé188789d2009-05-16 18:37:32 +0000978 def has_modules(self):
Greg Wardfe6462c2000-04-04 01:40:52 +0000979 return self.has_pure_modules() or self.has_ext_modules()
980
Tarek Ziadé188789d2009-05-16 18:37:32 +0000981 def has_headers(self):
Greg Ward51def7d2000-05-27 01:36:14 +0000982 return self.headers and len(self.headers) > 0
983
Tarek Ziadé188789d2009-05-16 18:37:32 +0000984 def has_scripts(self):
Greg Ward44a61bb2000-05-20 15:06:48 +0000985 return self.scripts and len(self.scripts) > 0
986
Tarek Ziadé188789d2009-05-16 18:37:32 +0000987 def has_data_files(self):
Greg Ward44a61bb2000-05-20 15:06:48 +0000988 return self.data_files and len(self.data_files) > 0
989
Tarek Ziadé188789d2009-05-16 18:37:32 +0000990 def is_pure(self):
Greg Wardfe6462c2000-04-04 01:40:52 +0000991 return (self.has_pure_modules() and
992 not self.has_ext_modules() and
993 not self.has_c_libraries())
994
Greg Ward82715e12000-04-21 02:28:14 +0000995 # -- Metadata query methods ----------------------------------------
996
997 # If you're looking for 'get_name()', 'get_version()', and so forth,
998 # they are defined in a sneaky way: the constructor binds self.get_XXX
999 # to self.metadata.get_XXX. The actual code is in the
1000 # DistributionMetadata class, below.
1001
Greg Ward82715e12000-04-21 02:28:14 +00001002class DistributionMetadata:
1003 """Dummy class to hold the distribution meta-data: name, version,
Greg Wardfd7b91e2000-09-26 01:52:25 +00001004 author, and so forth.
1005 """
Greg Ward82715e12000-04-21 02:28:14 +00001006
Neil Schemenauera8aefe52001-09-03 15:47:21 +00001007 _METHOD_BASENAMES = ("name", "version", "author", "author_email",
1008 "maintainer", "maintainer_email", "url",
1009 "license", "description", "long_description",
1010 "keywords", "platforms", "fullname", "contact",
Andrew M. Kuchlinga52b8522003-03-03 20:07:27 +00001011 "contact_email", "license", "classifiers",
Fred Drakedb7b0022005-03-20 22:19:47 +00001012 "download_url",
1013 # PEP 314
1014 "provides", "requires", "obsoletes",
1015 )
Neil Schemenauera8aefe52001-09-03 15:47:21 +00001016
Greg Ward82715e12000-04-21 02:28:14 +00001017 def __init__ (self):
1018 self.name = None
1019 self.version = None
1020 self.author = None
1021 self.author_email = None
1022 self.maintainer = None
1023 self.maintainer_email = None
1024 self.url = None
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +00001025 self.license = None
Greg Ward82715e12000-04-21 02:28:14 +00001026 self.description = None
Greg Warde5a584e2000-04-26 02:26:55 +00001027 self.long_description = None
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001028 self.keywords = None
1029 self.platforms = None
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +00001030 self.classifiers = None
Andrew M. Kuchling188d85f2003-02-19 14:16:01 +00001031 self.download_url = None
Fred Drakedb7b0022005-03-20 22:19:47 +00001032 # PEP 314
1033 self.provides = None
1034 self.requires = None
1035 self.obsoletes = None
Fred Drakeb94b8492001-12-06 20:51:35 +00001036
Tarek Ziadé188789d2009-05-16 18:37:32 +00001037 def write_pkg_info(self, base_dir):
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001038 """Write the PKG-INFO file into the release tree.
1039 """
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001040 pkg_info = open( os.path.join(base_dir, 'PKG-INFO'), 'w')
Fred Drakedb7b0022005-03-20 22:19:47 +00001041 self.write_pkg_file(pkg_info)
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001042 pkg_info.close()
Fred Drakeb94b8492001-12-06 20:51:35 +00001043
Tarek Ziadé188789d2009-05-16 18:37:32 +00001044 def write_pkg_file(self, file):
Fred Drakedb7b0022005-03-20 22:19:47 +00001045 """Write the PKG-INFO format data to a file object.
1046 """
1047 version = '1.0'
1048 if self.provides or self.requires or self.obsoletes:
1049 version = '1.1'
1050
1051 file.write('Metadata-Version: %s\n' % version)
1052 file.write('Name: %s\n' % self.get_name() )
1053 file.write('Version: %s\n' % self.get_version() )
1054 file.write('Summary: %s\n' % self.get_description() )
1055 file.write('Home-page: %s\n' % self.get_url() )
1056 file.write('Author: %s\n' % self.get_contact() )
1057 file.write('Author-email: %s\n' % self.get_contact_email() )
1058 file.write('License: %s\n' % self.get_license() )
1059 if self.download_url:
1060 file.write('Download-URL: %s\n' % self.download_url)
1061
Tarek Ziadéf11be752009-06-01 22:36:26 +00001062 long_desc = rfc822_escape(self.get_long_description())
Fred Drakedb7b0022005-03-20 22:19:47 +00001063 file.write('Description: %s\n' % long_desc)
1064
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001065 keywords = ','.join(self.get_keywords())
Fred Drakedb7b0022005-03-20 22:19:47 +00001066 if keywords:
1067 file.write('Keywords: %s\n' % keywords )
1068
1069 self._write_list(file, 'Platform', self.get_platforms())
1070 self._write_list(file, 'Classifier', self.get_classifiers())
1071
1072 # PEP 314
1073 self._write_list(file, 'Requires', self.get_requires())
1074 self._write_list(file, 'Provides', self.get_provides())
1075 self._write_list(file, 'Obsoletes', self.get_obsoletes())
1076
Tarek Ziadé188789d2009-05-16 18:37:32 +00001077 def _write_list(self, file, name, values):
Fred Drakedb7b0022005-03-20 22:19:47 +00001078 for value in values:
1079 file.write('%s: %s\n' % (name, value))
1080
Greg Ward82715e12000-04-21 02:28:14 +00001081 # -- Metadata query methods ----------------------------------------
1082
Tarek Ziadé188789d2009-05-16 18:37:32 +00001083 def get_name(self):
Greg Wardfe6462c2000-04-04 01:40:52 +00001084 return self.name or "UNKNOWN"
1085
Greg Ward82715e12000-04-21 02:28:14 +00001086 def get_version(self):
Thomas Hellerbcd89752001-12-06 20:44:19 +00001087 return self.version or "0.0.0"
Greg Wardfe6462c2000-04-04 01:40:52 +00001088
Tarek Ziadé188789d2009-05-16 18:37:32 +00001089 def get_fullname(self):
Greg Ward82715e12000-04-21 02:28:14 +00001090 return "%s-%s" % (self.get_name(), self.get_version())
1091
1092 def get_author(self):
1093 return self.author or "UNKNOWN"
1094
1095 def get_author_email(self):
1096 return self.author_email or "UNKNOWN"
1097
1098 def get_maintainer(self):
1099 return self.maintainer or "UNKNOWN"
1100
1101 def get_maintainer_email(self):
1102 return self.maintainer_email or "UNKNOWN"
1103
1104 def get_contact(self):
Tarek Ziadé188789d2009-05-16 18:37:32 +00001105 return self.maintainer or self.author or "UNKNOWN"
Greg Ward82715e12000-04-21 02:28:14 +00001106
1107 def get_contact_email(self):
Tarek Ziadé188789d2009-05-16 18:37:32 +00001108 return self.maintainer_email or self.author_email or "UNKNOWN"
Greg Ward82715e12000-04-21 02:28:14 +00001109
1110 def get_url(self):
1111 return self.url or "UNKNOWN"
1112
Andrew M. Kuchlingfa7dc572001-08-10 18:49:23 +00001113 def get_license(self):
1114 return self.license or "UNKNOWN"
1115 get_licence = get_license
Fred Drakeb94b8492001-12-06 20:51:35 +00001116
Greg Ward82715e12000-04-21 02:28:14 +00001117 def get_description(self):
1118 return self.description or "UNKNOWN"
Greg Warde5a584e2000-04-26 02:26:55 +00001119
1120 def get_long_description(self):
1121 return self.long_description or "UNKNOWN"
1122
Andrew M. Kuchlinga7210ed2001-03-22 03:06:52 +00001123 def get_keywords(self):
1124 return self.keywords or []
1125
1126 def get_platforms(self):
1127 return self.platforms or ["UNKNOWN"]
1128
Andrew M. Kuchling282e2c32003-01-03 15:24:36 +00001129 def get_classifiers(self):
1130 return self.classifiers or []
1131
Andrew M. Kuchling188d85f2003-02-19 14:16:01 +00001132 def get_download_url(self):
1133 return self.download_url or "UNKNOWN"
1134
Fred Drakedb7b0022005-03-20 22:19:47 +00001135 # PEP 314
Fred Drakedb7b0022005-03-20 22:19:47 +00001136 def get_requires(self):
1137 return self.requires or []
1138
1139 def set_requires(self, value):
1140 import distutils.versionpredicate
1141 for v in value:
1142 distutils.versionpredicate.VersionPredicate(v)
1143 self.requires = value
1144
1145 def get_provides(self):
1146 return self.provides or []
1147
1148 def set_provides(self, value):
1149 value = [v.strip() for v in value]
1150 for v in value:
1151 import distutils.versionpredicate
Fred Drake227e8ff2005-03-21 06:36:32 +00001152 distutils.versionpredicate.split_provision(v)
Fred Drakedb7b0022005-03-20 22:19:47 +00001153 self.provides = value
1154
1155 def get_obsoletes(self):
1156 return self.obsoletes or []
1157
1158 def set_obsoletes(self, value):
1159 import distutils.versionpredicate
1160 for v in value:
1161 distutils.versionpredicate.VersionPredicate(v)
1162 self.obsoletes = value
1163
Tarek Ziadé188789d2009-05-16 18:37:32 +00001164def fix_help_options(options):
Greg Ward2ff78872000-06-24 00:23:20 +00001165 """Convert a 4-tuple 'help_options' list as found in various command
1166 classes to the 3-tuple form required by FancyGetopt.
1167 """
1168 new_options = []
1169 for help_tuple in options:
1170 new_options.append(help_tuple[0:3])
1171 return new_options