core.py 9.1 KB

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