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