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