core.py 9.2 KB

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