Debian Codegraph @

mesonbuild/wrap/wrap.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2015 The Meson development team
3
4 from __future__ import annotations
5
6 from .. import mlog
7 import contextlib
8 from dataclasses import dataclass
9 import urllib.request
10 import urllib.error
11 import urllib.parse
12 import os
13 import hashlib
14 import shutil
15 import tempfile
16 import stat
17 import subprocess
18 import sys
19 import configparser
20 import time
21 import typing as T
22 import textwrap
23 import json
24 import gzip
25
26 from base64 import b64encode
27 from enum import Enum
28 from netrc import netrc
29 from pathlib import Path, PurePath
30 from functools import lru_cache
31
32 from . import WrapMode
33 from .. import coredata
34 from ..mesonlib import (
35 DirectoryLock, DirectoryLockAction, quiet_git, GIT, ProgressBar, MesonException,
36 windows_proof_rmtree, Popen_safe, SubProject,
37 )
38 from ..interpreterbase import FeatureNew
39 from .. import mesonlib
40
41 if T.TYPE_CHECKING:
42 import http.client
43 from typing_extensions import Literal
44
45 from ..cargo.manifest import CargoLock
46
47 Method = Literal['meson', 'cmake', 'cargo']
48
49 try:
50 # Importing is just done to check if SSL exists, so all warnings
51 # regarding 'imported but unused' can be safely ignored
52 import ssl # noqa
53 has_ssl = True
54 except ImportError:
55 has_ssl = False
56
57 REQ_TIMEOUT = 30.0
58 WHITELIST_SUBDOMAIN = 'wrapdb.mesonbuild.com'
59
60 if sys.version_info >= (3, 14):
61 import tarfile
62 tarfile.TarFile.extraction_filter = staticmethod(tarfile.fully_trusted_filter)
63
64 @lru_cache(maxsize=None)
65 def patch_command() -> T.Optional[str]:
66 if mesonlib.is_windows():
67 from ..programs import ExternalProgram
68 from ..mesonlib import version_compare
69 _exclude_paths: T.List[str] = []
70 while True:
71 _patch = ExternalProgram('patch', silent=True, exclude_paths=_exclude_paths)
72 if not _patch.found():
73 break
74 if version_compare(_patch.get_version(), '>=2.6.1'):
75 break
76 _exclude_paths.append(os.path.dirname(_patch.get_path()))
77 return _patch.get_path() if _patch.found() else None
78 else:
79 return shutil.which('patch')
80
81
82 truststore_message = '''
83
84 If you believe the connection should be secure, but python cannot see the
85 correct SSL certificates, install https://truststore.readthedocs.io/ and
86 try again.'''
87
88 @lru_cache(maxsize=None)
89 def ssl_truststore() -> T.Optional[ssl.SSLContext]:
90 """ Provide a default context=None for urlopen, but use truststore if installed. """
91 try:
92 import truststore
93 except ImportError:
94 # use default
95 return None
96 else:
97 return truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
98
99 def whitelist_wrapdb(urlstr: str) -> urllib.parse.ParseResult:
100 """ raises WrapException if not whitelisted subdomain """
101 url = urllib.parse.urlparse(urlstr)
102 if not url.hostname:
103 raise WrapException(f'{urlstr} is not a valid URL')
104 if not url.hostname.endswith(WHITELIST_SUBDOMAIN):
105 raise WrapException(f'{urlstr} is not a whitelisted WrapDB URL')
106 if has_ssl and not url.scheme == 'https':
107 raise WrapException(f'WrapDB did not have expected SSL https url, instead got {urlstr}')
108 return url
109
110 def open_wrapdburl(urlstring: str, allow_insecure: bool = False, have_opt: bool = False, allow_compression: bool = False) -> http.client.HTTPResponse:
111 if have_opt:
112 insecure_msg = '\n\n To allow connecting anyway, pass `--allow-insecure`.'
113 else:
114 insecure_msg = ''
115
116 def do_urlopen(url: urllib.parse.ParseResult) -> http.client.HTTPResponse:
117 headers = {}
118 if allow_compression:
119 headers['Accept-Encoding'] = 'gzip'
120 req = urllib.request.Request(urllib.parse.urlunparse(url), headers=headers)
121 return T.cast('http.client.HTTPResponse', urllib.request.urlopen(req, timeout=REQ_TIMEOUT, context=ssl_truststore()))
122
123 url = whitelist_wrapdb(urlstring)
124 if has_ssl:
125 try:
126 return do_urlopen(url)
127 except OSError as excp:
128 msg = f'WrapDB connection failed to {urlstring} with error {excp}.'
129 if isinstance(excp, urllib.error.URLError) and isinstance(excp.reason, ssl.SSLCertVerificationError):
130 if allow_insecure:
131 mlog.warning(f'{msg}\n\n Proceeding without authentication.')
132 elif ssl_truststore() is None:
133 raise WrapException(f'{msg}{insecure_msg}{truststore_message}')
134 else:
135 raise WrapException(f'{msg}{insecure_msg}')
136 else:
137 raise WrapException(msg)
138 elif not allow_insecure:
139 raise WrapException(f'SSL module not available in {sys.executable}: Cannot contact the WrapDB.{insecure_msg}')
140 else:
141 # following code is only for those without Python SSL
142 mlog.warning(f'SSL module not available in {sys.executable}: WrapDB traffic not authenticated.', once=True)
143
144 # If we got this far, allow_insecure was manually passed
145 try:
146 return do_urlopen(url._replace(scheme='http'))
147 except OSError as excp:
148 raise WrapException(f'WrapDB connection failed to {urlstring} with error {excp}')
149
150 def read_and_decompress(resp: http.client.HTTPResponse) -> bytes:
151 data = resp.read()
152 encoding = resp.headers['Content-Encoding']
153 if encoding == 'gzip':
154 return gzip.decompress(data)
155 elif encoding:
156 raise WrapException(f'Unexpected Content-Encoding for {resp.url}: {encoding}')
157 else:
158 return data
159
160 def get_releases_data(allow_insecure: bool) -> bytes:
161 url = open_wrapdburl('https://wrapdb.mesonbuild.com/v2/releases.json', allow_insecure, True, True)
162 return read_and_decompress(url)
163
164 @lru_cache(maxsize=None)
165 def get_releases(allow_insecure: bool) -> T.Dict[str, T.Any]:
166 data = get_releases_data(allow_insecure)
167 return T.cast('T.Dict[str, T.Any]', json.loads(data.decode()))
168
169 def update_wrap_file(wrapfile: str, name: str, new_version: str, new_revision: str, allow_insecure: bool) -> None:
170 url = open_wrapdburl(f'https://wrapdb.mesonbuild.com/v2/{name}_{new_version}-{new_revision}/{name}.wrap',
171 allow_insecure, True, True)
172 with open(wrapfile, 'wb') as f:
173 f.write(read_and_decompress(url))
174
175 def parse_patch_url(patch_url: str) -> T.Tuple[str, str]:
176 u = urllib.parse.urlparse(patch_url)
177 if u.netloc != 'wrapdb.mesonbuild.com':
178 raise WrapException(f'URL {patch_url} does not seems to be a wrapdb patch')
179 arr = u.path.strip('/').split('/')
180 if arr[0] == 'v1':
181 # e.g. https://wrapdb.mesonbuild.com/v1/projects/zlib/1.2.11/5/get_zip
182 return arr[-3], arr[-2]
183 elif arr[0] == 'v2':
184 # e.g. https://wrapdb.mesonbuild.com/v2/zlib_1.2.11-5/get_patch
185 tag = arr[-2]
186 _, version = tag.rsplit('_', 1)
187 version, revision = version.rsplit('-', 1)
188 return version, revision
189 else:
190 raise WrapException(f'Invalid wrapdb URL {patch_url}')
191
192
193 class WrapType(str, Enum):
194 FILE = 'file'
195 GIT = 'git'
196 HG = 'hg'
197 SVN = 'svn'
198 REDIRECT = 'redirect'
199
200
201 class WrapException(MesonException):
202 pass
203
204 class WrapNotFoundException(WrapException):
205 pass
206
207 class PackageDefinition:
208 def __init__(self, name: SubProject, subprojects_dir: str, type_: T.Optional[WrapType] = None, values: T.Optional[T.Dict[str, str]] = None):
209 self.name = name
210 self.subprojects_dir = subprojects_dir
211 self.type = type_
212 self.values = values or {}
213 self.provided_deps: T.Dict[str, T.Optional[str]] = {}
214 self.provided_programs: T.List[str] = []
215 self.diff_files: T.List[Path] = []
216 self.wrapfile_hash: T.Optional[str] = None
217 self.original_filename: T.Optional[str] = None
218 self.redirected: bool = False
219 self.filesdir = os.path.join(self.subprojects_dir, 'packagefiles')
220 self.directory = self.values.get('directory', self.name)
221 if os.path.dirname(self.directory):
222 raise WrapException('Directory key must be a name and not a path')
223 if 'diff_files' in self.values:
224 for s in self.values['diff_files'].split(','):
225 path = Path(s.strip())
226 if path.is_absolute():
227 raise WrapException('diff_files paths cannot be absolute')
228 if '..' in path.parts:
229 raise WrapException('diff_files paths cannot contain ".."')
230 self.diff_files.append(path)
231 # must be lowercase for consistency with dep=variable assignment
232 self.provided_deps[self.name.lower()] = None
233
234 @staticmethod
235 def from_values(name: SubProject, subprojects_dir: str, type_: WrapType, values: T.Dict[str, str]) -> PackageDefinition:
236 return PackageDefinition(name, subprojects_dir, type_, values)
237
238 @staticmethod
239 def from_directory(filename: str) -> PackageDefinition:
240 name = SubProject(os.path.basename(filename))
241 subprojects_dir = os.path.dirname(filename)
242 return PackageDefinition(name, subprojects_dir)
243
244 @staticmethod
245 def from_wrap_file(filename: str, subproject: SubProject = mesonlib.ROOT_SUBPROJECT) -> PackageDefinition:
246 config, type_, values = PackageDefinition._parse_wrap(filename)
247 if 'diff_files' in values:
248 FeatureNew('Wrap files with diff_files', '0.63.0').use(subproject)
249 if 'patch_directory' in values:
250 FeatureNew('Wrap files with patch_directory', '0.55.0').use(subproject)
251 for what in ['patch', 'source']:
252 if f'{what}_filename' in values and f'{what}_url' not in values:
253 FeatureNew(f'Local wrap patch files without {what}_url', '0.55.0').use(subproject)
254
255 subprojects_dir = os.path.dirname(filename)
256
257 if type_ is WrapType.REDIRECT:
258 # [wrap-redirect] have a `filename` value pointing to the real wrap
259 # file we should parse instead. It must be relative to the current
260 # wrap file location and must be in the form foo/subprojects/bar.wrap.
261 fname = Path(values['filename'])
262 for i, p in enumerate(fname.parts):
263 if i % 2 == 0:
264 if p == '..':
265 raise WrapException(f"wrap-redirect filename {values['filename']!r} cannot contain '..'")
266 else:
267 if p != 'subprojects':
268 raise WrapException(f"wrap-redirect filename {values['filename']!r} must be in the form foo/subprojects/bar.wrap")
269 if fname.suffix != '.wrap':
270 raise WrapException(f"wrap-redirect filename {values['filename']!r} must be a .wrap file")
271 fname = Path(subprojects_dir, fname)
272 if not fname.is_file():
273 raise WrapException(f"wrap-redirect filename {values['filename']!r} does not exist")
274 wrap = PackageDefinition.from_wrap_file(str(fname), subproject)
275 wrap.original_filename = filename
276 wrap.redirected = True
277 return wrap
278
279 name = SubProject(os.path.basename(filename)[:-5])
280 wrap = PackageDefinition.from_values(name, subprojects_dir, type_, values)
281 wrap.original_filename = filename
282 wrap.parse_provide_section(config)
283
284 patch_url = values.get('patch_url')
285 if patch_url and patch_url.startswith('https://wrapdb.mesonbuild.com/v1'):
286 if name == 'sqlite':
287 mlog.deprecation('sqlite wrap has been renamed to sqlite3, update using `meson wrap install sqlite3`')
288 elif name == 'libjpeg':
289 mlog.deprecation('libjpeg wrap has been renamed to libjpeg-turbo, update using `meson wrap install libjpeg-turbo`')
290 else:
291 mlog.deprecation(f'WrapDB v1 is deprecated, updated using `meson wrap update {name}`')
292
293 with open(filename, 'r', encoding='utf-8') as file:
294 wrap.wrapfile_hash = hashlib.sha256(file.read().encode('utf-8')).hexdigest()
295
296 return wrap
297
298 @staticmethod
299 def _parse_wrap(filename: str) -> T.Tuple[configparser.ConfigParser, WrapType, T.Dict[str, str]]:
300 try:
301 config = configparser.ConfigParser(interpolation=None)
302 config.read(filename, encoding='utf-8')
303 except configparser.Error as e:
304 raise WrapException(f'Failed to parse {filename}: {e!s}')
305 if len(config.sections()) < 1:
306 raise WrapException(f'Missing sections in {filename}')
307 wrap_section = config.sections()[0]
308 if not wrap_section.startswith('wrap-'):
309 raise WrapException(f'{wrap_section!r} is not a valid first section in {filename}')
310 type_ = wrap_section[5:]
311 if type_ not in tuple(WrapType):
312 raise WrapException(f'Unknown wrap type {type_!r}')
313 values = dict(config[wrap_section])
314 return config, WrapType(type_), values
315
316 def parse_provide_section(self, config: configparser.ConfigParser) -> None:
317 if config.has_section('provides'):
318 raise WrapException('Unexpected "[provides]" section, did you mean "[provide]"?')
319 if config.has_section('provide'):
320 for k, v in config['provide'].items():
321 if k == 'dependency_names':
322 # A comma separated list of dependency names that does not
323 # need a variable name; must be lowercase for consistency with
324 # dep=variable assignment
325 names_dict = {n.strip().lower(): None for n in v.split(',')}
326 self.provided_deps.update(names_dict)
327 continue
328 if k == 'program_names':
329 # A comma separated list of program names
330 names_list = [n.strip() for n in v.split(',')]
331 self.provided_programs += names_list
332 continue
333 if not v:
334 m = (f'Empty dependency variable name for {k!r} in {self.name}.wrap. '
335 'If the subproject uses meson.override_dependency() '
336 'it can be added in the "dependency_names" special key.')
337 raise WrapException(m)
338 self.provided_deps[k] = v
339
340 def get(self, key: str) -> str:
341 try:
342 return self.values[key]
343 except KeyError:
344 raise WrapException(f'Missing key {key!r} in {self.name}.wrap')
345
346 @staticmethod
347 def get_hashfile(subproject_directory: str) -> str:
348 return os.path.join(subproject_directory, '.meson-subproject-wrap-hash.txt')
349
350 def update_hash_cache(self, subproject_directory: str) -> None:
351 if self.wrapfile_hash:
352 with open(self.get_hashfile(subproject_directory), 'w', encoding='utf-8') as file:
353 file.write(self.wrapfile_hash + '\n')
354
355 def add_provided_dep(self, name: str) -> None:
356 self.provided_deps[name] = None
357
358 def verbose_git(cmd: T.List[str], workingdir: str, check: bool = False) -> bool:
359 '''
360 Wrapper to convert GitException to WrapException caught in interpreter.
361 '''
362 try:
363 return mesonlib.verbose_git(cmd, workingdir, check=check)
364 except mesonlib.GitException as e:
365 raise WrapException(str(e))
366
367 @dataclass(eq=False)
368 class Resolver:
369 source_dir: str
370 subdir: str
371 subproject: SubProject = mesonlib.ROOT_SUBPROJECT
372 wrap_mode: WrapMode = WrapMode.default
373 wrap_frontend: bool = False
374 allow_insecure: bool = False
375 silent: bool = False
376
377 def __post_init__(self) -> None:
378 self.subdir_root = os.path.join(self.source_dir, self.subdir)
379 self.project_subdir = os.path.relpath(os.path.dirname(self.subdir_root), self.source_dir)
380 self.cachedir = os.environ.get('MESON_PACKAGE_CACHE_DIR') or os.path.join(self.subdir_root, 'packagecache')
381 self.wraps: T.Dict[str, PackageDefinition] = {}
382 self.netrc: T.Optional[netrc] = None
383 self.provided_deps: T.Dict[str, PackageDefinition] = {}
384 self.provided_programs: T.Dict[str, PackageDefinition] = {}
385 self.wrapdb: T.Dict[str, T.Any] = {}
386 self.wrapdb_provided_deps: T.Dict[str, str] = {}
387 self.wrapdb_provided_programs: T.Dict[str, SubProject] = {}
388 self.loaded_dirs: T.Set[str] = set()
389 self.cargolocks: T.Dict[str, T.Optional[CargoLock]] = {}
390 self.load_wraps()
391 self.load_netrc()
392 self.load_wrapdb()
393
394 def load_netrc(self) -> None:
395 try:
396 self.netrc = netrc()
397 except FileNotFoundError:
398 return
399 except Exception as e:
400 mlog.warning(f'failed to process netrc file: {e}.', fatal=False)
401
402 def load_wraps(self) -> None:
403 # Load subprojects/*.wrap
404 if os.path.isdir(self.subdir_root):
405 root, dirs, files = next(os.walk(self.subdir_root))
406 for i in files:
407 if not i.endswith('.wrap'):
408 continue
409 fname = os.path.join(self.subdir_root, i)
410 wrap = PackageDefinition.from_wrap_file(fname, self.subproject)
411 self.wraps[wrap.name] = wrap
412 # Add dummy package definition for directories not associated with a wrap file.
413 ignore_dirs = {'packagecache', 'packagefiles'}
414 for wrap in self.wraps.values():
415 ignore_dirs |= {wrap.directory, wrap.name}
416 for i in dirs:
417 if i in ignore_dirs:
418 continue
419 fname = os.path.join(self.subdir_root, i)
420 wrap = PackageDefinition.from_directory(fname)
421 self.wraps[wrap.name] = wrap
422 # Add provided deps and programs into our lookup tables
423 for wrap in self.wraps.values():
424 self.add_wrap(wrap)
425 self.get_cargo_lock(self.project_subdir, warn_only=True)
426 self.loaded_dirs.add(self.subdir)
427
428 def get_cargo_lock(self, project_subdir: str, warn_only: bool = False) -> T.Optional[CargoLock]:
429 project_subdir = os.path.normpath(os.path.join(self.source_dir, project_subdir))
430 filename = os.path.join(project_subdir, 'Cargo.lock')
431 if filename in self.cargolocks:
432 return self.cargolocks[filename]
433
434 if not os.path.exists(filename):
435 self.cargolocks[filename] = None
436 return None
437
438 from ..cargo.interpreter import load_cargo_lock
439 from ..cargo.toml import TomlImplementationMissing
440 subdir_root = os.path.join(project_subdir, os.path.basename(self.subdir))
441 try:
442 cargolock = load_cargo_lock(filename, subdir_root)
443 except TomlImplementationMissing as e:
444 if not warn_only:
445 raise
446 # Error delayed to the actual usage of a Cargo subproject; do not
447 # cache the failure, so that it can be reported properly then.
448 mlog.warning(f'cannot load Cargo.lock: {e}', fatal=False, once=True)
449 return None
450
451 self.cargolocks[filename] = cargolock
452 self.merge_wraps(cargolock.wraps)
453 return cargolock
454
455 def add_wrap(self, wrap: PackageDefinition, ignore_dups: bool = False) -> None:
456 for k in wrap.provided_deps.keys():
457 if k not in self.provided_deps:
458 self.provided_deps[k] = wrap
459 elif not ignore_dups:
460 prev_wrap = self.provided_deps[k]
461 m = f'Multiple wrap files provide {k!r} dependency: {wrap.name} and {prev_wrap.name}'
462 raise WrapException(m)
463 for k in wrap.provided_programs:
464 if k not in self.provided_programs:
465 self.provided_programs[k] = wrap
466 elif not ignore_dups:
467 prev_wrap = self.provided_programs[k]
468 m = f'Multiple wrap files provide {k!r} program: {wrap.name} and {prev_wrap.name}'
469 raise WrapException(m)
470
471 def load_wrapdb(self) -> None:
472 try:
473 with Path(self.subdir_root, 'wrapdb.json').open('r', encoding='utf-8') as f:
474 self.wrapdb = json.load(f)
475 except FileNotFoundError:
476 return
477 for name, info in self.wrapdb.items():
478 self.wrapdb_provided_deps.update({i: name for i in info.get('dependency_names', [])})
479 self.wrapdb_provided_programs.update({i: name for i in info.get('program_names', [])})
480
481 def get_from_wrapdb(self, subp_name: str) -> T.Optional[PackageDefinition]:
482 info = self.wrapdb.get(subp_name)
483 if not info:
484 return None
485 self.check_can_download()
486 latest_version = info['versions'][0]
487 version, revision = latest_version.rsplit('-', 1)
488 url = open_wrapdburl(f'https://wrapdb.mesonbuild.com/v2/{subp_name}_{version}-{revision}/{subp_name}.wrap', allow_compression=True)
489 fname = Path(self.subdir_root, f'{subp_name}.wrap')
490 with fname.open('wb') as f:
491 f.write(read_and_decompress(url))
492 mlog.log(f'Installed {subp_name} version {version} revision {revision}')
493 wrap = PackageDefinition.from_wrap_file(str(fname))
494 self.wraps[wrap.name] = wrap
495 self.add_wrap(wrap)
496 return wrap
497
498 def merge_wraps(self, wraps: T.Dict[str, PackageDefinition]) -> None:
499 for k, v in wraps.items():
500 prev_wrap = self.wraps.get(v.directory)
501 if prev_wrap and prev_wrap.type is None and v.type is not None:
502 # This happens when a subproject has been previously downloaded
503 # using a wrap from another subproject and the wrap-redirect got
504 # deleted. In that case, the main project created a bare wrap
505 # for the download directory, but now we have a proper wrap.
506 # It also happens for wraps coming from Cargo.lock files, which
507 # don't create wrap-redirect.
508 del self.wraps[v.directory]
509 del self.provided_deps[v.directory.lower()]
510 if k not in self.wraps:
511 self.wraps[k] = v
512 # it's fine if a dependency or program is provided by a wrap
513 # from *another* project (including the superproject).
514 self.add_wrap(v, ignore_dups=True)
515
516 def load_and_merge(self, subdir: str, subproject: SubProject) -> None:
517 if self.wrap_mode != WrapMode.nopromote and subdir not in self.loaded_dirs:
518 other_resolver = Resolver(self.source_dir, subdir, subproject, self.wrap_mode, self.wrap_frontend, self.allow_insecure, self.silent)
519 self.merge_wraps(other_resolver.wraps)
520 self.cargolocks.update(other_resolver.cargolocks)
521 self.loaded_dirs.add(subdir)
522
523 def get_directory(self, packagename: str) -> T.Optional[str]:
524 wrap = self.wraps.get(packagename)
525 if wrap:
526 return None if wrap.redirected else wrap.directory
527 return packagename
528
529 def find_dep_provider(self, packagename: str) -> T.Tuple[T.Optional[str], T.Optional[str]]:
530 # Python's ini parser converts all key values to lowercase.
531 # Thus the query name must also be in lower case.
532 packagename = packagename.lower()
533 wrap = self.provided_deps.get(packagename)
534 if wrap:
535 dep_var = wrap.provided_deps.get(packagename)
536 return wrap.name, dep_var
537 wrap_name = self.wrapdb_provided_deps.get(packagename)
538 return wrap_name, None
539
540 def get_varname(self, subp_name: str, depname: str) -> T.Optional[str]:
541 wrap = self.wraps.get(subp_name)
542 return wrap.provided_deps.get(depname) if wrap else None
543
544 def find_program_provider(self, names: list[str | mesonlib.File]) -> T.Optional[SubProject]:
545 for name in names:
546 # A File is always a local program, i.e., a script file in the source tree
547 if isinstance(name, mesonlib.File):
548 continue
549 wrap = self.provided_programs.get(name)
550 if wrap:
551 return wrap.name
552 wrap_name = self.wrapdb_provided_programs.get(name)
553 if wrap_name:
554 return wrap_name
555 return None
556
557 def _resolve(self, packagename: str, force_method: T.Optional[Method] = None) -> T.Tuple[str, Method]:
558 wrap = self.wraps.get(packagename)
559 if wrap is None:
560 wrap = self.get_from_wrapdb(packagename)
561 if wrap is None:
562 ustr = f'Neither a subproject directory nor a {packagename}.wrap file was found.'
563 from difflib import get_close_matches
564 close_matches = get_close_matches(packagename, self.wraps.keys())
565 if close_matches:
566 ustr += f' Did you mean "{close_matches[0]}"?'
567 raise WrapNotFoundException(ustr)
568 self.wrap = wrap
569 self.directory = self.wrap.directory
570 self.dirname = os.path.join(self.wrap.subprojects_dir, self.wrap.directory)
571 if not os.path.exists(self.dirname):
572 self.dirname = os.path.join(self.subdir_root, self.directory)
573 rel_path = os.path.relpath(self.dirname, self.source_dir)
574
575 if self.wrap.original_filename:
576 # If the original wrap file is not in main project's subproject_dir,
577 # write a wrap-redirect.
578 basename = os.path.basename(self.wrap.original_filename)
579 main_fname = os.path.join(self.subdir_root, basename)
580 if self.wrap.original_filename != main_fname:
581 rel = os.path.relpath(self.wrap.original_filename, self.source_dir)
582 mlog.log('Using', mlog.bold(rel))
583 # Write a dummy wrap file in main project that redirect to the
584 # wrap we picked.
585 with open(main_fname, 'w', encoding='utf-8') as f:
586 f.write(textwrap.dedent(f'''\
587 [wrap-redirect]
588 filename = {PurePath(os.path.relpath(self.wrap.original_filename, self.subdir_root)).as_posix()}
589 '''))
590
591 # Map each supported method to a file that must exist at the root of source tree.
592 methods_map: T.Dict[Method, str] = {
593 'meson': 'meson.build',
594 'cmake': 'CMakeLists.txt',
595 'cargo': 'Cargo.toml',
596 }
597
598 # Check if this wrap forces a specific method, use meson otherwise.
599 method = T.cast('T.Optional[Method]', self.wrap.values.get('method', force_method))
600 if method and method not in methods_map:
601 allowed_methods = ', '.join(methods_map.keys())
602 raise WrapException(f'Wrap method {method!r} is not supported, must be one of: {allowed_methods}')
603 if force_method and method != force_method:
604 raise WrapException(f'Wrap method is {method!r} but we are trying to configure it with {force_method}')
605 method = method or 'meson'
606
607 def has_buildfile() -> bool:
608 return os.path.exists(os.path.join(self.dirname, methods_map[method]))
609
610 # The directory is there and has meson.build? Great, use it.
611 if has_buildfile():
612 self.validate()
613 return rel_path, method
614
615 # Check if the subproject is a git submodule
616 self.resolve_git_submodule()
617
618 if os.path.exists(self.dirname):
619 if not os.path.isdir(self.dirname):
620 raise WrapException('Path already exists but is not a directory')
621 else:
622 # Check first if we have the extracted directory in our cache. This can
623 # happen for example when MESON_PACKAGE_CACHE_DIR=/usr/share/cargo/registry
624 # on distros that ships Rust source code.
625 # TODO: We don't currently clone git repositories into the cache
626 # directory, but we should to avoid cloning multiple times the same
627 # repository. In that case, we could do something smarter than
628 # copy_tree() here.
629 cached_directory = os.path.join(self.cachedir, self.directory)
630 if os.path.isdir(cached_directory):
631 self.copy_tree(cached_directory, self.dirname)
632 elif self.wrap.type is WrapType.FILE:
633 self._get_file(packagename)
634 else:
635 self.check_can_download()
636 if self.wrap.type is WrapType.GIT:
637 self._get_git(packagename)
638 elif self.wrap.type is WrapType.HG:
639 self._get_hg()
640 elif self.wrap.type is WrapType.SVN:
641 self._get_svn()
642 else:
643 raise WrapException(f'Unknown wrap type {self.wrap.type!r}')
644 try:
645 self.apply_patch(packagename)
646 self.apply_diff_files()
647 except Exception:
648 windows_proof_rmtree(self.dirname)
649 raise
650
651 if not has_buildfile():
652 raise WrapException(f'Subproject exists but has no {methods_map[method]} file.')
653
654 # At this point, the subproject has been successfully resolved for the
655 # first time so save off the hash of the entire wrap file for future
656 # reference.
657 self.wrap.update_hash_cache(self.dirname)
658 return rel_path, method
659
660 def resolve(self, packagename: str, force_method: T.Optional[Method] = None) -> T.Tuple[str, Method]:
661 try:
662 with DirectoryLock(self.subdir_root, '.wraplock',
663 DirectoryLockAction.WAIT,
664 'Failed to lock subprojects directory', optional=True):
665 return self._resolve(packagename, force_method)
666 except FileNotFoundError:
667 raise WrapNotFoundException('Attempted to resolve subproject without subprojects directory present.')
668
669 def check_can_download(self) -> None:
670 # Don't download subproject data based on wrap file if requested.
671 # Git submodules are ok (see above)!
672 if self.wrap_mode is WrapMode.nodownload:
673 m = 'Automatic wrap-based subproject downloading is disabled'
674 raise WrapException(m)
675
676 def resolve_git_submodule(self) -> bool:
677 # Is git installed? If not, we're probably not in a git repository and
678 # definitely cannot try to conveniently set up a submodule.
679 if not GIT:
680 return False
681 # Does the directory exist? Even uninitialised submodules checkout an
682 # empty directory to work in
683 if not os.path.isdir(self.dirname):
684 return False
685 # Are we in a git repository?
686 ret, out = quiet_git(['rev-parse'], Path(self.dirname).parent)
687 if not ret:
688 return False
689 # Is `dirname` a submodule?
690 ret, out = quiet_git(['submodule', 'status', '.'], self.dirname)
691 if not ret:
692 return False
693 # Submodule has not been added, add it
694 if out.startswith('+'):
695 mlog.warning('git submodule might be out of date')
696 return True
697 elif out.startswith('U'):
698 raise WrapException('git submodule has merge conflicts')
699 # Submodule exists, but is deinitialized or wasn't initialized
700 elif out.startswith('-'):
701 if verbose_git(['submodule', 'update', '--init', '.'], self.dirname):
702 return True
703 raise WrapException('git submodule failed to init')
704 # Submodule looks fine, but maybe it wasn't populated properly. Do a checkout.
705 elif out.startswith(' '):
706 verbose_git(['submodule', 'update', '.'], self.dirname)
707 verbose_git(['checkout', '.'], self.dirname)
708 # Even if checkout failed, try building it anyway and let the user
709 # handle any problems manually.
710 return True
711 elif out == '':
712 # It is not a submodule, just a folder that exists in the main repository.
713 return False
714 raise WrapException(f'Unknown git submodule output: {out!r}')
715
716 def _get_file(self, packagename: str) -> None:
717 path = self._get_file_internal('source', packagename)
718 extract_dir = self.subdir_root
719 # Some upstreams ship packages that do not have a leading directory.
720 # Create one for them.
721 if 'lead_directory_missing' in self.wrap.values:
722 os.mkdir(self.dirname)
723 extract_dir = self.dirname
724 try:
725 shutil.unpack_archive(path, extract_dir)
726 except OSError as e:
727 raise WrapException(f'failed to unpack archive with error: {str(e)}') from e
728
729 def _get_git(self, packagename: str) -> None:
730 if not GIT:
731 raise WrapException(f'Git program not found, cannot download {packagename}.wrap via git.')
732 revno = self.wrap.get('revision')
733 checkout_cmd = ['-c', 'advice.detachedHead=false', 'checkout', revno, '--']
734 is_shallow = False
735 depth_option: T.List[str] = []
736 if self.wrap.values.get('depth', '') != '':
737 is_shallow = True
738 depth_option = ['--depth', self.wrap.values.get('depth')]
739 # for some reason git only allows commit ids to be shallowly fetched by fetch not with clone
740 if is_shallow and self.is_git_full_commit_id(revno):
741 # git doesn't support directly cloning shallowly for commits,
742 # so we follow https://stackoverflow.com/a/43136160
743 verbose_git(['-c', 'init.defaultBranch=meson-dummy-branch', 'init', self.directory], self.subdir_root, check=True)
744 verbose_git(['remote', 'add', 'origin', self.wrap.get('url')], self.dirname, check=True)
745 revno = self.wrap.get('revision')
746 verbose_git(['fetch', *depth_option, 'origin', revno], self.dirname, check=True)
747 verbose_git(checkout_cmd, self.dirname, check=True)
748 else:
749 if not is_shallow:
750 verbose_git(['clone', self.wrap.get('url'), self.directory], self.subdir_root, check=True)
751 if revno.lower() != 'head':
752 if not verbose_git(checkout_cmd, self.dirname):
753 verbose_git(['fetch', self.wrap.get('url'), revno], self.dirname, check=True)
754 verbose_git(checkout_cmd, self.dirname, check=True)
755 else:
756 args = ['-c', 'advice.detachedHead=false', 'clone', *depth_option]
757 if revno.lower() != 'head':
758 args += ['--branch', revno]
759 args += [self.wrap.get('url'), self.directory]
760 verbose_git(args, self.subdir_root, check=True)
761 if self.wrap.values.get('clone-recursive', '').lower() == 'true':
762 verbose_git(['submodule', 'update', '--init', '--checkout', '--recursive', *depth_option],
763 self.dirname, check=True)
764 push_url = self.wrap.values.get('push-url')
765 if push_url:
766 verbose_git(['remote', 'set-url', '--push', 'origin', push_url], self.dirname, check=True)
767
768 def validate(self) -> None:
769 # This check is only for subprojects with wraps.
770 if not self.wrap.wrapfile_hash:
771 return
772
773 # Retrieve original hash, if it exists.
774 hashfile = self.wrap.get_hashfile(self.dirname)
775 if os.path.isfile(hashfile):
776 with open(hashfile, 'r', encoding='utf-8') as file:
777 expected_hash = file.read().strip()
778 else:
779 # If stored hash doesn't exist then don't warn.
780 return
781
782 # Compare hashes and warn the user if they don't match.
783 if expected_hash != self.wrap.wrapfile_hash:
784 mlog.warning(f'Subproject {self.wrap.name}\'s revision may be out of date; its wrap file has changed since it was first configured')
785
786 def is_git_full_commit_id(self, revno: str) -> bool:
787 result = False
788 if len(revno) in {40, 64}: # 40 for sha1, 64 for upcoming sha256
789 result = all(ch in '0123456789AaBbCcDdEeFf' for ch in revno)
790 return result
791
792 def _get_hg(self) -> None:
793 revno = self.wrap.get('revision')
794 hg = shutil.which('hg')
795 if not hg:
796 raise WrapException('Mercurial program not found.')
797 subprocess.check_call([hg, 'clone', self.wrap.get('url'),
798 self.directory], cwd=self.subdir_root)
799 if revno.lower() != 'tip':
800 subprocess.check_call([hg, 'checkout', revno],
801 cwd=self.dirname)
802
803 def _get_svn(self) -> None:
804 revno = self.wrap.get('revision')
805 svn = shutil.which('svn')
806 if not svn:
807 raise WrapException('SVN program not found.')
808 subprocess.check_call([svn, 'checkout', '-r', revno, self.wrap.get('url'),
809 self.directory], cwd=self.subdir_root)
810
811 def get_netrc_credentials(self, netloc: str) -> T.Optional[T.Tuple[str, str]]:
812 if self.netrc is None or netloc not in self.netrc.hosts:
813 return None
814
815 login, account, password = self.netrc.authenticators(netloc)
816 if account:
817 login = account
818
819 return login, password
820
821 def get_data(self, urlstring: str) -> T.Tuple[str, str]:
822 blocksize = 10 * 1024
823 h = hashlib.sha256()
824 tmpfile = tempfile.NamedTemporaryFile(mode='wb', dir=self.cachedir, delete=False)
825 url = urllib.parse.urlparse(urlstring)
826 if url.hostname and url.hostname.endswith(WHITELIST_SUBDOMAIN):
827 resp = open_wrapdburl(urlstring, allow_insecure=self.allow_insecure, have_opt=self.wrap_frontend)
828 elif WHITELIST_SUBDOMAIN in urlstring:
829 raise WrapException(f'{urlstring} may be a WrapDB-impersonating URL')
830 elif url.scheme == 'sftp':
831 sftp = shutil.which('sftp')
832 if sftp is None:
833 raise WrapException('Scheme sftp is not available. Install sftp to enable it.')
834 with tempfile.TemporaryDirectory() as workdir, \
835 tempfile.NamedTemporaryFile(mode='wb', dir=self.cachedir, delete=False) as tmpfile:
836 args = []
837 # Older versions of the sftp client cannot handle URLs, hence the splitting of url below
838 if url.port:
839 args += ['-P', f'{url.port}']
840 user = f'{url.username}@' if url.username else ''
841 command = [sftp, '-o', 'KbdInteractiveAuthentication=no', *args, f'{user}{url.hostname}:{url.path[1:]}']
842 subprocess.run(command, cwd=workdir, check=True)
843 downloaded = os.path.join(workdir, os.path.basename(url.path))
844 tmpfile.close()
845 shutil.move(downloaded, tmpfile.name)
846 return self.hash_file(tmpfile.name), tmpfile.name
847 else:
848 headers = {
849 'User-Agent': f'mesonbuild/{coredata.version}',
850 'Accept-Language': '*',
851 'Accept-Encoding': '*',
852 }
853 creds = self.get_netrc_credentials(url.netloc)
854
855 if creds is not None and '@' not in url.netloc:
856 login, password = creds
857 if url.scheme == 'https':
858 enc_creds = b64encode(f'{login}:{password}'.encode()).decode()
859 headers.update({'Authorization': f'Basic {enc_creds}'})
860 elif url.scheme == 'ftp':
861 urlstring = urllib.parse.urlunparse(url._replace(netloc=f'{login}:{password}@{url.netloc}'))
862 else:
863 mlog.warning('Meson is not going to use netrc credentials for protocols other than https/ftp',
864 fatal=False)
865
866 try:
867 req = urllib.request.Request(urlstring, headers=headers)
868 resp = urllib.request.urlopen(req, timeout=REQ_TIMEOUT, context=ssl_truststore())
869 except OSError as e:
870 mlog.log(str(e))
871 if isinstance(e, urllib.error.URLError) and isinstance(e.reason, ssl.SSLCertVerificationError) and ssl_truststore() is None:
872 raise WrapException(f'could not get {urlstring}; is the internet available?{truststore_message}')
873 else:
874 raise WrapException(f'could not get {urlstring}; is the internet available?')
875 with contextlib.closing(resp) as resp, tmpfile as tmpfile:
876 try:
877 dlsize = int(resp.info()['Content-Length'])
878 except TypeError:
879 dlsize = None
880 if dlsize is None:
881 print('Downloading file of unknown size.')
882 while True:
883 block = resp.read(blocksize)
884 if block == b'':
885 break
886 h.update(block)
887 tmpfile.write(block)
888 hashvalue = h.hexdigest()
889 return hashvalue, tmpfile.name
890 sys.stdout.flush()
891 progress_bar = ProgressBar(bar_type='download', total=dlsize,
892 desc='Downloading',
893 disable=(self.silent or None))
894 while True:
895 block = resp.read(blocksize)
896 if block == b'':
897 break
898 h.update(block)
899 tmpfile.write(block)
900 progress_bar.update(len(block))
901 progress_bar.close()
902 hashvalue = h.hexdigest()
903 return hashvalue, tmpfile.name
904
905 def hash_file(self, path: str) -> str:
906 h = hashlib.sha256()
907 with open(path, 'rb') as f:
908 h.update(f.read())
909 return h.hexdigest()
910
911 def check_hash(self, what: str, path: str, hash_required: bool = True) -> None:
912 if what + '_hash' not in self.wrap.values and not hash_required:
913 return
914 expected = self.wrap.get(what + '_hash').lower()
915 dhash = self.hash_file(path)
916 if dhash != expected:
917 raise WrapException(f'Incorrect hash for {what}:\n {expected} expected\n {dhash} actual.')
918
919 def get_data_with_backoff(self, urlstring: str) -> T.Tuple[str, str]:
920 delays = [1, 2, 4, 8, 16]
921 for d in delays:
922 try:
923 return self.get_data(urlstring)
924 except Exception as e:
925 mlog.warning(f'failed to download with error: {e}. Trying after a delay...', fatal=False)
926 time.sleep(d)
927 return self.get_data(urlstring)
928
929 def _download(self, what: str, ofname: str, packagename: str, fallback: bool = False) -> None:
930 self.check_can_download()
931 srcurl = self.wrap.get(what + ('_fallback_url' if fallback else '_url'))
932 mlog.log('Downloading', mlog.bold(packagename), what, 'from', mlog.bold(srcurl))
933 try:
934 dhash, tmpfile = self.get_data_with_backoff(srcurl)
935 expected = self.wrap.get(what + '_hash').lower()
936 if dhash != expected:
937 os.remove(tmpfile)
938 raise WrapException(f'Incorrect hash for {what}:\n {expected} expected\n {dhash} actual.')
939 except WrapException:
940 if not fallback:
941 if what + '_fallback_url' in self.wrap.values:
942 return self._download(what, ofname, packagename, fallback=True)
943 mlog.log('A fallback URL could be specified using',
944 mlog.bold(what + '_fallback_url'), 'key in the wrap file')
945 raise
946 os.rename(tmpfile, ofname)
947
948 def _get_file_internal(self, what: str, packagename: str) -> str:
949 filename = self.wrap.get(what + '_filename')
950 if what + '_url' in self.wrap.values:
951 cache_path = os.path.join(self.cachedir, filename)
952
953 if os.path.exists(cache_path):
954 self.check_hash(what, cache_path)
955 mlog.log('Using', mlog.bold(packagename), what, 'from cache.')
956 return cache_path
957
958 os.makedirs(self.cachedir, exist_ok=True)
959 self._download(what, cache_path, packagename)
960 return cache_path
961 else:
962 path = Path(self.wrap.filesdir) / filename
963
964 if not path.exists():
965 raise WrapException(f'File "{path}" does not exist')
966 self.check_hash(what, path.as_posix(), hash_required=False)
967
968 return path.as_posix()
969
970 def apply_patch(self, packagename: str) -> None:
971 if 'patch_filename' in self.wrap.values and 'patch_directory' in self.wrap.values:
972 m = f'Wrap file {self.wrap.name!r} must not have both "patch_filename" and "patch_directory"'
973 raise WrapException(m)
974 if 'patch_filename' in self.wrap.values:
975 path = self._get_file_internal('patch', packagename)
976 try:
977 shutil.unpack_archive(path, self.subdir_root)
978 except Exception:
979 with tempfile.TemporaryDirectory() as workdir:
980 shutil.unpack_archive(path, workdir)
981 self.copy_tree(workdir, self.subdir_root)
982 elif 'patch_directory' in self.wrap.values:
983 patch_dir = self.wrap.values['patch_directory']
984 src_dir = os.path.join(self.wrap.filesdir, patch_dir)
985 if not os.path.isdir(src_dir):
986 raise WrapException(f'patch directory does not exist: {patch_dir}')
987 self.copy_tree(src_dir, self.dirname)
988
989 def apply_diff_files(self) -> None:
990 for filename in self.wrap.diff_files:
991 mlog.log(f'Applying diff file "{filename}"')
992 path = Path(self.wrap.filesdir) / filename
993 if not path.exists():
994 raise WrapException(f'Diff file "{path}" does not exist')
995 relpath = os.path.relpath(str(path), self.dirname)
996 if patch_command():
997 # Always pass a POSIX path to patch, because on Windows it's MSYS
998 # Ignore whitespace when applying patches to workaround
999 # line-ending differences
1000 cmd = [patch_command(), '-l', '-f', '-p1', '-i', str(Path(relpath).as_posix())]
1001 elif GIT:
1002 # If the `patch` command is not available, fall back to `git
1003 # apply`. The `--work-tree` is necessary in case we're inside a
1004 # Git repository: by default, Git will try to apply the patch to
1005 # the repository root.
1006 cmd = [GIT, '--work-tree', '.', 'apply', '--ignore-whitespace', '-p1', relpath]
1007 else:
1008 raise WrapException('Missing "patch" or "git" commands to apply diff files')
1009
1010 p, out, _ = Popen_safe(cmd, cwd=self.dirname, stderr=subprocess.STDOUT)
1011 if p.returncode != 0:
1012 mlog.log(out.strip())
1013 raise WrapException(f'Failed to apply diff file "{filename}"')
1014
1015 def copy_tree(self, root_src_dir: str, root_dst_dir: str) -> None:
1016 """
1017 Copy directory tree. Overwrites also read only files.
1018 """
1019 for src_dir, _, files in os.walk(root_src_dir):
1020 dst_dir = src_dir.replace(root_src_dir, root_dst_dir, 1)
1021 if not os.path.exists(dst_dir):
1022 os.makedirs(dst_dir)
1023 for file_ in files:
1024 src_file = os.path.join(src_dir, file_)
1025 dst_file = os.path.join(dst_dir, file_)
1026 if os.path.exists(dst_file):
1027 try:
1028 os.remove(dst_file)
1029 except PermissionError:
1030 os.chmod(dst_file, stat.S_IWUSR)
1031 os.remove(dst_file)
1032 shutil.copy2(src_file, dst_dir, follow_symlinks=False)