core.py 8.7 KB

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