| 1 |
# SPDX-License-Identifier: Apache-2.0 |
| 2 |
# Copyright 2020 The Meson development team |
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
from pathlib import Path |
| 7 |
import os |
| 8 |
import shlex |
| 9 |
import shutil |
| 10 |
import subprocess |
| 11 |
import typing as T |
| 12 |
|
| 13 |
from . import ExtensionModule, ModuleReturnValue, NewExtensionModule, ModuleInfo |
| 14 |
from .. import mlog, build |
| 15 |
from ..compilers.compilers import CFLAGS_MAPPING |
| 16 |
from ..envconfig import ENV_VAR_PROG_MAP |
| 17 |
from ..dependencies import InternalDependency |
| 18 |
from ..dependencies.pkgconfig import PkgConfigInterface |
| 19 |
from ..interpreterbase import FeatureNew |
| 20 |
from ..interpreter.type_checking import ENV_KW, DEPENDS_KW |
| 21 |
from ..interpreterbase.decorators import ContainerTypeInfo, KwargInfo, typed_kwargs, typed_pos_args |
| 22 |
from ..mesonlib import (EnvironmentException, MesonException, Popen_safe, MachineChoice, |
| 23 |
get_variable_regex, do_replacement, join_args) |
| 24 |
from ..options import OptionKey |
| 25 |
|
| 26 |
if T.TYPE_CHECKING: |
| 27 |
from typing_extensions import TypedDict |
| 28 |
|
| 29 |
from . import ModuleState |
| 30 |
from .._typing import ImmutableListProtocol |
| 31 |
from ..interpreter import Interpreter |
| 32 |
from ..interpreter.kwargs import TargetDepends |
| 33 |
from ..interpreterbase import TYPE_var |
| 34 |
from ..mesonlib import EnvironmentVariables |
| 35 |
from ..utils.core import EnvironOrDict |
| 36 |
|
| 37 |
class Dependency(TypedDict): |
| 38 |
|
| 39 |
subdir: str |
| 40 |
|
| 41 |
class AddProject(TypedDict): |
| 42 |
|
| 43 |
configure_options: T.List[str] |
| 44 |
cross_configure_options: T.List[str] |
| 45 |
verbose: bool |
| 46 |
env: EnvironmentVariables |
| 47 |
depends: T.List[TargetDepends] |
| 48 |
|
| 49 |
|
| 50 |
class ExternalProject(NewExtensionModule): |
| 51 |
|
| 52 |
make: ImmutableListProtocol[str] |
| 53 |
|
| 54 |
def __init__(self, |
| 55 |
state: 'ModuleState', |
| 56 |
configure_command: str, |
| 57 |
configure_options: T.List[str], |
| 58 |
cross_configure_options: T.List[str], |
| 59 |
env: EnvironmentVariables, |
| 60 |
verbose: bool, |
| 61 |
extra_depends: T.List[TargetDepends]): |
| 62 |
super().__init__() |
| 63 |
self.methods.update({'dependency': self.dependency_method, |
| 64 |
}) |
| 65 |
|
| 66 |
self.subdir = Path(state.subdir) |
| 67 |
self.project_version = state.project_version |
| 68 |
self.subproject = state.subproject |
| 69 |
self.env = state.environment |
| 70 |
self.configure_command = configure_command |
| 71 |
self.configure_options = configure_options |
| 72 |
self.cross_configure_options = cross_configure_options |
| 73 |
self.verbose = verbose |
| 74 |
self.user_env = env |
| 75 |
|
| 76 |
self.src_dir = Path(self.env.get_source_dir(), self.subdir) |
| 77 |
self.build_dir = Path(self.env.get_build_dir(), self.subdir, 'build') |
| 78 |
self.install_dir = Path(self.env.get_build_dir(), self.subdir, 'dist') |
| 79 |
_p = self.env.coredata.optstore.get_value_for(OptionKey('prefix')) |
| 80 |
assert isinstance(_p, str), 'for mypy' |
| 81 |
self.prefix = Path(_p) |
| 82 |
_l = self.env.coredata.optstore.get_value_for(OptionKey('libdir')) |
| 83 |
assert isinstance(_l, str), 'for mypy' |
| 84 |
self.libdir = Path(_l) |
| 85 |
_l = self.env.coredata.optstore.get_value_for(OptionKey('bindir')) |
| 86 |
assert isinstance(_l, str), 'for mypy' |
| 87 |
self.bindir = Path(_l) |
| 88 |
_i = self.env.coredata.optstore.get_value_for(OptionKey('includedir')) |
| 89 |
assert isinstance(_i, str), 'for mypy' |
| 90 |
self.includedir = Path(_i) |
| 91 |
self.name = self.src_dir.name |
| 92 |
|
| 93 |
self.prefix = self._cygpath_convert(self.prefix) |
| 94 |
|
| 95 |
# self.prefix is an absolute path, so we cannot append it to another path. |
| 96 |
# On Windows (where cygpath is not applied), |
| 97 |
# if the prefix is "c:/foo" and DESTDIR is "c:/bar", |
| 98 |
# `make` will install files into "c:/bar/c:/foo" which is an invalid path. |
| 99 |
# This also removes the drive letter from the prefix to workaround the issue. |
| 100 |
self.rel_prefix = self.prefix.relative_to(self.prefix.anchor) |
| 101 |
|
| 102 |
self._configure(state) |
| 103 |
|
| 104 |
self.targets = self._create_targets(extra_depends, state.current_build_project) |
| 105 |
|
| 106 |
def _cygpath_convert(self, winpath: Path) -> Path: |
| 107 |
# On Cygwin, MSYS2 and GitBash, the configure command and the prefix |
| 108 |
# should be converted to unix style path like "/c/foo" by cygpath command, |
| 109 |
# because the colon in the drive letter breaks many configure scripts. |
| 110 |
# Do nothing on other environment where cygpath is not available. |
| 111 |
if winpath.drive and shutil.which('cygpath'): |
| 112 |
_p, o, _e = Popen_safe(['cygpath', '-u', winpath.as_posix()]) |
| 113 |
return Path(o.strip('\n')) |
| 114 |
return winpath |
| 115 |
|
| 116 |
def _configure(self, state: 'ModuleState') -> None: |
| 117 |
if self.configure_command == 'waf': |
| 118 |
FeatureNew('Waf external project', '0.60.0').use(self.subproject, state.current_node) |
| 119 |
waf = state.find_program('waf') |
| 120 |
configure_cmd = waf.get_command() |
| 121 |
configure_cmd += ['configure', '-o', str(self.build_dir)] |
| 122 |
workdir = self.src_dir |
| 123 |
self.make = waf.get_command() + ['build'] |
| 124 |
else: |
| 125 |
# Assume it's the name of a script in source dir, like 'configure', |
| 126 |
# 'autogen.sh', etc). |
| 127 |
configure_path = Path(self.src_dir, self.configure_command) |
| 128 |
configure_prog = state.find_program(configure_path.as_posix()) |
| 129 |
configure_cmd = configure_prog.get_command() |
| 130 |
if len(configure_cmd) >= 2 and configure_cmd[-1] == configure_path.as_posix(): |
| 131 |
configure_cmd = configure_cmd[:-1] + [self._cygpath_convert(configure_path).as_posix()] |
| 132 |
workdir = self.build_dir |
| 133 |
self.make = state.find_program('make').get_command() |
| 134 |
|
| 135 |
d = [('PREFIX', '--prefix=@PREFIX@', self.prefix.as_posix()), |
| 136 |
('LIBDIR', '--libdir=@PREFIX@/@LIBDIR@', self.libdir.as_posix()), |
| 137 |
('BINDIR', '--bindir=@PREFIX@/@BINDIR@', self.bindir.as_posix()), |
| 138 |
('INCLUDEDIR', None, self.includedir.as_posix()), |
| 139 |
] |
| 140 |
self._validate_configure_options(d, state) |
| 141 |
|
| 142 |
configure_cmd += self._format_options(self.configure_options, d) |
| 143 |
|
| 144 |
if self.env.is_cross_build(): |
| 145 |
host = '{}-{}-{}'.format(state.environment.machines.host.cpu, |
| 146 |
'pc' if state.environment.machines.host.cpu_family in {"x86", "x86_64"} |
| 147 |
else 'unknown', |
| 148 |
state.environment.machines.host.system) |
| 149 |
d = [('HOST', None, host)] |
| 150 |
configure_cmd += self._format_options(self.cross_configure_options, d) |
| 151 |
|
| 152 |
# Set common env variables like CFLAGS, CC, etc. |
| 153 |
link_exelist: T.List[str] = [] |
| 154 |
link_args: T.List[str] = [] |
| 155 |
self.run_env: EnvironOrDict = os.environ.copy() |
| 156 |
for lang, compiler in self.env.coredata.compilers[MachineChoice.HOST].items(): |
| 157 |
if any(lang not in i for i in (ENV_VAR_PROG_MAP, CFLAGS_MAPPING)): |
| 158 |
continue |
| 159 |
cargs = self.env.coredata.get_external_args(MachineChoice.HOST, lang) |
| 160 |
assert isinstance(cargs, list), 'for mypy' |
| 161 |
self.run_env[ENV_VAR_PROG_MAP[lang][0]] = self._quote_and_join(compiler.get_exelist()) |
| 162 |
self.run_env[CFLAGS_MAPPING[lang]] = self._quote_and_join(cargs) |
| 163 |
if not link_exelist: |
| 164 |
link_exelist = compiler.get_linker_exelist() |
| 165 |
_l = self.env.coredata.get_external_link_args(MachineChoice.HOST, lang) |
| 166 |
assert isinstance(_l, list), 'for mypy' |
| 167 |
link_args = _l |
| 168 |
if link_exelist: |
| 169 |
# FIXME: Do not pass linker because Meson uses CC as linker wrapper, |
| 170 |
# but autotools often expects the real linker (e.h. GNU ld). |
| 171 |
# self.run_env['LD'] = self._quote_and_join(link_exelist) |
| 172 |
pass |
| 173 |
self.run_env['LDFLAGS'] = self._quote_and_join(link_args) |
| 174 |
|
| 175 |
self.run_env = self.user_env.get_env(self.run_env) |
| 176 |
self.run_env = PkgConfigInterface.setup_env(self.run_env, self.env, MachineChoice.HOST, |
| 177 |
uninstalled=True) |
| 178 |
|
| 179 |
self.build_dir.mkdir(parents=True, exist_ok=True) |
| 180 |
self._run('configure', configure_cmd, workdir) |
| 181 |
|
| 182 |
def _quote_and_join(self, array: T.List[str]) -> str: |
| 183 |
return ' '.join([shlex.quote(i) for i in array]) |
| 184 |
|
| 185 |
def _validate_configure_options(self, variables: T.Sequence[T.Tuple[str, T.Optional[str], str]], state: 'ModuleState') -> None: |
| 186 |
# Ensure the user at least try to pass basic info to the build system, |
| 187 |
# like the prefix, libdir, etc. |
| 188 |
for key, default, val in variables: |
| 189 |
if default is None: |
| 190 |
continue |
| 191 |
key_format = f'@{key}@' |
| 192 |
for option in self.configure_options: |
| 193 |
if key_format in option: |
| 194 |
break |
| 195 |
else: |
| 196 |
FeatureNew('Default configure_option', '0.57.0').use(self.subproject, state.current_node) |
| 197 |
self.configure_options.append(default) |
| 198 |
|
| 199 |
def _format_options(self, options: T.List[str], variables: T.Sequence[T.Tuple[str, T.Optional[str], str]]) -> T.List[str]: |
| 200 |
out: T.List[str] = [] |
| 201 |
missing = set() |
| 202 |
regex = get_variable_regex('meson') |
| 203 |
confdata: T.Dict[str, T.Tuple[str, T.Optional[str]]] = {k: (v, None) for k, _, v in variables} |
| 204 |
for o in options: |
| 205 |
arg, missing_vars = do_replacement(regex, o, 'meson', confdata) |
| 206 |
missing.update(missing_vars) |
| 207 |
out.append(arg) |
| 208 |
if missing: |
| 209 |
var_list = ", ".join(repr(m) for m in sorted(missing)) |
| 210 |
raise EnvironmentException( |
| 211 |
f"Variables {var_list} in configure options are missing.") |
| 212 |
return out |
| 213 |
|
| 214 |
def _run(self, step: str, command: T.List[str], workdir: Path) -> None: |
| 215 |
mlog.log(f'External project {self.name}:', mlog.bold(step)) |
| 216 |
m = 'Running command ' + str(command) + ' in directory ' + str(workdir) + '\n' |
| 217 |
logfile = Path(mlog.get_log_dir(), f'{self.name}-{step}.log') |
| 218 |
output = None |
| 219 |
if not self.verbose: |
| 220 |
output = open(logfile, 'w', encoding='utf-8') |
| 221 |
output.write(m + '\n') |
| 222 |
output.flush() |
| 223 |
else: |
| 224 |
mlog.log(m) |
| 225 |
p, *_ = Popen_safe(command, cwd=workdir, env=self.run_env, |
| 226 |
stderr=subprocess.STDOUT, |
| 227 |
stdout=output) |
| 228 |
if p.returncode != 0: |
| 229 |
m = f'{step} step returned error code {p.returncode}.' |
| 230 |
if not self.verbose: |
| 231 |
m += '\nSee logs: ' + str(logfile) |
| 232 |
contents = mlog.ci_fold_file(logfile, f'CI platform detected, click here for {os.path.basename(logfile)} contents.') |
| 233 |
if contents: |
| 234 |
print(contents) |
| 235 |
raise MesonException(m) |
| 236 |
|
| 237 |
def _create_targets(self, extra_depends: T.List[TargetDepends], build_project: build.BuildProject) -> T.List['TYPE_var']: |
| 238 |
cmd = self.env.get_build_command() |
| 239 |
cmd += ['--internal', 'externalproject', |
| 240 |
'--name', self.name, |
| 241 |
'--srcdir', self.src_dir.as_posix(), |
| 242 |
'--builddir', self.build_dir.as_posix(), |
| 243 |
'--installdir', self.install_dir.as_posix(), |
| 244 |
'--logdir', mlog.get_log_dir(), |
| 245 |
'--make', join_args(self.make), |
| 246 |
] |
| 247 |
if self.verbose: |
| 248 |
cmd.append('--verbose') |
| 249 |
|
| 250 |
self.target = build.CustomTarget( |
| 251 |
self.name, |
| 252 |
self.subdir.as_posix(), |
| 253 |
self.env, |
| 254 |
cmd + ['@OUTPUT@', '@DEPFILE@'], |
| 255 |
[], |
| 256 |
[f'{self.name}.stamp'], |
| 257 |
build_project, |
| 258 |
depfile=f'{self.name}.d', |
| 259 |
console=True, |
| 260 |
extra_depends=extra_depends, |
| 261 |
description='Generating external project {}', |
| 262 |
) |
| 263 |
|
| 264 |
idir = build.InstallDir(self.subdir.as_posix(), |
| 265 |
Path('dist', self.rel_prefix).as_posix(), |
| 266 |
install_dir='.', |
| 267 |
install_dir_name='.', |
| 268 |
install_mode=None, |
| 269 |
exclude=None, |
| 270 |
strip_directory=True, |
| 271 |
from_source_dir=False, |
| 272 |
subproject=self.subproject) |
| 273 |
|
| 274 |
return [self.target, idir] |
| 275 |
|
| 276 |
@typed_pos_args('external_project.dependency', str) |
| 277 |
@typed_kwargs('external_project.dependency', KwargInfo('subdir', str, default='')) |
| 278 |
def dependency_method(self, state: 'ModuleState', args: T.Tuple[str], kwargs: 'Dependency') -> InternalDependency: |
| 279 |
libname = args[0] |
| 280 |
|
| 281 |
abs_includedir = Path(self.install_dir, self.rel_prefix, self.includedir) |
| 282 |
if kwargs['subdir']: |
| 283 |
abs_includedir = Path(abs_includedir, kwargs['subdir']) |
| 284 |
abs_libdir = Path(self.install_dir, self.rel_prefix, self.libdir) |
| 285 |
|
| 286 |
version = self.project_version |
| 287 |
compile_args = [f'-I{abs_includedir}'] |
| 288 |
link_args = [f'-L{abs_libdir}', f'-l{libname}'] |
| 289 |
sources = self.target |
| 290 |
dep = InternalDependency(version, [], compile_args, link_args, [], |
| 291 |
[], [sources], [], [], {}, [], [], []) |
| 292 |
return dep |
| 293 |
|
| 294 |
|
| 295 |
class ExternalProjectModule(ExtensionModule): |
| 296 |
|
| 297 |
INFO = ModuleInfo('External build system', '0.56.0', unstable=True) |
| 298 |
|
| 299 |
def __init__(self, interpreter: 'Interpreter'): |
| 300 |
super().__init__(interpreter) |
| 301 |
self.devenv: T.Optional[EnvironmentVariables] = None |
| 302 |
self.methods.update({'add_project': self.add_project, |
| 303 |
}) |
| 304 |
|
| 305 |
@typed_pos_args('external_project_mod.add_project', str) |
| 306 |
@typed_kwargs( |
| 307 |
'external_project.add_project', |
| 308 |
KwargInfo('configure_options', ContainerTypeInfo(list, str), default=[], listify=True), |
| 309 |
KwargInfo('cross_configure_options', ContainerTypeInfo(list, str), default=['--host=@HOST@'], listify=True), |
| 310 |
KwargInfo('verbose', bool, default=False), |
| 311 |
ENV_KW, |
| 312 |
DEPENDS_KW.evolve(since='0.63.0'), |
| 313 |
) |
| 314 |
def add_project(self, state: 'ModuleState', args: T.Tuple[str], kwargs: 'AddProject') -> ModuleReturnValue: |
| 315 |
configure_command = args[0] |
| 316 |
project = ExternalProject(state, |
| 317 |
configure_command, |
| 318 |
kwargs['configure_options'], |
| 319 |
kwargs['cross_configure_options'], |
| 320 |
kwargs['env'], |
| 321 |
kwargs['verbose'], |
| 322 |
kwargs['depends']) |
| 323 |
abs_libdir = Path(project.install_dir, project.rel_prefix, project.libdir).as_posix() |
| 324 |
abs_bindir = Path(project.install_dir, project.rel_prefix, project.bindir).as_posix() |
| 325 |
env = state.environment.get_env_for_paths({abs_libdir}, {abs_bindir}) |
| 326 |
if self.devenv is None: |
| 327 |
self.devenv = env |
| 328 |
else: |
| 329 |
self.devenv.merge(env) |
| 330 |
return ModuleReturnValue(project, project.targets) |
| 331 |
|
| 332 |
def postconf_hook(self, b: build.Build) -> None: |
| 333 |
if self.devenv is not None: |
| 334 |
b.devenv.append(self.devenv) |
| 335 |
|
| 336 |
|
| 337 |
def initialize(interp: 'Interpreter') -> ExternalProjectModule: |
| 338 |
return ExternalProjectModule(interp) |