3 Provides the Distribution class, which represents the module distribution
4 being built/installed/distributed.
7 # created 2000/04/03, Greg Ward
8 # (extricated from core.py; actually dates back to the beginning)
12 import sys
, os
, string
, re
15 from distutils
.errors
import *
16 from distutils
.fancy_getopt
import FancyGetopt
, translate_longopt
17 from distutils
.util
import check_environ
, strtobool
, rfc822_escape
18 from distutils
import log
19 from distutils
.debug
import DEBUG
21 # Regex to define acceptable Distutils command names. This is not *quite*
22 # the same as a Python NAME -- I don't allow leading underscores. The fact
23 # that they're very similar is no coincidence; the default naming scheme is
24 # to look for a Python module named after the command.
25 command_re
= re
.compile (r
'^[a-zA-Z]([a-zA-Z0-9_]*)$')
29 """The core of the Distutils. Most of the work hiding behind 'setup'
30 is really done within a Distribution instance, which farms the work out
31 to the Distutils commands specified on the command line.
33 Setup scripts will almost never instantiate Distribution directly,
34 unless the 'setup()' function is totally inadequate to their needs.
35 However, it is conceivable that a setup script might wish to subclass
36 Distribution for some specialized purpose, and then pass the subclass
37 to 'setup()' as the 'distclass' keyword argument. If so, it is
38 necessary to respect the expectations that 'setup' has of Distribution.
39 See the code for 'setup()', in core.py, for details.
43 # 'global_options' describes the command-line options that may be
44 # supplied to the setup script prior to any actual commands.
45 # Eg. "./setup.py -n" or "./setup.py --quiet" both take advantage of
46 # these global options. This list should be kept to a bare minimum,
47 # since every global option is also valid as a command option -- and we
48 # don't want to pollute the commands with too many options that they
49 # have minimal control over.
50 # The fourth entry for verbose means that it can be repeated.
51 global_options
= [('verbose', 'v', "run verbosely (default)", 1),
52 ('quiet', 'q', "run quietly (turns verbosity off)"),
53 ('dry-run', 'n', "don't actually do anything"),
54 ('help', 'h', "show detailed help message"),
57 # options that are not propagated to the commands
59 ('help-commands', None,
60 "list all available commands"),
62 "print package name"),
64 "print package version"),
66 "print <package name>-<version>"),
68 "print the author's name"),
69 ('author-email', None,
70 "print the author's email address"),
72 "print the maintainer's name"),
73 ('maintainer-email', None,
74 "print the maintainer's email address"),
76 "print the maintainer's name if known, else the author's"),
77 ('contact-email', None,
78 "print the maintainer's email address if known, else the author's"),
80 "print the URL for this package"),
82 "print the license of the package"),
84 "alias for --license"),
86 "print the package description"),
87 ('long-description', None,
88 "print the long package description"),
90 "print the list of platforms"),
92 "print the list of keywords"),
94 display_option_names
= map(lambda x
: translate_longopt(x
[0]),
97 # negative options are options that exclude other options
98 negative_opt
= {'quiet': 'verbose'}
101 # -- Creation/initialization methods -------------------------------
103 def __init__ (self
, attrs
=None):
104 """Construct a new Distribution instance: initialize all the
105 attributes of a Distribution, and then use 'attrs' (a dictionary
106 mapping attribute names to values) to assign some of those
107 attributes their "real" values. (Any attributes not mentioned in
108 'attrs' will be assigned to some null value: 0, None, an empty list
109 or dictionary, etc.) Most importantly, initialize the
110 'command_obj' attribute to the empty dictionary; this will be
111 filled in with real command objects by 'parse_command_line()'.
114 # Default values for our command-line options
118 for attr
in self
.display_option_names
:
119 setattr(self
, attr
, 0)
121 # Store the distribution meta-data (name, version, author, and so
122 # forth) in a separate object -- we're getting to have enough
123 # information here (and enough command-line options) that it's
124 # worth it. Also delegate 'get_XXX()' methods to the 'metadata'
125 # object in a sneaky and underhanded (but efficient!) way.
126 self
.metadata
= DistributionMetadata()
127 for basename
in self
.metadata
._METHOD
_BASENAMES
:
128 method_name
= "get_" + basename
129 setattr(self
, method_name
, getattr(self
.metadata
, method_name
))
131 # 'cmdclass' maps command names to class objects, so we
132 # can 1) quickly figure out which class to instantiate when
133 # we need to create a new command object, and 2) have a way
134 # for the setup script to override command classes
137 # 'script_name' and 'script_args' are usually set to sys.argv[0]
138 # and sys.argv[1:], but they can be overridden when the caller is
139 # not necessarily a setup script run from the command-line.
140 self
.script_name
= None
141 self
.script_args
= None
143 # 'command_options' is where we store command options between
144 # parsing them (from config files, the command-line, etc.) and when
145 # they are actually needed -- ie. when the command in question is
146 # instantiated. It is a dictionary of dictionaries of 2-tuples:
147 # command_options = { command_name : { option : (source, value) } }
148 self
.command_options
= {}
150 # These options are really the business of various commands, rather
151 # than of the Distribution itself. We provide aliases for them in
152 # Distribution as a convenience to the developer.
154 self
.package_dir
= None
155 self
.py_modules
= None
156 self
.libraries
= None
158 self
.ext_modules
= None
159 self
.ext_package
= None
160 self
.include_dirs
= None
161 self
.extra_path
= None
163 self
.data_files
= None
165 # And now initialize bookkeeping stuff that can't be supplied by
166 # the caller at all. 'command_obj' maps command names to
167 # Command instances -- that's how we enforce that every command
168 # class is a singleton.
169 self
.command_obj
= {}
171 # 'have_run' maps command names to boolean values; it keeps track
172 # of whether we have actually run a particular command, to make it
173 # cheap to "run" a command whenever we think we might need to -- if
174 # it's already been done, no need for expensive filesystem
175 # operations, we just check the 'have_run' dictionary and carry on.
176 # It's only safe to query 'have_run' for a command class that has
177 # been instantiated -- a false value will be inserted when the
178 # command object is created, and replaced with a true value when
179 # the command is successfully run. Thus it's probably best to use
180 # '.get()' rather than a straight lookup.
183 # Now we'll use the attrs dictionary (ultimately, keyword args from
184 # the setup script) to possibly override any or all of these
185 # distribution options.
189 # Pull out the set of command options and work on them
190 # specifically. Note that this order guarantees that aliased
191 # command options will override any supplied redundantly
192 # through the general options dictionary.
193 options
= attrs
.get('options')
196 for (command
, cmd_options
) in options
.items():
197 opt_dict
= self
.get_option_dict(command
)
198 for (opt
, val
) in cmd_options
.items():
199 opt_dict
[opt
] = ("setup script", val
)
201 # Now work on the rest of the attributes. Any attribute that's
202 # not already defined is invalid!
203 for (key
,val
) in attrs
.items():
204 if hasattr(self
.metadata
, key
):
205 setattr(self
.metadata
, key
, val
)
206 elif hasattr(self
, key
):
207 setattr(self
, key
, val
)
209 raise DistutilsSetupError
, \
210 "invalid distribution option '%s'" % key
212 self
.finalize_options()
217 def get_option_dict (self
, command
):
218 """Get the option dictionary for a given command. If that
219 command's option dictionary hasn't been created yet, then create it
220 and return the new dictionary; otherwise, return the existing
224 dict = self
.command_options
.get(command
)
226 dict = self
.command_options
[command
] = {}
230 def dump_option_dicts (self
, header
=None, commands
=None, indent
=""):
231 from pprint
import pformat
233 if commands
is None: # dump all command option dicts
234 commands
= self
.command_options
.keys()
237 if header
is not None:
238 print indent
+ header
239 indent
= indent
+ " "
242 print indent
+ "no commands known yet"
245 for cmd_name
in commands
:
246 opt_dict
= self
.command_options
.get(cmd_name
)
248 print indent
+ "no option dict for '%s' command" % cmd_name
250 print indent
+ "option dict for '%s' command:" % cmd_name
251 out
= pformat(opt_dict
)
252 for line
in string
.split(out
, "\n"):
253 print indent
+ " " + line
255 # dump_option_dicts ()
259 # -- Config file finding/parsing methods ---------------------------
261 def find_config_files (self
):
262 """Find as many configuration files as should be processed for this
263 platform, and return a list of filenames in the order in which they
264 should be parsed. The filenames returned are guaranteed to exist
265 (modulo nasty race conditions).
267 There are three possible config files: distutils.cfg in the
268 Distutils installation directory (ie. where the top-level
269 Distutils __inst__.py file lives), a file in the user's home
270 directory named .pydistutils.cfg on Unix and pydistutils.cfg
271 on Windows/Mac, and setup.cfg in the current directory.
276 # Where to look for the system-wide Distutils config file
277 sys_dir
= os
.path
.dirname(sys
.modules
['distutils'].__file
__)
279 # Look for the system config file
280 sys_file
= os
.path
.join(sys_dir
, "distutils.cfg")
281 if os
.path
.isfile(sys_file
):
282 files
.append(sys_file
)
284 # What to call the per-user config file
285 if os
.name
== 'posix':
286 user_filename
= ".pydistutils.cfg"
288 user_filename
= "pydistutils.cfg"
290 # And look for the user config file
291 if os
.environ
.has_key('HOME'):
292 user_file
= os
.path
.join(os
.environ
.get('HOME'), user_filename
)
293 if os
.path
.isfile(user_file
):
294 files
.append(user_file
)
296 # All platforms support local setup.cfg
297 local_file
= "setup.cfg"
298 if os
.path
.isfile(local_file
):
299 files
.append(local_file
)
303 # find_config_files ()
306 def parse_config_files (self
, filenames
=None):
308 from ConfigParser
import ConfigParser
310 if filenames
is None:
311 filenames
= self
.find_config_files()
313 if DEBUG
: print "Distribution.parse_config_files():"
315 parser
= ConfigParser()
316 for filename
in filenames
:
317 if DEBUG
: print " reading", filename
318 parser
.read(filename
)
319 for section
in parser
.sections():
320 options
= parser
.options(section
)
321 opt_dict
= self
.get_option_dict(section
)
324 if opt
!= '__name__':
325 val
= parser
.get(section
,opt
)
326 opt
= string
.replace(opt
, '-', '_')
327 opt_dict
[opt
] = (filename
, val
)
329 # Make the ConfigParser forget everything (so we retain
330 # the original filenames that options come from) -- gag,
331 # retch, puke -- another good reason for a distutils-
332 # specific config parser (sigh...)
335 # If there was a "global" section in the config file, use it
336 # to set Distribution options.
338 if self
.command_options
.has_key('global'):
339 for (opt
, (src
, val
)) in self
.command_options
['global'].items():
340 alias
= self
.negative_opt
.get(opt
)
343 setattr(self
, alias
, not strtobool(val
))
344 elif opt
in ('verbose', 'dry_run'): # ugh!
345 setattr(self
, opt
, strtobool(val
))
346 except ValueError, msg
:
347 raise DistutilsOptionError
, msg
349 # parse_config_files ()
352 # -- Command-line parsing methods ----------------------------------
354 def parse_command_line (self
):
355 """Parse the setup script's command line, taken from the
356 'script_args' instance attribute (which defaults to 'sys.argv[1:]'
357 -- see 'setup()' in core.py). This list is first processed for
358 "global options" -- options that set attributes of the Distribution
359 instance. Then, it is alternately scanned for Distutils commands
360 and options for that command. Each new command terminates the
361 options for the previous command. The allowed options for a
362 command are determined by the 'user_options' attribute of the
363 command class -- thus, we have to be able to load command classes
364 in order to parse the command line. Any error in that 'options'
365 attribute raises DistutilsGetoptError; any error on the
366 command-line raises DistutilsArgError. If no Distutils commands
367 were found on the command line, raises DistutilsArgError. Return
368 true if command-line was successfully parsed and we should carry
369 on with executing commands; false if no errors but we shouldn't
370 execute commands (currently, this only happens if user asks for
374 # We now have enough information to show the Macintosh dialog
375 # that allows the user to interactively specify the "command line".
377 if sys
.platform
== 'mac':
379 cmdlist
= self
.get_command_list()
380 self
.script_args
= EasyDialogs
.GetArgv(
381 self
.global_options
+ self
.display_options
, cmdlist
)
383 # We have to parse the command line a bit at a time -- global
384 # options, then the first command, then its options, and so on --
385 # because each command will be handled by a different class, and
386 # the options that are valid for a particular class aren't known
387 # until we have loaded the command class, which doesn't happen
388 # until we know what the command is.
391 parser
= FancyGetopt(self
.global_options
+ self
.display_options
)
392 parser
.set_negative_aliases(self
.negative_opt
)
393 parser
.set_aliases({'licence': 'license'})
394 args
= parser
.getopt(args
=self
.script_args
, object=self
)
395 option_order
= parser
.get_option_order()
396 log
.set_verbosity(self
.verbose
)
398 # for display options we return immediately
399 if self
.handle_display_options(option_order
):
403 args
= self
._parse
_command
_opts
(parser
, args
)
404 if args
is None: # user asked for help (and got it)
407 # Handle the cases of --help as a "global" option, ie.
408 # "setup.py --help" and "setup.py --help command ...". For the
409 # former, we show global options (--verbose, --dry-run, etc.)
410 # and display-only options (--name, --version, etc.); for the
411 # latter, we omit the display-only options and show help for
412 # each command listed on the command line.
414 self
._show
_help
(parser
,
415 display_options
=len(self
.commands
) == 0,
416 commands
=self
.commands
)
419 # Oops, no commands found -- an end-user error
420 if not self
.commands
:
421 raise DistutilsArgError
, "no commands supplied"
423 # All is well: return true
426 # parse_command_line()
428 def _parse_command_opts (self
, parser
, args
):
429 """Parse the command-line options for a single command.
430 'parser' must be a FancyGetopt instance; 'args' must be the list
431 of arguments, starting with the current command (whose options
432 we are about to parse). Returns a new version of 'args' with
433 the next command at the front of the list; will be the empty
434 list if there are no more commands on the command line. Returns
435 None if the user asked for help on this command.
437 # late import because of mutual dependence between these modules
438 from distutils
.cmd
import Command
440 # Pull the current command from the head of the command line
442 if not command_re
.match(command
):
443 raise SystemExit, "invalid command name '%s'" % command
444 self
.commands
.append(command
)
446 # Dig up the command class that implements this command, so we
447 # 1) know that it's a valid command, and 2) know which options
450 cmd_class
= self
.get_command_class(command
)
451 except DistutilsModuleError
, msg
:
452 raise DistutilsArgError
, msg
454 # Require that the command class be derived from Command -- want
455 # to be sure that the basic "command" interface is implemented.
456 if not issubclass(cmd_class
, Command
):
457 raise DistutilsClassError
, \
458 "command class %s must subclass Command" % cmd_class
460 # Also make sure that the command object provides a list of its
462 if not (hasattr(cmd_class
, 'user_options') and
463 type(cmd_class
.user_options
) is ListType
):
464 raise DistutilsClassError
, \
465 ("command class %s must provide " +
466 "'user_options' attribute (a list of tuples)") % \
469 # If the command class has a list of negative alias options,
470 # merge it in with the global negative aliases.
471 negative_opt
= self
.negative_opt
472 if hasattr(cmd_class
, 'negative_opt'):
473 negative_opt
= copy(negative_opt
)
474 negative_opt
.update(cmd_class
.negative_opt
)
476 # Check for help_options in command class. They have a different
477 # format (tuple of four) so we need to preprocess them here.
478 if (hasattr(cmd_class
, 'help_options') and
479 type(cmd_class
.help_options
) is ListType
):
480 help_options
= fix_help_options(cmd_class
.help_options
)
485 # All commands support the global options too, just by adding
486 # in 'global_options'.
487 parser
.set_option_table(self
.global_options
+
488 cmd_class
.user_options
+
490 parser
.set_negative_aliases(negative_opt
)
491 (args
, opts
) = parser
.getopt(args
[1:])
492 if hasattr(opts
, 'help') and opts
.help:
493 self
._show
_help
(parser
, display_options
=0, commands
=[cmd_class
])
496 if (hasattr(cmd_class
, 'help_options') and
497 type(cmd_class
.help_options
) is ListType
):
499 for (help_option
, short
, desc
, func
) in cmd_class
.help_options
:
500 if hasattr(opts
, parser
.get_attr_name(help_option
)):
502 #print "showing help for option %s of command %s" % \
503 # (help_option[0],cmd_class)
508 raise DistutilsClassError(
509 "invalid help function %s for help option '%s': "
510 "must be a callable object (function, etc.)"
511 % (`func`
, help_option
))
513 if help_option_found
:
516 # Put the options from the command-line into their official
517 # holding pen, the 'command_options' dictionary.
518 opt_dict
= self
.get_option_dict(command
)
519 for (name
, value
) in vars(opts
).items():
520 opt_dict
[name
] = ("command line", value
)
524 # _parse_command_opts ()
527 def finalize_options (self
):
528 """Set final values for all the options on the Distribution
529 instance, analogous to the .finalize_options() method of Command
533 keywords
= self
.metadata
.keywords
534 if keywords
is not None:
535 if type(keywords
) is StringType
:
536 keywordlist
= string
.split(keywords
, ',')
537 self
.metadata
.keywords
= map(string
.strip
, keywordlist
)
539 platforms
= self
.metadata
.platforms
540 if platforms
is not None:
541 if type(platforms
) is StringType
:
542 platformlist
= string
.split(platforms
, ',')
543 self
.metadata
.platforms
= map(string
.strip
, platformlist
)
545 def _show_help (self
,
550 """Show help for the setup script command-line in the form of
551 several lists of command-line options. 'parser' should be a
552 FancyGetopt instance; do not expect it to be returned in the
553 same state, as its option table will be reset to make it
554 generate the correct help text.
556 If 'global_options' is true, lists the global options:
557 --verbose, --dry-run, etc. If 'display_options' is true, lists
558 the "display-only" options: --name, --version, etc. Finally,
559 lists per-command help for every command name or command class
562 # late import because of mutual dependence between these modules
563 from distutils
.core
import gen_usage
564 from distutils
.cmd
import Command
567 parser
.set_option_table(self
.global_options
)
568 parser
.print_help("Global options:")
572 parser
.set_option_table(self
.display_options
)
574 "Information display options (just display " +
575 "information, ignore any commands)")
578 for command
in self
.commands
:
579 if type(command
) is ClassType
and issubclass(command
, Command
):
582 klass
= self
.get_command_class(command
)
583 if (hasattr(klass
, 'help_options') and
584 type(klass
.help_options
) is ListType
):
585 parser
.set_option_table(klass
.user_options
+
586 fix_help_options(klass
.help_options
))
588 parser
.set_option_table(klass
.user_options
)
589 parser
.print_help("Options for '%s' command:" % klass
.__name
__)
592 print gen_usage(self
.script_name
)
598 def handle_display_options (self
, option_order
):
599 """If there were any non-global "display-only" options
600 (--help-commands or the metadata display options) on the command
601 line, display the requested info and return true; else return
604 from distutils
.core
import gen_usage
606 # User just wants a list of commands -- we'll print it out and stop
607 # processing now (ie. if they ran "setup --help-commands foo bar",
608 # we ignore "foo bar").
609 if self
.help_commands
:
610 self
.print_commands()
612 print gen_usage(self
.script_name
)
615 # If user supplied any of the "display metadata" options, then
616 # display that metadata in the order in which the user supplied the
618 any_display_options
= 0
619 is_display_option
= {}
620 for option
in self
.display_options
:
621 is_display_option
[option
[0]] = 1
623 for (opt
, val
) in option_order
:
624 if val
and is_display_option
.get(opt
):
625 opt
= translate_longopt(opt
)
626 value
= getattr(self
.metadata
, "get_"+opt
)()
627 if opt
in ['keywords', 'platforms']:
628 print string
.join(value
, ',')
631 any_display_options
= 1
633 return any_display_options
635 # handle_display_options()
637 def print_command_list (self
, commands
, header
, max_length
):
638 """Print a subset of the list of all commands -- used by
645 klass
= self
.cmdclass
.get(cmd
)
647 klass
= self
.get_command_class(cmd
)
649 description
= klass
.description
650 except AttributeError:
651 description
= "(no description available)"
653 print " %-*s %s" % (max_length
, cmd
, description
)
655 # print_command_list ()
658 def print_commands (self
):
659 """Print out a help message listing all available commands with a
660 description of each. The list is divided into "standard commands"
661 (listed in distutils.command.__all__) and "extra commands"
662 (mentioned in self.cmdclass, but not a standard command). The
663 descriptions come from the command class attribute
667 import distutils
.command
668 std_commands
= distutils
.command
.__all
__
670 for cmd
in std_commands
:
674 for cmd
in self
.cmdclass
.keys():
675 if not is_std
.get(cmd
):
676 extra_commands
.append(cmd
)
679 for cmd
in (std_commands
+ extra_commands
):
680 if len(cmd
) > max_length
:
681 max_length
= len(cmd
)
683 self
.print_command_list(std_commands
,
688 self
.print_command_list(extra_commands
,
694 def get_command_list (self
):
695 """Get a list of (command, description) tuples.
696 The list is divided into "standard commands" (listed in
697 distutils.command.__all__) and "extra commands" (mentioned in
698 self.cmdclass, but not a standard command). The descriptions come
699 from the command class attribute 'description'.
701 # Currently this is only used on Mac OS, for the Mac-only GUI
702 # Distutils interface (by Jack Jansen)
704 import distutils
.command
705 std_commands
= distutils
.command
.__all
__
707 for cmd
in std_commands
:
711 for cmd
in self
.cmdclass
.keys():
712 if not is_std
.get(cmd
):
713 extra_commands
.append(cmd
)
716 for cmd
in (std_commands
+ extra_commands
):
717 klass
= self
.cmdclass
.get(cmd
)
719 klass
= self
.get_command_class(cmd
)
721 description
= klass
.description
722 except AttributeError:
723 description
= "(no description available)"
724 rv
.append((cmd
, description
))
727 # -- Command class/object methods ----------------------------------
729 def get_command_class (self
, command
):
730 """Return the class that implements the Distutils command named by
731 'command'. First we check the 'cmdclass' dictionary; if the
732 command is mentioned there, we fetch the class object from the
733 dictionary and return it. Otherwise we load the command module
734 ("distutils.command." + command) and fetch the command class from
735 the module. The loaded class is also stored in 'cmdclass'
736 to speed future calls to 'get_command_class()'.
738 Raises DistutilsModuleError if the expected module could not be
739 found, or if that module does not define the expected class.
741 klass
= self
.cmdclass
.get(command
)
745 module_name
= 'distutils.command.' + command
749 __import__ (module_name
)
750 module
= sys
.modules
[module_name
]
752 raise DistutilsModuleError
, \
753 "invalid command '%s' (no module named '%s')" % \
754 (command
, module_name
)
757 klass
= getattr(module
, klass_name
)
758 except AttributeError:
759 raise DistutilsModuleError
, \
760 "invalid command '%s' (no class '%s' in module '%s')" \
761 % (command
, klass_name
, module_name
)
763 self
.cmdclass
[command
] = klass
766 # get_command_class ()
768 def get_command_obj (self
, command
, create
=1):
769 """Return the command object for 'command'. Normally this object
770 is cached on a previous call to 'get_command_obj()'; if no command
771 object for 'command' is in the cache, then we either create and
772 return it (if 'create' is true) or return None.
774 cmd_obj
= self
.command_obj
.get(command
)
775 if not cmd_obj
and create
:
777 print "Distribution.get_command_obj(): " \
778 "creating '%s' command object" % command
780 klass
= self
.get_command_class(command
)
781 cmd_obj
= self
.command_obj
[command
] = klass(self
)
782 self
.have_run
[command
] = 0
784 # Set any options that were supplied in config files
785 # or on the command line. (NB. support for error
786 # reporting is lame here: any errors aren't reported
787 # until 'finalize_options()' is called, which means
788 # we won't report the source of the error.)
789 options
= self
.command_options
.get(command
)
791 self
._set
_command
_options
(cmd_obj
, options
)
795 def _set_command_options (self
, command_obj
, option_dict
=None):
796 """Set the options for 'command_obj' from 'option_dict'. Basically
797 this means copying elements of a dictionary ('option_dict') to
798 attributes of an instance ('command').
800 'command_obj' must be a Command instance. If 'option_dict' is not
801 supplied, uses the standard option dictionary for this command
802 (from 'self.command_options').
804 command_name
= command_obj
.get_command_name()
805 if option_dict
is None:
806 option_dict
= self
.get_option_dict(command_name
)
808 if DEBUG
: print " setting options for '%s' command:" % command_name
809 for (option
, (source
, value
)) in option_dict
.items():
810 if DEBUG
: print " %s = %s (from %s)" % (option
, value
, source
)
812 bool_opts
= map(translate_longopt
, command_obj
.boolean_options
)
813 except AttributeError:
816 neg_opt
= command_obj
.negative_opt
817 except AttributeError:
821 is_string
= type(value
) is StringType
822 if neg_opt
.has_key(option
) and is_string
:
823 setattr(command_obj
, neg_opt
[option
], not strtobool(value
))
824 elif option
in bool_opts
and is_string
:
825 setattr(command_obj
, option
, strtobool(value
))
826 elif hasattr(command_obj
, option
):
827 setattr(command_obj
, option
, value
)
829 raise DistutilsOptionError
, \
830 ("error in %s: command '%s' has no such option '%s'"
831 % (source
, command_name
, option
))
832 except ValueError, msg
:
833 raise DistutilsOptionError
, msg
835 def reinitialize_command (self
, command
, reinit_subcommands
=0):
836 """Reinitializes a command to the state it was in when first
837 returned by 'get_command_obj()': ie., initialized but not yet
838 finalized. This provides the opportunity to sneak option
839 values in programmatically, overriding or supplementing
840 user-supplied values from the config files and command line.
841 You'll have to re-finalize the command object (by calling
842 'finalize_options()' or 'ensure_finalized()') before using it for
845 'command' should be a command name (string) or command object. If
846 'reinit_subcommands' is true, also reinitializes the command's
847 sub-commands, as declared by the 'sub_commands' class attribute (if
848 it has one). See the "install" command for an example. Only
849 reinitializes the sub-commands that actually matter, ie. those
850 whose test predicates return true.
852 Returns the reinitialized command object.
854 from distutils
.cmd
import Command
855 if not isinstance(command
, Command
):
856 command_name
= command
857 command
= self
.get_command_obj(command_name
)
859 command_name
= command
.get_command_name()
861 if not command
.finalized
:
863 command
.initialize_options()
864 command
.finalized
= 0
865 self
.have_run
[command_name
] = 0
866 self
._set
_command
_options
(command
)
868 if reinit_subcommands
:
869 for sub
in command
.get_sub_commands():
870 self
.reinitialize_command(sub
, reinit_subcommands
)
875 # -- Methods that operate on the Distribution ----------------------
877 def announce (self
, msg
, level
=1):
880 def run_commands (self
):
881 """Run each command that was seen on the setup script command line.
882 Uses the list of commands found and cache of command objects
883 created by 'get_command_obj()'.
885 for cmd
in self
.commands
:
886 self
.run_command(cmd
)
889 # -- Methods that operate on its Commands --------------------------
891 def run_command (self
, command
):
892 """Do whatever it takes to run a command (including nothing at all,
893 if the command has already been run). Specifically: if we have
894 already created and run the command named by 'command', return
895 silently without doing anything. If the command named by 'command'
896 doesn't even have a command object yet, create one. Then invoke
897 'run()' on that command object (or an existing one).
899 # Already been here, done that? then return silently.
900 if self
.have_run
.get(command
):
903 log
.info("running %s", command
)
904 cmd_obj
= self
.get_command_obj(command
)
905 cmd_obj
.ensure_finalized()
907 self
.have_run
[command
] = 1
910 # -- Distribution query methods ------------------------------------
912 def has_pure_modules (self
):
913 return len(self
.packages
or self
.py_modules
or []) > 0
915 def has_ext_modules (self
):
916 return self
.ext_modules
and len(self
.ext_modules
) > 0
918 def has_c_libraries (self
):
919 return self
.libraries
and len(self
.libraries
) > 0
921 def has_modules (self
):
922 return self
.has_pure_modules() or self
.has_ext_modules()
924 def has_headers (self
):
925 return self
.headers
and len(self
.headers
) > 0
927 def has_scripts (self
):
928 return self
.scripts
and len(self
.scripts
) > 0
930 def has_data_files (self
):
931 return self
.data_files
and len(self
.data_files
) > 0
934 return (self
.has_pure_modules() and
935 not self
.has_ext_modules() and
936 not self
.has_c_libraries())
938 # -- Metadata query methods ----------------------------------------
940 # If you're looking for 'get_name()', 'get_version()', and so forth,
941 # they are defined in a sneaky way: the constructor binds self.get_XXX
942 # to self.metadata.get_XXX. The actual code is in the
943 # DistributionMetadata class, below.
948 class DistributionMetadata
:
949 """Dummy class to hold the distribution meta-data: name, version,
950 author, and so forth.
953 _METHOD_BASENAMES
= ("name", "version", "author", "author_email",
954 "maintainer", "maintainer_email", "url",
955 "license", "description", "long_description",
956 "keywords", "platforms", "fullname", "contact",
957 "contact_email", "licence")
963 self
.author_email
= None
964 self
.maintainer
= None
965 self
.maintainer_email
= None
968 self
.description
= None
969 self
.long_description
= None
971 self
.platforms
= None
973 def write_pkg_info (self
, base_dir
):
974 """Write the PKG-INFO file into the release tree.
977 pkg_info
= open( os
.path
.join(base_dir
, 'PKG-INFO'), 'w')
979 pkg_info
.write('Metadata-Version: 1.0\n')
980 pkg_info
.write('Name: %s\n' % self
.get_name() )
981 pkg_info
.write('Version: %s\n' % self
.get_version() )
982 pkg_info
.write('Summary: %s\n' % self
.get_description() )
983 pkg_info
.write('Home-page: %s\n' % self
.get_url() )
984 pkg_info
.write('Author: %s\n' % self
.get_contact() )
985 pkg_info
.write('Author-email: %s\n' % self
.get_contact_email() )
986 pkg_info
.write('License: %s\n' % self
.get_license() )
988 long_desc
= rfc822_escape( self
.get_long_description() )
989 pkg_info
.write('Description: %s\n' % long_desc
)
991 keywords
= string
.join( self
.get_keywords(), ',')
993 pkg_info
.write('Keywords: %s\n' % keywords
)
995 for platform
in self
.get_platforms():
996 pkg_info
.write('Platform: %s\n' % platform
)
1002 # -- Metadata query methods ----------------------------------------
1004 def get_name (self
):
1005 return self
.name
or "UNKNOWN"
1007 def get_version(self
):
1008 return self
.version
or "0.0.0"
1010 def get_fullname (self
):
1011 return "%s-%s" % (self
.get_name(), self
.get_version())
1013 def get_author(self
):
1014 return self
.author
or "UNKNOWN"
1016 def get_author_email(self
):
1017 return self
.author_email
or "UNKNOWN"
1019 def get_maintainer(self
):
1020 return self
.maintainer
or "UNKNOWN"
1022 def get_maintainer_email(self
):
1023 return self
.maintainer_email
or "UNKNOWN"
1025 def get_contact(self
):
1026 return (self
.maintainer
or
1030 def get_contact_email(self
):
1031 return (self
.maintainer_email
or
1032 self
.author_email
or
1036 return self
.url
or "UNKNOWN"
1038 def get_license(self
):
1039 return self
.license
or "UNKNOWN"
1040 get_licence
= get_license
1042 def get_description(self
):
1043 return self
.description
or "UNKNOWN"
1045 def get_long_description(self
):
1046 return self
.long_description
or "UNKNOWN"
1048 def get_keywords(self
):
1049 return self
.keywords
or []
1051 def get_platforms(self
):
1052 return self
.platforms
or ["UNKNOWN"]
1054 # class DistributionMetadata
1057 def fix_help_options (options
):
1058 """Convert a 4-tuple 'help_options' list as found in various command
1059 classes to the 3-tuple form required by FancyGetopt.
1062 for help_tuple
in options
:
1063 new_options
.append(help_tuple
[0:3])
1067 if __name__
== "__main__":
1068 dist
= Distribution()