Debian Codegraph @

third_party/python/build/build/__main__.py

raw
1 # SPDX-License-Identifier: MIT
2
3 from __future__ import annotations
4
5 import argparse
6 import contextlib
7 import contextvars
8 import os
9 import platform
10 import shutil
11 import subprocess
12 import sys
13 import tempfile
14 import textwrap
15 import traceback
16 import warnings
17
18 from collections.abc import Iterator, Sequence
19 from functools import partial
20 from typing import NoReturn, TextIO
21
22 import build
23
24 from . import ProjectBuilder, _ctx
25 from . import env as _env
26 from ._exceptions import BuildBackendException, BuildException, FailedProcessError
27 from ._types import ConfigSettings, Distribution, StrPath
28 from .env import DefaultIsolatedEnv
29
30
31 _COLORS = {
32 'red': '\33[91m',
33 'green': '\33[92m',
34 'yellow': '\33[93m',
35 'bold': '\33[1m',
36 'dim': '\33[2m',
37 'underline': '\33[4m',
38 'reset': '\33[0m',
39 }
40 _NO_COLORS = {color: '' for color in _COLORS}
41
42
43 _styles = contextvars.ContextVar('_styles', default=_COLORS)
44
45
46 def _init_colors() -> None:
47 if 'NO_COLOR' in os.environ:
48 if 'FORCE_COLOR' in os.environ:
49 warnings.warn('Both NO_COLOR and FORCE_COLOR environment variables are set, disabling color', stacklevel=2)
50 _styles.set(_NO_COLORS)
51 elif 'FORCE_COLOR' in os.environ or sys.stdout.isatty():
52 return
53 _styles.set(_NO_COLORS)
54
55
56 def _cprint(fmt: str = '', msg: str = '', file: TextIO | None = None) -> None:
57 print(fmt.format(msg, **_styles.get()), file=file, flush=True)
58
59
60 def _showwarning(
61 message: Warning | str,
62 category: type[Warning],
63 filename: str,
64 lineno: int,
65 file: TextIO | None = None,
66 line: str | None = None,
67 ) -> None: # pragma: no cover
68 _cprint('{yellow}WARNING{reset} {}', str(message))
69
70
71 _max_terminal_width = shutil.get_terminal_size().columns - 2
72 if _max_terminal_width <= 0:
73 _max_terminal_width = 78
74
75
76 _fill = partial(textwrap.fill, subsequent_indent=' ', width=_max_terminal_width)
77
78
79 def _log(message: str, *, origin: tuple[str, ...] | None = None) -> None:
80 if origin is None:
81 (first, *rest) = message.splitlines()
82 _cprint('{bold}{}{reset}', _fill(first, initial_indent='* '))
83 for line in rest:
84 print(_fill(line, initial_indent=' '))
85
86 elif origin[0] == 'subprocess':
87 initial_indent = '> ' if origin[1] == 'cmd' else '< '
88 file = sys.stderr if origin[1] == 'stderr' else None
89 for line in message.splitlines():
90 _cprint('{dim}{}{reset}', _fill(line, initial_indent=initial_indent), file=file)
91
92
93 def _setup_cli(*, verbosity: int) -> None:
94 warnings.showwarning = _showwarning
95
96 if platform.system() == 'Windows':
97 try:
98 import colorama
99
100 colorama.init()
101 except ModuleNotFoundError:
102 pass
103
104 _init_colors()
105
106 _ctx.LOGGER.set(_log)
107 _ctx.VERBOSITY.set(verbosity)
108
109
110 def _error(msg: str, code: int = 1) -> NoReturn: # pragma: no cover
111 """
112 Print an error message and exit. Will color the output when writing to a TTY.
113
114 :param msg: Error message
115 :param code: Error code
116 """
117 _cprint('{red}ERROR{reset} {}', msg)
118 raise SystemExit(code)
119
120
121 def _format_dep_chain(dep_chain: Sequence[str]) -> str:
122 return ' -> '.join(dep.partition(';')[0].strip() for dep in dep_chain)
123
124
125 def _build_in_isolated_env(
126 srcdir: StrPath,
127 outdir: StrPath,
128 distribution: Distribution,
129 config_settings: ConfigSettings | None,
130 installer: _env.Installer,
131 ) -> str:
132 with DefaultIsolatedEnv(installer=installer) as env:
133 builder = ProjectBuilder.from_isolated_env(env, srcdir)
134 # first install the build dependencies
135 env.install(builder.build_system_requires)
136 # then get the extra required dependencies from the backend (which was installed in the call above :P)
137 env.install(builder.get_requires_for_build(distribution, config_settings or {}))
138 return builder.build(distribution, outdir, config_settings or {})
139
140
141 def _build_in_current_env(
142 srcdir: StrPath,
143 outdir: StrPath,
144 distribution: Distribution,
145 config_settings: ConfigSettings | None,
146 skip_dependency_check: bool = False,
147 ) -> str:
148 builder = ProjectBuilder(srcdir)
149
150 if not skip_dependency_check:
151 missing = builder.check_dependencies(distribution, config_settings or {})
152 if missing:
153 dependencies = ''.join('\n\t' + dep for deps in missing for dep in (deps[0], _format_dep_chain(deps[1:])) if dep)
154 _cprint()
155 _error(f'Missing dependencies:{dependencies}')
156
157 return builder.build(distribution, outdir, config_settings or {})
158
159
160 def _build(
161 isolation: bool,
162 srcdir: StrPath,
163 outdir: StrPath,
164 distribution: Distribution,
165 config_settings: ConfigSettings | None,
166 skip_dependency_check: bool,
167 installer: _env.Installer,
168 ) -> str:
169 if isolation:
170 return _build_in_isolated_env(srcdir, outdir, distribution, config_settings, installer)
171 else:
172 return _build_in_current_env(srcdir, outdir, distribution, config_settings, skip_dependency_check)
173
174
175 @contextlib.contextmanager
176 def _handle_build_error() -> Iterator[None]:
177 try:
178 yield
179 except (BuildException, FailedProcessError) as e:
180 _error(str(e))
181 except BuildBackendException as e:
182 if isinstance(e.exception, subprocess.CalledProcessError):
183 _cprint()
184 _error(str(e))
185
186 if e.exc_info:
187 tb_lines = traceback.format_exception(
188 e.exc_info[0],
189 e.exc_info[1],
190 e.exc_info[2],
191 limit=-1,
192 )
193 tb = ''.join(tb_lines)
194 else:
195 tb = traceback.format_exc(-1)
196 _cprint('\n{dim}{}{reset}\n', tb.strip('\n'))
197 _error(str(e))
198 except Exception as e: # pragma: no cover
199 tb = traceback.format_exc().strip('\n')
200 _cprint('\n{dim}{}{reset}\n', tb)
201 _error(str(e))
202
203
204 def _natural_language_list(elements: Sequence[str]) -> str:
205 if len(elements) == 0:
206 msg = 'no elements'
207 raise IndexError(msg)
208 elif len(elements) == 1:
209 return elements[0]
210 else:
211 return '{} and {}'.format(
212 ', '.join(elements[:-1]),
213 elements[-1],
214 )
215
216
217 def build_package(
218 srcdir: StrPath,
219 outdir: StrPath,
220 distributions: Sequence[Distribution],
221 config_settings: ConfigSettings | None = None,
222 isolation: bool = True,
223 skip_dependency_check: bool = False,
224 installer: _env.Installer = 'pip',
225 ) -> Sequence[str]:
226 """
227 Run the build process.
228
229 :param srcdir: Source directory
230 :param outdir: Output directory
231 :param distribution: Distribution to build (sdist or wheel)
232 :param config_settings: Configuration settings to be passed to the backend
233 :param isolation: Isolate the build in a separate environment
234 :param skip_dependency_check: Do not perform the dependency check
235 """
236 built: list[str] = []
237 for distribution in distributions:
238 out = _build(isolation, srcdir, outdir, distribution, config_settings, skip_dependency_check, installer)
239 built.append(os.path.basename(out))
240 return built
241
242
243 def build_package_via_sdist(
244 srcdir: StrPath,
245 outdir: StrPath,
246 distributions: Sequence[Distribution],
247 config_settings: ConfigSettings | None = None,
248 isolation: bool = True,
249 skip_dependency_check: bool = False,
250 installer: _env.Installer = 'pip',
251 ) -> Sequence[str]:
252 """
253 Build a sdist and then the specified distributions from it.
254
255 :param srcdir: Source directory
256 :param outdir: Output directory
257 :param distribution: Distribution to build (only wheel)
258 :param config_settings: Configuration settings to be passed to the backend
259 :param isolation: Isolate the build in a separate environment
260 :param skip_dependency_check: Do not perform the dependency check
261 """
262 from ._compat import tarfile
263
264 if 'sdist' in distributions:
265 msg = 'Only binary distributions are allowed but sdist was specified'
266 raise ValueError(msg)
267
268 sdist = _build(isolation, srcdir, outdir, 'sdist', config_settings, skip_dependency_check, installer)
269
270 sdist_name = os.path.basename(sdist)
271 sdist_out = tempfile.mkdtemp(prefix='build-via-sdist-')
272 built: list[str] = []
273 if distributions:
274 # extract sdist
275 with tarfile.TarFile.open(sdist) as t:
276 t.extractall(sdist_out)
277 try:
278 _ctx.log(f'Building {_natural_language_list(distributions)} from sdist')
279 srcdir = os.path.join(sdist_out, sdist_name[: -len('.tar.gz')])
280 for distribution in distributions:
281 out = _build(isolation, srcdir, outdir, distribution, config_settings, skip_dependency_check, installer)
282 built.append(os.path.basename(out))
283 finally:
284 shutil.rmtree(sdist_out, ignore_errors=True)
285 return [sdist_name, *built]
286
287
288 def main_parser() -> argparse.ArgumentParser:
289 """
290 Construct the main parser.
291 """
292 parser = argparse.ArgumentParser(
293 description=textwrap.indent(
294 textwrap.dedent(
295 """
296 A simple, correct Python build frontend.
297
298 By default, a source distribution (sdist) is built from {srcdir}
299 and a binary distribution (wheel) is built from the sdist.
300 This is recommended as it will ensure the sdist can be used
301 to build wheels.
302
303 Pass -s/--sdist and/or -w/--wheel to build a specific distribution.
304 If you do this, the default behavior will be disabled, and all
305 artifacts will be built from {srcdir} (even if you combine
306 -w/--wheel with -s/--sdist, the wheel will be built from {srcdir}).
307 """
308 ).strip(),
309 ' ',
310 ),
311 # Prevent argparse from taking up the entire width of the terminal window
312 # which impedes readability.
313 formatter_class=partial(argparse.RawDescriptionHelpFormatter, width=min(_max_terminal_width, 127)),
314 )
315 parser.add_argument(
316 'srcdir',
317 type=str,
318 nargs='?',
319 default=os.getcwd(),
320 help='source directory (defaults to current directory)',
321 )
322 parser.add_argument(
323 '--version',
324 '-V',
325 action='version',
326 version=f"build {build.__version__} ({','.join(build.__path__)})",
327 )
328 parser.add_argument(
329 '--verbose',
330 '-v',
331 dest='verbosity',
332 action='count',
333 default=0,
334 help='increase verbosity',
335 )
336 parser.add_argument(
337 '--sdist',
338 '-s',
339 dest='distributions',
340 action='append_const',
341 const='sdist',
342 help='build a source distribution (disables the default behavior)',
343 )
344 parser.add_argument(
345 '--wheel',
346 '-w',
347 dest='distributions',
348 action='append_const',
349 const='wheel',
350 help='build a wheel (disables the default behavior)',
351 )
352 parser.add_argument(
353 '--outdir',
354 '-o',
355 type=str,
356 help=f'output directory (defaults to {{srcdir}}{os.sep}dist)',
357 metavar='PATH',
358 )
359 parser.add_argument(
360 '--skip-dependency-check',
361 '-x',
362 action='store_true',
363 help='do not check that build dependencies are installed',
364 )
365 env_group = parser.add_mutually_exclusive_group()
366 env_group.add_argument(
367 '--no-isolation',
368 '-n',
369 action='store_true',
370 help='disable building the project in an isolated virtual environment. '
371 'Build dependencies must be installed separately when this option is used',
372 )
373 env_group.add_argument(
374 '--installer',
375 choices=_env.INSTALLERS,
376 help='Python package installer to use (defaults to pip)',
377 )
378 parser.add_argument(
379 '--config-setting',
380 '-C',
381 dest='config_settings',
382 action='append',
383 help='settings to pass to the backend. Multiple settings can be provided. '
384 'Settings beginning with a hyphen will erroneously be interpreted as options to build if separated '
385 'by a space character; use ``--config-setting=--my-setting -C--my-other-setting``',
386 metavar='KEY[=VALUE]',
387 )
388 return parser
389
390
391 def main(cli_args: Sequence[str], prog: str | None = None) -> None:
392 """
393 Parse the CLI arguments and invoke the build process.
394
395 :param cli_args: CLI arguments
396 :param prog: Program name to show in help text
397 """
398 parser = main_parser()
399 if prog:
400 parser.prog = prog
401 args = parser.parse_args(cli_args)
402
403 _setup_cli(verbosity=args.verbosity)
404
405 config_settings = {}
406
407 if args.config_settings:
408 for arg in args.config_settings:
409 setting, _, value = arg.partition('=')
410 if setting not in config_settings:
411 config_settings[setting] = value
412 else:
413 if not isinstance(config_settings[setting], list):
414 config_settings[setting] = [config_settings[setting]]
415
416 config_settings[setting].append(value)
417
418 # outdir is relative to srcdir only if omitted.
419 outdir = os.path.join(args.srcdir, 'dist') if args.outdir is None else args.outdir
420
421 distributions: list[Distribution] = args.distributions
422 if distributions:
423 build_call = build_package
424 else:
425 build_call = build_package_via_sdist
426 distributions = ['wheel']
427
428 with _handle_build_error():
429 built = build_call(
430 args.srcdir,
431 outdir,
432 distributions,
433 config_settings,
434 not args.no_isolation,
435 args.skip_dependency_check,
436 args.installer,
437 )
438 artifact_list = _natural_language_list(
439 ['{underline}{}{reset}{bold}{green}'.format(artifact, **_styles.get()) for artifact in built]
440 )
441 _cprint('{bold}{green}Successfully built {}{reset}', artifact_list)
442
443
444 def entrypoint() -> None:
445 main(sys.argv[1:])
446
447
448 if __name__ == '__main__': # pragma: no cover
449 main(sys.argv[1:], 'python -m build')
450
451
452 __all__ = [
453 'main',
454 'main_parser',
455 ]