Debian Codegraph @

mesonbuild/mesonmain.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2012-2021 The Meson development team
3
4 from __future__ import annotations
5
6 # Work around some pathlib bugs...
7
8 from . import _pathlib
9 import sys
10 sys.modules['pathlib'] = _pathlib
11
12 # This file is an entry point for all commands, including scripts. Include the
13 # strict minimum python modules for performance reasons.
14 import os.path
15 import platform
16 import importlib
17 import argparse
18 import typing as T
19
20 from .utils.core import MesonException, MesonBugException
21 from . import mlog
22
23 if T.TYPE_CHECKING:
24
25 class MesonMainCMDOptions(T.Protocol):
26
27 command: str
28 run_func: T.Callable[['MesonMainCMDOptions'], int]
29
30
31 def errorhandler(e: Exception, command: str) -> int:
32 import traceback
33 if isinstance(e, MesonException):
34 mlog.exception(e)
35 logfile = mlog.shutdown()
36 if logfile is not None:
37 mlog.log("\nA full log can be found at", mlog.bold(logfile))
38 contents = mlog.ci_fold_file(logfile, f'CI platform detected, click here for {os.path.basename(logfile)} contents.')
39 if contents:
40 print(contents)
41 if os.environ.get('MESON_FORCE_BACKTRACE'):
42 raise e
43 return 1
44 else:
45 # We assume many types of traceback are Meson logic bugs, but most
46 # particularly anything coming from the interpreter during `setup`.
47 # Some things definitely aren't:
48 # - PermissionError is always a problem in the user environment
49 # - runpython doesn't run Meson's own code, even though it is
50 # dispatched by our run()
51 if os.environ.get('MESON_FORCE_BACKTRACE'):
52 raise e
53 traceback.print_exc()
54
55 if command == 'runpython':
56 return 2
57 elif isinstance(e, OSError):
58 mlog.exception(Exception("Unhandled python OSError. This is probably not a Meson bug, "
59 "but an issue with your build environment."))
60 return e.errno or 0
61 else: # Exception
62 msg = 'Unhandled python exception'
63 if all(getattr(e, a, None) is not None for a in ['file', 'lineno', 'colno']):
64 e = MesonBugException(msg, e.file, e.lineno, e.colno) # type: ignore
65 else:
66 e = MesonBugException(msg)
67 mlog.exception(e)
68 return 2
69
70 # Note: when adding arguments, please also add them to the completion
71 # scripts in $MESONSRC/data/shell-completions/
72 class CommandLineParser:
73 def __init__(self) -> None:
74 # only import these once we do full argparse processing
75 from . import mconf, mdist, minit, minstall, mintro, msetup, mtest, rewriter, msubprojects, munstable_coredata, mcompile, mdevenv, mformat
76 from .scripts import env2mfile, reprotest
77 from .wrap import wraptool
78 import shutil
79
80 self.term_width = shutil.get_terminal_size().columns
81 self.formatter = lambda prog: argparse.HelpFormatter(prog, max_help_position=int(self.term_width / 2), width=self.term_width)
82
83 self.commands: T.Dict[str, argparse.ArgumentParser] = {}
84 self.hidden_commands: T.List[str] = []
85 self.parser = argparse.ArgumentParser(prog='meson', formatter_class=self.formatter)
86 self.subparsers = self.parser.add_subparsers(title='Commands', dest='command',
87 description='If no command is specified it defaults to setup command.')
88 self.add_command('setup', msetup.add_arguments, msetup.run,
89 help_msg='Configure the project')
90 self.add_command('configure', mconf.add_arguments, mconf.run,
91 help_msg='Change project options',)
92 self.add_command('dist', mdist.add_arguments, mdist.run,
93 help_msg='Generate release archive',)
94 self.add_command('install', minstall.add_arguments, minstall.run,
95 help_msg='Install the project')
96 self.add_command('introspect', mintro.add_arguments, mintro.run,
97 help_msg='Introspect project')
98 self.add_command('init', minit.add_arguments, minit.run,
99 help_msg='Create a new project')
100 self.add_command('test', mtest.add_arguments, mtest.run,
101 help_msg='Run tests')
102 self.add_command('wrap', wraptool.add_arguments, wraptool.run,
103 help_msg='Wrap tools')
104 self.add_command('subprojects', msubprojects.add_arguments, msubprojects.run,
105 help_msg='Manage subprojects')
106 self.add_command('rewrite', lambda parser: rewriter.add_arguments(parser, self.formatter), rewriter.run,
107 help_msg='Modify the project definition')
108 self.add_command('compile', mcompile.add_arguments, mcompile.run,
109 help_msg='Build the project')
110 self.add_command('devenv', mdevenv.add_arguments, mdevenv.run,
111 help_msg='Run commands in developer environment')
112 self.add_command('env2mfile', env2mfile.add_arguments, env2mfile.run,
113 help_msg='Convert current environment to a cross or native file')
114 self.add_command('reprotest', reprotest.add_arguments, reprotest.run,
115 help_msg='Test if project builds reproducibly')
116 self.add_command('format', mformat.add_arguments, mformat.run, aliases=['fmt'],
117 help_msg='Format meson source file')
118 # Add new commands above this line to list them in help command
119 self.add_command('help', self.add_help_arguments, self.run_help_command,
120 help_msg='Print help of a subcommand')
121
122 # Hidden commands
123 self.add_command('runpython', self.add_runpython_arguments, self.run_runpython_command,
124 help_msg=argparse.SUPPRESS)
125 self.add_command('unstable-coredata', munstable_coredata.add_arguments, munstable_coredata.run,
126 help_msg=argparse.SUPPRESS)
127
128 def add_command(self, name: str, add_arguments_func: T.Callable[[argparse.ArgumentParser], None],
129 run_func: T.Callable[[argparse.Namespace], int], help_msg: str,
130 aliases: T.List[str] | None = None) -> None:
131 aliases = aliases or []
132 # FIXME: Cannot have hidden subparser:
133 # https://bugs.python.org/issue22848
134 if help_msg == argparse.SUPPRESS:
135 p = argparse.ArgumentParser(prog='meson ' + name, formatter_class=self.formatter)
136 self.hidden_commands.append(name)
137 else:
138 p = self.subparsers.add_parser(name, help=help_msg, aliases=aliases, formatter_class=self.formatter)
139 add_arguments_func(p)
140 p.set_defaults(run_func=run_func)
141 for i in [name] + aliases:
142 self.commands[i] = p
143
144 def add_runpython_arguments(self, parser: argparse.ArgumentParser) -> None:
145 parser.add_argument('-c', action='store_true', dest='eval_arg', default=False)
146 parser.add_argument('--version', action='version', version=platform.python_version())
147 parser.add_argument('script_file')
148 parser.add_argument('script_args', nargs=argparse.REMAINDER)
149
150 def run_runpython_command(self, options: argparse.Namespace) -> int:
151 sys.argv[1:] = options.script_args
152 if options.eval_arg:
153 exec(options.script_file)
154 else:
155 import runpy
156 sys.path.insert(0, os.path.dirname(options.script_file))
157 runpy.run_path(options.script_file, run_name='__main__')
158 return 0
159
160 def add_help_arguments(self, parser: argparse.ArgumentParser) -> None:
161 parser.add_argument('command', nargs='?', choices=list(self.commands.keys()))
162
163 def run_help_command(self, options: argparse.Namespace) -> int:
164 if options.command:
165 self.commands[options.command].print_help()
166 else:
167 self.parser.print_help()
168 return 0
169
170 def run(self, args: T.List[str]) -> int:
171 implicit_setup_command_notice = False
172 # If first arg is not a known command, assume user wants to run the setup
173 # command.
174 known_commands = list(self.commands.keys()) + ['-h', '--help']
175 if not args or args[0] not in known_commands:
176 implicit_setup_command_notice = True
177 args = ['setup'] + args
178
179 # Hidden commands have their own parser instead of using the global one
180 if args[0] in self.hidden_commands:
181 command = args[0]
182 parser = self.commands[command]
183 args = args[1:]
184 else:
185 parser = self.parser
186 command = None
187
188 from . import mesonlib
189 args = mesonlib.unwrap_err(mesonlib.expand_arguments(args), 'Failed to expand arguments')
190 options = T.cast('MesonMainCMDOptions', parser.parse_args(args))
191
192 if command is None:
193 command = options.command
194
195 # Bump the version here in order to add a pre-exit warning that we are phasing out
196 # support for old python. If this is already the oldest supported version, then
197 # this can never be true and does nothing.
198 pending_python_deprecation_notice = \
199 command in {'setup', 'compile', 'test', 'install'} and sys.version_info < (3, 10)
200
201 try:
202 return options.run_func(options)
203 except Exception as e:
204 return errorhandler(e, command)
205 finally:
206 if implicit_setup_command_notice:
207 mlog.warning('Running the setup command as `meson [options]` instead of '
208 '`meson setup [options]` is ambiguous and deprecated.', fatal=False)
209 if pending_python_deprecation_notice:
210 mlog.notice(f'You are using Python 3.{sys.version_info.minor} which is EOL. Starting with v1.12.0, '
211 'Meson will require Python 3.10 or newer', fatal=False)
212 mlog.shutdown()
213
214 def run_script_command(script_name: str, script_args: T.List[str]) -> int:
215 # Map script name to module name for those that doesn't match
216 script_map = {'exe': 'meson_exe',
217 'install': 'meson_install',
218 'delsuffix': 'delwithsuffix',
219 'gtkdoc': 'gtkdochelper',
220 'hotdoc': 'hotdochelper',
221 'regencheck': 'regen_checker'}
222 module_name = script_map.get(script_name, script_name)
223
224 try:
225 func = T.cast('T.Callable[[list[str]], int]',
226 importlib.import_module('mesonbuild.scripts.' + module_name).run)
227 except (ModuleNotFoundError, AttributeError) as e:
228 mlog.exception(e)
229 return 1
230
231 try:
232 return func(script_args)
233 except MesonException as e:
234 mlog.error(f'Error in {script_name} helper script:')
235 mlog.exception(e)
236 return 1
237
238 def ensure_stdout_accepts_unicode() -> None:
239 if sys.stdout.encoding and isinstance(sys.stdout.encoding, str) and not sys.stdout.encoding.upper().startswith('UTF-'):
240 sys.stdout.reconfigure(errors='surrogateescape') # type: ignore[union-attr]
241
242 def set_meson_command(mainfile: str) -> None:
243 # Set the meson command that will be used to run scripts and so on
244 from . import mesonlib
245 mesonlib.set_meson_command(mainfile)
246
247 def validate_original_args(args: list[str]) -> None:
248 import mesonbuild.options
249 import itertools
250
251 def has_startswith(coll: list[str], target: str) -> bool:
252 for entry in coll:
253 if entry.startswith(target + '=') or entry == target:
254 return True
255 return False
256
257 for optionkey in itertools.chain(mesonbuild.options.BUILTIN_DIR_OPTIONS, mesonbuild.options.BUILTIN_CORE_OPTIONS):
258 longarg = mesonbuild.options.argparse_name_to_arg(optionkey.name)
259 shortarg = f'-D{optionkey.name}'
260 if has_startswith(args, longarg) and has_startswith(args, shortarg):
261 sys.exit(
262 f'Got argument {optionkey.name} as both {shortarg} and {longarg}. Pick one.')
263
264
265 def run(original_args: T.List[str], mainfile: str) -> int:
266 if os.environ.get('MESON_SHOW_DEPRECATIONS'):
267 # workaround for https://bugs.python.org/issue34624
268 import warnings
269 for typ in [DeprecationWarning, SyntaxWarning, FutureWarning, PendingDeprecationWarning]:
270 warnings.filterwarnings('error', category=typ, module='mesonbuild')
271 warnings.filterwarnings('ignore', message=".*importlib-resources.*")
272
273 if sys.version_info >= (3, 10) and os.environ.get('MESON_RUNNING_IN_PROJECT_TESTS'):
274 # workaround for https://bugs.python.org/issue34624
275 import warnings
276 warnings.filterwarnings('error', category=EncodingWarning, module='mesonbuild')
277 # python 3.11 adds a warning that in 3.15, UTF-8 mode will be default.
278 # This is fantastic news, we'd love that. Less fantastic: this warning is silly,
279 # we *want* these checks to be affected. Plus, the recommended alternative API
280 # would (in addition to warning people when UTF-8 mode removed the problem) also
281 # require using a minimum python version of 3.11 (in which the warning was added)
282 # or add verbose if/else soup.
283 warnings.filterwarnings('ignore', message="UTF-8 Mode affects .*getpreferredencoding", category=EncodingWarning)
284
285 # Meson gets confused if stdout can't output Unicode, if the
286 # locale isn't Unicode, just force stdout to accept it. This tries
287 # to emulate enough of PEP 540 to work elsewhere.
288 ensure_stdout_accepts_unicode()
289
290 # https://github.com/mesonbuild/meson/issues/3653
291 if sys.platform == 'cygwin' and os.environ.get('MSYSTEM', '') not in ['MSYS', '']:
292 mlog.error('This python3 seems to be msys/python on MSYS2 Windows, but you are in a MinGW environment')
293 mlog.error('Please install it via https://packages.msys2.org/base/mingw-w64-python')
294 return 2
295
296 args = original_args[:]
297
298 # Special handling of internal commands called from backends, they don't
299 # need to go through argparse.
300 if len(args) >= 2 and args[0] == '--internal':
301 if args[1] == 'regenerate':
302 set_meson_command(mainfile)
303 from . import msetup
304 try:
305 return msetup.run(['--reconfigure'] + args[2:])
306 except Exception as e:
307 return errorhandler(e, 'setup')
308 else:
309 return run_script_command(args[1], args[2:])
310
311 set_meson_command(mainfile)
312 validate_original_args(args)
313 return CommandLineParser().run(args)
314
315 def main() -> int:
316 # Always resolve the command path so Ninja can find it for regen, tests, etc.
317 if getattr(sys, 'frozen', False):
318 assert os.path.isabs(sys.executable)
319 launcher = sys.executable
320 else:
321 launcher = os.path.abspath(sys.argv[0])
322 return run(sys.argv[1:], launcher)
323
324 if __name__ == '__main__':
325 sys.exit(main())