/Lib/distutils/core.py

http://unladen-swallow.googlecode.com/ · Python · 243 lines · 221 code · 10 blank · 12 comment · 14 complexity · 73decdbe7d8eb284d090407a1a9b5ce1 MD5 · raw file

  1. """distutils.core
  2. The only module that needs to be imported to use the Distutils; provides
  3. the 'setup' function (which is to be called from the setup script). Also
  4. indirectly provides the Distribution and Command classes, although they are
  5. really defined in distutils.dist and distutils.cmd.
  6. """
  7. # This module should be kept compatible with Python 2.1.
  8. __revision__ = "$Id: core.py 65806 2008-08-18 11:13:45Z marc-andre.lemburg $"
  9. import sys, os
  10. from types import *
  11. from distutils.debug import DEBUG
  12. from distutils.errors import *
  13. from distutils.util import grok_environment_error
  14. # Mainly import these so setup scripts can "from distutils.core import" them.
  15. from distutils.dist import Distribution
  16. from distutils.cmd import Command
  17. from distutils.config import PyPIRCCommand
  18. from distutils.extension import Extension
  19. # This is a barebones help message generated displayed when the user
  20. # runs the setup script with no arguments at all. More useful help
  21. # is generated with various --help options: global help, list commands,
  22. # and per-command help.
  23. USAGE = """\
  24. usage: %(script)s [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
  25. or: %(script)s --help [cmd1 cmd2 ...]
  26. or: %(script)s --help-commands
  27. or: %(script)s cmd --help
  28. """
  29. def gen_usage (script_name):
  30. script = os.path.basename(script_name)
  31. return USAGE % vars()
  32. # Some mild magic to control the behaviour of 'setup()' from 'run_setup()'.
  33. _setup_stop_after = None
  34. _setup_distribution = None
  35. # Legal keyword arguments for the setup() function
  36. setup_keywords = ('distclass', 'script_name', 'script_args', 'options',
  37. 'name', 'version', 'author', 'author_email',
  38. 'maintainer', 'maintainer_email', 'url', 'license',
  39. 'description', 'long_description', 'keywords',
  40. 'platforms', 'classifiers', 'download_url',
  41. 'requires', 'provides', 'obsoletes',
  42. )
  43. # Legal keyword arguments for the Extension constructor
  44. extension_keywords = ('name', 'sources', 'include_dirs',
  45. 'define_macros', 'undef_macros',
  46. 'library_dirs', 'libraries', 'runtime_library_dirs',
  47. 'extra_objects', 'extra_compile_args', 'extra_link_args',
  48. 'swig_opts', 'export_symbols', 'depends', 'language')
  49. def setup (**attrs):
  50. """The gateway to the Distutils: do everything your setup script needs
  51. to do, in a highly flexible and user-driven way. Briefly: create a
  52. Distribution instance; find and parse config files; parse the command
  53. line; run each Distutils command found there, customized by the options
  54. supplied to 'setup()' (as keyword arguments), in config files, and on
  55. the command line.
  56. The Distribution instance might be an instance of a class supplied via
  57. the 'distclass' keyword argument to 'setup'; if no such class is
  58. supplied, then the Distribution class (in dist.py) is instantiated.
  59. All other arguments to 'setup' (except for 'cmdclass') are used to set
  60. attributes of the Distribution instance.
  61. The 'cmdclass' argument, if supplied, is a dictionary mapping command
  62. names to command classes. Each command encountered on the command line
  63. will be turned into a command class, which is in turn instantiated; any
  64. class found in 'cmdclass' is used in place of the default, which is
  65. (for command 'foo_bar') class 'foo_bar' in module
  66. 'distutils.command.foo_bar'. The command class must provide a
  67. 'user_options' attribute which is a list of option specifiers for
  68. 'distutils.fancy_getopt'. Any command-line options between the current
  69. and the next command are used to set attributes of the current command
  70. object.
  71. When the entire command-line has been successfully parsed, calls the
  72. 'run()' method on each command object in turn. This method will be
  73. driven entirely by the Distribution object (which each command object
  74. has a reference to, thanks to its constructor), and the
  75. command-specific options that became attributes of each command
  76. object.
  77. """
  78. global _setup_stop_after, _setup_distribution
  79. # Determine the distribution class -- either caller-supplied or
  80. # our Distribution (see below).
  81. klass = attrs.get('distclass')
  82. if klass:
  83. del attrs['distclass']
  84. else:
  85. klass = Distribution
  86. if 'script_name' not in attrs:
  87. attrs['script_name'] = os.path.basename(sys.argv[0])
  88. if 'script_args' not in attrs:
  89. attrs['script_args'] = sys.argv[1:]
  90. # Create the Distribution instance, using the remaining arguments
  91. # (ie. everything except distclass) to initialize it
  92. try:
  93. _setup_distribution = dist = klass(attrs)
  94. except DistutilsSetupError, msg:
  95. if 'name' in attrs:
  96. raise SystemExit, "error in %s setup command: %s" % \
  97. (attrs['name'], msg)
  98. else:
  99. raise SystemExit, "error in setup command: %s" % msg
  100. if _setup_stop_after == "init":
  101. return dist
  102. # Find and parse the config file(s): they will override options from
  103. # the setup script, but be overridden by the command line.
  104. dist.parse_config_files()
  105. if DEBUG:
  106. print "options (after parsing config files):"
  107. dist.dump_option_dicts()
  108. if _setup_stop_after == "config":
  109. return dist
  110. # Parse the command line; any command-line errors are the end user's
  111. # fault, so turn them into SystemExit to suppress tracebacks.
  112. try:
  113. ok = dist.parse_command_line()
  114. except DistutilsArgError, msg:
  115. raise SystemExit, gen_usage(dist.script_name) + "\nerror: %s" % msg
  116. if DEBUG:
  117. print "options (after parsing command line):"
  118. dist.dump_option_dicts()
  119. if _setup_stop_after == "commandline":
  120. return dist
  121. # And finally, run all the commands found on the command line.
  122. if ok:
  123. try:
  124. dist.run_commands()
  125. except KeyboardInterrupt:
  126. raise SystemExit, "interrupted"
  127. except (IOError, os.error), exc:
  128. error = grok_environment_error(exc)
  129. if DEBUG:
  130. sys.stderr.write(error + "\n")
  131. raise
  132. else:
  133. raise SystemExit, error
  134. except (DistutilsError,
  135. CCompilerError), msg:
  136. if DEBUG:
  137. raise
  138. else:
  139. raise SystemExit, "error: " + str(msg)
  140. return dist
  141. # setup ()
  142. def run_setup (script_name, script_args=None, stop_after="run"):
  143. """Run a setup script in a somewhat controlled environment, and
  144. return the Distribution instance that drives things. This is useful
  145. if you need to find out the distribution meta-data (passed as
  146. keyword args from 'script' to 'setup()', or the contents of the
  147. config files or command-line.
  148. 'script_name' is a file that will be run with 'execfile()';
  149. 'sys.argv[0]' will be replaced with 'script' for the duration of the
  150. call. 'script_args' is a list of strings; if supplied,
  151. 'sys.argv[1:]' will be replaced by 'script_args' for the duration of
  152. the call.
  153. 'stop_after' tells 'setup()' when to stop processing; possible
  154. values:
  155. init
  156. stop after the Distribution instance has been created and
  157. populated with the keyword arguments to 'setup()'
  158. config
  159. stop after config files have been parsed (and their data
  160. stored in the Distribution instance)
  161. commandline
  162. stop after the command-line ('sys.argv[1:]' or 'script_args')
  163. have been parsed (and the data stored in the Distribution)
  164. run [default]
  165. stop after all commands have been run (the same as if 'setup()'
  166. had been called in the usual way
  167. Returns the Distribution instance, which provides all information
  168. used to drive the Distutils.
  169. """
  170. if stop_after not in ('init', 'config', 'commandline', 'run'):
  171. raise ValueError, "invalid value for 'stop_after': %r" % (stop_after,)
  172. global _setup_stop_after, _setup_distribution
  173. _setup_stop_after = stop_after
  174. save_argv = sys.argv
  175. g = {'__file__': script_name}
  176. l = {}
  177. try:
  178. try:
  179. sys.argv[0] = script_name
  180. if script_args is not None:
  181. sys.argv[1:] = script_args
  182. exec open(script_name, 'r').read() in g, l
  183. finally:
  184. sys.argv = save_argv
  185. _setup_stop_after = None
  186. except SystemExit:
  187. # Hmm, should we do something if exiting with a non-zero code
  188. # (ie. error)?
  189. pass
  190. except:
  191. raise
  192. if _setup_distribution is None:
  193. raise RuntimeError, \
  194. ("'distutils.core.setup()' was never called -- "
  195. "perhaps '%s' is not a Distutils setup script?") % \
  196. script_name
  197. # I wonder if the setup script's namespace -- g and l -- would be of
  198. # any interest to callers?
  199. #print "_setup_distribution:", _setup_distribution
  200. return _setup_distribution
  201. # run_setup ()