Debian Codegraph @

mesonbuild/mcompile.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2020 The Meson development team
3
4 from __future__ import annotations
5
6 """Entrypoint script for backend agnostic compile."""
7
8 import os
9 import json
10 import re
11 import sys
12 import shutil
13 import typing as T
14 from collections import defaultdict
15 from pathlib import Path
16
17 from . import mlog
18 from . import mesonlib
19 from .options import OptionKey
20 from .mesonlib import MesonException, RealPathAction, join_args, listify_array_value, setup_vsenv
21 from mesonbuild.tooldetect import detect_ninja
22 from mesonbuild import build
23
24 if T.TYPE_CHECKING:
25 import argparse
26
27 def array_arg(value: str) -> T.List[str]:
28 return listify_array_value(value)
29
30 def validate_builddir(builddir: Path) -> None:
31 if not (builddir / 'meson-private' / 'coredata.dat').is_file():
32 raise MesonException(f'Current directory is not a meson build directory: `{builddir}`.\n'
33 'Please specify a valid build dir or change the working directory to it.\n'
34 'It is also possible that the build directory was generated with an old\n'
35 'meson version. Please regenerate it in this case.')
36
37 def parse_introspect_data(builddir: Path) -> T.Dict[str, T.List[dict]]:
38 """
39 Converts a List of name-to-dict to a dict of name-to-dicts (since names are not unique)
40 """
41 path_to_intro = builddir / 'meson-info' / 'intro-targets.json'
42 if not path_to_intro.exists():
43 raise MesonException(f'`{path_to_intro.name}` is missing! Directory is not configured yet?')
44 with path_to_intro.open(encoding='utf-8') as f:
45 schema = json.load(f)
46
47 parsed_data: T.Dict[str, T.List[dict]] = defaultdict(list)
48 for target in schema:
49 parsed_data[target['name']] += [target]
50 return parsed_data
51
52 class ParsedTargetName:
53 full_name = ''
54 base_name = ''
55 name = ''
56 type = ''
57 path = ''
58 suffix = ''
59
60 def __init__(self, target: str):
61 self.full_name = target
62 split = target.rsplit(':', 1)
63 if len(split) > 1:
64 self.type = split[1]
65 if not self._is_valid_type(self.type):
66 raise MesonException(f'Can\'t invoke target `{target}`: unknown target type: `{self.type}`')
67
68 split = split[0].rsplit('/', 1)
69 if len(split) > 1:
70 self.path = split[0]
71 self.name = split[1]
72 else:
73 self.name = split[0]
74
75 split = self.name.rsplit('.', 1)
76 if len(split) > 1:
77 self.base_name = split[0]
78 self.suffix = split[1]
79 else:
80 self.base_name = split[0]
81
82 @staticmethod
83 def _is_valid_type(type: str) -> bool:
84 # Amend docs in Commands.md when editing this list
85 allowed_types = {
86 'executable',
87 'static_library',
88 'shared_library',
89 'shared_module',
90 'custom',
91 'alias',
92 'run',
93 'jar',
94 }
95 return type in allowed_types
96
97 def get_target_from_intro_data(target: ParsedTargetName, builddir: Path, introspect_data: T.Dict[str, T.Any]) -> T.Dict[str, T.Any]:
98 if target.name not in introspect_data and target.base_name not in introspect_data:
99 raise MesonException(f'Can\'t invoke target `{target.full_name}`: target not found')
100
101 intro_targets = introspect_data[target.name]
102 # if target.name doesn't find anything, try just the base name
103 if not intro_targets:
104 intro_targets = introspect_data[target.base_name]
105 found_targets: T.List[T.Dict[str, T.Any]] = []
106
107 resolved_bdir = builddir.resolve()
108
109 if not target.type and not target.path and not target.suffix:
110 found_targets = intro_targets
111 else:
112 for intro_target in intro_targets:
113 # Parse out the name from the id if needed
114 intro_target_name = intro_target['name']
115 split = intro_target['id'].rsplit('@', 1)
116 if len(split) > 1:
117 split = split[0].split('@@', 1)
118 if len(split) > 1:
119 intro_target_name = split[1]
120 else:
121 intro_target_name = split[0]
122 if ((target.type and target.type != intro_target['type'].replace(' ', '_')) or
123 (target.name != intro_target_name) or
124 (target.path and intro_target['filename'] != 'no_name' and
125 Path(target.path) != Path(intro_target['filename'][0]).relative_to(resolved_bdir).parent)):
126 continue
127 found_targets += [intro_target]
128
129 if not found_targets:
130 raise MesonException(f'Can\'t invoke target `{target.full_name}`: target not found')
131 elif len(found_targets) > 1:
132 suggestions: T.List[str] = []
133 for i in found_targets:
134 i_name = i['name']
135 split = i['id'].rsplit('@', 1)
136 if len(split) > 1:
137 split = split[0].split('@@', 1)
138 if len(split) > 1:
139 i_name = split[1]
140 else:
141 i_name = split[0]
142 p = Path(i['filename'][0]).relative_to(resolved_bdir).parent / i_name
143 t = i['type'].replace(' ', '_')
144 suggestions.append(f'- ./{p}:{t}')
145 suggestions_str = '\n'.join(suggestions)
146 raise MesonException(f'Can\'t invoke target `{target.full_name}`: ambiguous name.'
147 f' Add target type and/or path:\n{suggestions_str}')
148
149 return found_targets[0]
150
151 def generate_target_names_ninja(target: ParsedTargetName, builddir: Path, introspect_data: dict) -> T.List[str]:
152 intro_target = get_target_from_intro_data(target, builddir, introspect_data)
153
154 if intro_target['type'] in {'alias', 'run'}:
155 return [target.name]
156 else:
157 return [str(Path(out_file).relative_to(builddir.resolve())) for out_file in intro_target['filename']]
158
159 def get_parsed_args_ninja(options: 'argparse.Namespace', builddir: Path) -> T.Tuple[T.List[str], T.Optional[T.Dict[str, str]]]:
160 runner = detect_ninja()
161 if runner is None:
162 raise MesonException('Cannot find ninja.')
163
164 cmd = runner
165 if not builddir.samefile('.'):
166 cmd.extend(['-C', builddir.as_posix()])
167
168 # If the value is set to < 1 then don't set anything, which let's
169 # ninja/samu decide what to do.
170 if options.jobs > 0:
171 cmd.extend(['-j', str(options.jobs)])
172 if options.load_average > 0:
173 cmd.extend(['-l', str(options.load_average)])
174
175 if options.verbose:
176 cmd.append('-v')
177
178 cmd += options.ninja_args
179
180 # operands must be processed after options/option-arguments
181 if options.targets:
182 intro_data = parse_introspect_data(builddir)
183 for t in options.targets:
184 cmd.extend(generate_target_names_ninja(ParsedTargetName(t), builddir, intro_data))
185 if options.clean:
186 cmd.append('clean')
187
188 return cmd, None
189
190 def generate_target_name_vs(target: ParsedTargetName, builddir: Path, introspect_data: dict) -> str:
191 intro_target = get_target_from_intro_data(target, builddir, introspect_data)
192
193 assert intro_target['type'] not in {'alias', 'run'}, 'Should not reach here: `run` targets must be handle above'
194
195 # Normalize project name
196 # Source: https://docs.microsoft.com/en-us/visualstudio/msbuild/how-to-build-specific-targets-in-solutions-by-using-msbuild-exe
197 target_name = re.sub(r"[\%\$\@\;\.\(\)']", '_', intro_target['id'])
198 rel_path = Path(intro_target['filename'][0]).relative_to(builddir.resolve()).parent
199 if rel_path != Path('.'):
200 target_name = str(rel_path / target_name)
201 return target_name
202
203 def get_parsed_args_vs(options: 'argparse.Namespace', builddir: Path) -> T.Tuple[T.List[str], T.Optional[T.Dict[str, str]]]:
204 slns = list(builddir.glob('*.sln'))
205 assert len(slns) == 1, 'More than one solution in a project?'
206 sln = slns[0]
207
208 cmd = ['msbuild']
209
210 if options.targets:
211 intro_data = parse_introspect_data(builddir)
212 has_run_target = any(
213 get_target_from_intro_data(ParsedTargetName(t), builddir, intro_data)['type'] in {'alias', 'run'}
214 for t in options.targets)
215
216 if has_run_target:
217 # `run` target can't be used the same way as other targets on `vs` backend.
218 # They are defined as disabled projects, which can't be invoked as `.sln`
219 # target and have to be invoked directly as project instead.
220 # Issue: https://github.com/microsoft/msbuild/issues/4772
221
222 if len(options.targets) > 1:
223 raise MesonException('Only one target may be specified when `run` target type is used on this backend.')
224 intro_target = get_target_from_intro_data(ParsedTargetName(options.targets[0]), builddir, intro_data)
225 proj_dir = Path(intro_target['filename'][0]).parent
226 proj = proj_dir/'{}.vcxproj'.format(intro_target['id'])
227 cmd += [str(proj.resolve())]
228 else:
229 cmd += [str(sln.resolve())]
230 cmd.extend(['-target:{}'.format(generate_target_name_vs(ParsedTargetName(t), builddir, intro_data)) for t in options.targets])
231 else:
232 cmd += [str(sln.resolve())]
233
234 if options.clean:
235 cmd.extend(['-target:Clean'])
236
237 # In msbuild `-maxCpuCount` with no number means "detect cpus", the default is `-maxCpuCount:1`
238 if options.jobs > 0:
239 cmd.append(f'-maxCpuCount:{options.jobs}')
240 else:
241 cmd.append('-maxCpuCount')
242
243 if options.load_average:
244 mlog.warning('Msbuild does not have a load-average switch, ignoring.')
245
246 if not options.verbose:
247 cmd.append('-verbosity:minimal')
248
249 cmd += options.vs_args
250
251 # Remove platform from env if set so that msbuild does not
252 # pick x86 platform when solution platform is Win32
253 env = os.environ.copy()
254 env.pop('PLATFORM', None)
255
256 return cmd, env
257
258 def get_parsed_args_xcode(options: 'argparse.Namespace', builddir: Path) -> T.Tuple[T.List[str], T.Optional[T.Dict[str, str]]]:
259 runner = 'xcodebuild'
260 if not shutil.which(runner):
261 raise MesonException('Cannot find xcodebuild, did you install XCode?')
262
263 # No argument to switch directory
264 os.chdir(str(builddir))
265
266 cmd = [runner, '-parallelizeTargets']
267
268 if options.targets:
269 for t in options.targets:
270 cmd += ['-target', t]
271
272 if options.clean:
273 if options.targets:
274 cmd += ['clean']
275 else:
276 cmd += ['-alltargets', 'clean']
277 # Otherwise xcodebuild tries to delete the builddir and fails
278 cmd += ['-UseNewBuildSystem=FALSE']
279
280 if options.jobs > 0:
281 cmd.extend(['-jobs', str(options.jobs)])
282
283 if options.load_average > 0:
284 mlog.warning('xcodebuild does not have a load-average switch, ignoring')
285
286 if options.verbose:
287 # xcodebuild is already quite verbose, and -quiet doesn't print any
288 # status messages
289 pass
290
291 cmd += options.xcode_args
292 return cmd, None
293
294 # Note: when adding arguments, please also add them to the completion
295 # scripts in $MESONSRC/data/shell-completions/
296 def add_arguments(parser: 'argparse.ArgumentParser') -> None:
297 """Add compile specific arguments."""
298 parser.add_argument(
299 'targets',
300 metavar='TARGET',
301 nargs='*',
302 default=None,
303 help='Targets to build. Target has the following format: [PATH_TO_TARGET/]TARGET_NAME.TARGET_SUFFIX[:TARGET_TYPE].')
304 parser.add_argument(
305 '--clean',
306 action='store_true',
307 help='Clean the build directory.'
308 )
309 parser.add_argument('-C', dest='wd', action=RealPathAction,
310 help='directory to cd into before running')
311
312 parser.add_argument(
313 '-j', '--jobs',
314 action='store',
315 default=0,
316 type=int,
317 help='The number of worker jobs to run (if supported). If the value is less than 1 the build program will guess.'
318 )
319 parser.add_argument(
320 '-l', '--load-average',
321 action='store',
322 default=0,
323 type=float,
324 help='The system load average to try to maintain (if supported).'
325 )
326 parser.add_argument(
327 '-v', '--verbose',
328 action='store_true',
329 help='Show more verbose output.'
330 )
331 parser.add_argument(
332 '--ninja-args',
333 type=array_arg,
334 default=[],
335 help='Arguments to pass to `ninja` (applied only on `ninja` backend).'
336 )
337 parser.add_argument(
338 '--vs-args',
339 type=array_arg,
340 default=[],
341 help='Arguments to pass to `msbuild` (applied only on `vs` backend).'
342 )
343 parser.add_argument(
344 '--xcode-args',
345 type=array_arg,
346 default=[],
347 help='Arguments to pass to `xcodebuild` (applied only on `xcode` backend).'
348 )
349
350 def run(options: 'argparse.Namespace') -> int:
351 bdir = Path(options.wd)
352 validate_builddir(bdir)
353 if options.targets and options.clean:
354 raise MesonException('`TARGET` and `--clean` can\'t be used simultaneously')
355
356 b = build.load(options.wd)
357 cdata = b.environment.coredata
358 need_vsenv = T.cast('bool', cdata.optstore.get_value_for(OptionKey('vsenv')))
359 if setup_vsenv(need_vsenv):
360 mlog.log(mlog.green('INFO:'), 'automatically activated MSVC compiler environment')
361
362 cmd: T.List[str] = []
363 env: T.Optional[T.Dict[str, str]] = None
364
365 backend = cdata.optstore.get_value_for(OptionKey('backend'))
366 assert isinstance(backend, str)
367 mlog.log(mlog.green('INFO:'), 'autodetecting backend as', backend)
368 if backend == 'ninja':
369 cmd, env = get_parsed_args_ninja(options, bdir)
370 elif backend.startswith('vs'):
371 cmd, env = get_parsed_args_vs(options, bdir)
372 elif backend == 'xcode':
373 cmd, env = get_parsed_args_xcode(options, bdir)
374 else:
375 raise MesonException(
376 f'Backend `{backend}` is not yet supported by `compile`. Use generated project files directly instead.')
377
378 mlog.log(mlog.green('INFO:'), 'calculating backend command to run:', join_args(cmd))
379 p, *_ = mesonlib.Popen_safe(cmd, stdout=sys.stdout.buffer, stderr=sys.stderr.buffer, env=env)
380
381 return p.returncode