Debian Codegraph @

mesonbuild/msubprojects.py

raw
1 from __future__ import annotations
2
3 from dataclasses import dataclass, InitVar
4 import sys, os, subprocess
5 import argparse
6 import asyncio
7 import fnmatch
8 import threading
9 import copy
10 import shutil
11 from concurrent.futures.thread import ThreadPoolExecutor
12 from pathlib import Path
13 import typing as T
14 import tarfile
15 import zipfile
16
17 from . import mlog
18 from .ast import IntrospectionInterpreter
19 from .mesonlib import quiet_git, GitException, Popen_safe, MesonException, windows_proof_rmtree
20 from .wrap.wrap import (Resolver, WrapException, WrapType,
21 parse_patch_url, update_wrap_file, get_releases)
22
23 if T.TYPE_CHECKING:
24 from typing_extensions import Protocol
25
26 from .wrap.wrap import PackageDefinition
27
28 SubParsers = argparse._SubParsersAction[argparse.ArgumentParser]
29
30 class Arguments(Protocol):
31 sourcedir: str
32 num_processes: int
33 subprojects: T.List[str]
34 types: str
35 subprojects_func: T.Callable[[], bool]
36 allow_insecure: bool
37
38 class UpdateArguments(Arguments):
39 rebase: bool
40 reset: bool
41
42 class UpdateWrapDBArguments(Arguments):
43 force: bool
44 releases: T.Dict[str, T.Any]
45
46 class CheckoutArguments(Arguments):
47 b: bool
48 branch_name: str
49
50 class ForeachArguments(Arguments):
51 command: str
52 args: T.List[str]
53
54 class PurgeArguments(Arguments):
55 confirm: bool
56 include_cache: bool
57
58 class PackagefilesArguments(Arguments):
59 apply: bool
60 save: bool
61
62 ALL_TYPES_STRING = ', '.join(WrapType)
63
64 if sys.version_info >= (3, 14):
65 tarfile.TarFile.extraction_filter = staticmethod(tarfile.fully_trusted_filter)
66
67 def read_archive_files(path: Path, base_path: Path) -> T.Set[Path]:
68 if path.suffix == '.zip':
69 with zipfile.ZipFile(path, 'r') as zip_archive:
70 archive_files = {base_path / i.filename for i in zip_archive.infolist()}
71 else:
72 with tarfile.open(path) as tar_archive: # [ignore encoding]
73 archive_files = {base_path / i.name for i in tar_archive}
74 return archive_files
75
76 class Logger:
77 def __init__(self, total_tasks: int) -> None:
78 self.lock = threading.Lock()
79 self.total_tasks = total_tasks
80 self.completed_tasks = 0
81 self.running_tasks: T.Set[str] = set()
82 self.should_erase_line = ''
83
84 def flush(self) -> None:
85 if self.should_erase_line:
86 print(self.should_erase_line, end='\r')
87 self.should_erase_line = ''
88
89 def print_progress(self) -> None:
90 line = f'Progress: {self.completed_tasks} / {self.total_tasks}'
91 max_len = shutil.get_terminal_size().columns - len(line)
92 running = ', '.join(self.running_tasks)
93 if len(running) + 3 > max_len:
94 running = running[:max_len - 6] + '...'
95 line = line + f' ({running})'
96 print(self.should_erase_line, line, sep='', end='\r')
97 self.should_erase_line = '\x1b[K'
98
99 def start(self, wrap_name: str) -> None:
100 with self.lock:
101 self.running_tasks.add(wrap_name)
102 self.print_progress()
103
104 def done(self, wrap_name: str, log_queue: T.List[T.Tuple[mlog.TV_LoggableList, T.Any]]) -> None:
105 with self.lock:
106 self.flush()
107 for args, kwargs in log_queue:
108 mlog.log(*args, **kwargs)
109 self.running_tasks.remove(wrap_name)
110 self.completed_tasks += 1
111 self.print_progress()
112
113
114 @dataclass(eq=False)
115 class Runner:
116 logger: Logger
117 r: InitVar[Resolver]
118 wrap: PackageDefinition
119 repo_dir: str
120 options: 'Arguments'
121
122 def __post_init__(self, r: Resolver) -> None:
123 # FIXME: Do a copy because Resolver.resolve() is stateful method that
124 # cannot be called from multiple threads.
125 self.wrap_resolver = copy.copy(r)
126 self.wrap_resolver.dirname = os.path.join(r.subdir_root, self.wrap.directory)
127 self.wrap_resolver.wrap = self.wrap
128 self.run_method: T.Callable[[], bool] = self.options.subprojects_func.__get__(self)
129 self.log_queue: T.List[T.Tuple[mlog.TV_LoggableList, T.Any]] = []
130
131 def log(self, *args: mlog.TV_Loggable, **kwargs: T.Any) -> None:
132 self.log_queue.append((list(args), kwargs))
133
134 def run(self) -> bool:
135 self.logger.start(self.wrap.name)
136 try:
137 result = self.run_method()
138 except MesonException as e:
139 self.log(mlog.red('Error:'), str(e))
140 result = False
141 self.logger.done(self.wrap.name, self.log_queue)
142 return result
143
144 @staticmethod
145 def pre_update_wrapdb(options: 'UpdateWrapDBArguments') -> None:
146 options.releases = get_releases(options.allow_insecure)
147
148 def update_wrapdb(self) -> bool:
149 self.log(f'Checking latest WrapDB version for {self.wrap.name}...')
150 options = T.cast('UpdateWrapDBArguments', self.options)
151
152 # Check if this wrap is in WrapDB
153 info = options.releases.get(self.wrap.name)
154 if not info:
155 self.log(' -> Wrap not found in wrapdb')
156 return True
157
158 # Determine current version
159 try:
160 wrapdb_version = self.wrap.get('wrapdb_version')
161 branch, revision = wrapdb_version.split('-', 1)
162 except ValueError:
163 if not options.force:
164 self.log(' ->', mlog.red('Malformed wrapdb_version field, use --force to update anyway'))
165 return False
166 branch = revision = None
167 except WrapException:
168 # Fallback to parsing the patch URL to determine current version.
169 # This won't work for projects that have upstream Meson support.
170 try:
171 patch_url = self.wrap.get('patch_url')
172 branch, revision = parse_patch_url(patch_url)
173 except WrapException:
174 if not options.force:
175 self.log(' ->', mlog.red('Could not determine current version, use --force to update anyway'))
176 return False
177 branch = revision = None
178
179 # Download latest wrap if version differs
180 latest_version = info['versions'][0]
181 new_branch, new_revision = latest_version.rsplit('-', 1)
182 if new_branch != branch or new_revision != revision:
183 filename = self.wrap.original_filename
184 if not filename:
185 filename = os.path.join(self.wrap.subprojects_dir, f'{self.wrap.name}.wrap')
186 update_wrap_file(filename, self.wrap.name,
187 new_branch, new_revision,
188 options.allow_insecure)
189 self.log(' -> New version downloaded:', mlog.blue(latest_version))
190 else:
191 self.log(' -> Already at latest version:', mlog.blue(latest_version))
192
193 return True
194
195 def update_file(self) -> bool:
196 options = T.cast('UpdateArguments', self.options)
197 if options.reset:
198 # Delete existing directory and redownload. It is possible that nothing
199 # changed but we have no way to know. Hopefully tarballs are still
200 # cached.
201 windows_proof_rmtree(self.repo_dir)
202 try:
203 self.wrap_resolver.resolve(self.wrap.name)
204 self.log(' -> New version extracted')
205 return True
206 except WrapException as e:
207 self.log(' ->', mlog.red(str(e)))
208 return False
209 else:
210 # The subproject has not changed, or the new source and/or patch
211 # tarballs should be extracted in the same directory than previous
212 # version.
213 self.log(' -> Subproject has not changed, or the new source/patch needs to be extracted on the same location.')
214 self.log(' Pass --reset option to delete directory and redownload.')
215 return False
216
217 def git_output(self, cmd: T.List[str]) -> str:
218 return quiet_git(cmd, self.repo_dir, check=True)[1]
219
220 def git_verbose(self, cmd: T.List[str]) -> None:
221 self.log(self.git_output(cmd))
222
223 def git_stash(self) -> None:
224 # That git command return some output when there is something to stash.
225 # We don't want to stash when there is nothing to stash because that would
226 # print spurious "No local changes to save".
227 if quiet_git(['status', '--porcelain', ':!/.meson-subproject-wrap-hash.txt'], self.repo_dir)[1].strip():
228 # Don't pipe stdout here because we want the user to see their changes have
229 # been saved.
230 # Note: `--all` is used, and not `--include-untracked`, to prevent
231 # a potential error if `.meson-subproject-wrap-hash.txt` matches a
232 # gitignore pattern.
233 # We must add the dot in addition to the negation, because older versions of git have a bug.
234 self.git_verbose(['stash', 'push', '--all', ':!/.meson-subproject-wrap-hash.txt', '.'])
235
236 def git_show(self) -> None:
237 commit_message = self.git_output(['show', '--quiet', '--pretty=format:%h%n%d%n%s%n[%an]'])
238 parts = [s.strip() for s in commit_message.split('\n')]
239 self.log(' ->', mlog.yellow(parts[0]), mlog.red(parts[1]), parts[2], mlog.blue(parts[3]))
240
241 def git_rebase(self, revision: str) -> bool:
242 try:
243 self.git_output(['-c', 'rebase.autoStash=true', 'rebase', 'FETCH_HEAD'])
244 except GitException as e:
245 self.git_output(['-c', 'rebase.autoStash=true', 'rebase', '--abort'])
246 self.log(' -> Could not rebase', mlog.bold(self.repo_dir), 'onto', mlog.bold(revision),
247 '-- aborted')
248 self.log(mlog.red(e.output))
249 self.log(mlog.red(str(e)))
250 return False
251 return True
252
253 def git_reset(self, revision: str) -> bool:
254 try:
255 # Stash local changes, commits can always be found back in reflog, to
256 # avoid any data lost by mistake.
257 self.git_stash()
258 self.git_output(['reset', '--hard', 'FETCH_HEAD'])
259 self.wrap_resolver.apply_patch(self.wrap.name)
260 self.wrap_resolver.apply_diff_files()
261 except GitException as e:
262 self.log(' -> Could not reset', mlog.bold(self.repo_dir), 'to', mlog.bold(revision))
263 self.log(mlog.red(e.output))
264 self.log(mlog.red(str(e)))
265 return False
266 return True
267
268 def git_checkout(self, revision: str, create: bool = False) -> bool:
269 cmd = ['checkout', '--ignore-other-worktrees']
270 if create:
271 cmd.append('-b')
272 cmd += [revision, '--']
273 try:
274 # Stash local changes, commits can always be found back in reflog, to
275 # avoid any data lost by mistake.
276 self.git_stash()
277 self.git_output(cmd)
278 except GitException as e:
279 self.log(' -> Could not checkout', mlog.bold(revision), 'in', mlog.bold(self.repo_dir))
280 self.log(mlog.red(e.output))
281 self.log(mlog.red(str(e)))
282 return False
283 return True
284
285 def git_checkout_and_reset(self, revision: str) -> bool:
286 # revision could be a branch that already exists but is outdated, so we still
287 # have to reset after the checkout.
288 success = self.git_checkout(revision)
289 if success:
290 success = self.git_reset(revision)
291 return success
292
293 def git_checkout_and_rebase(self, revision: str) -> bool:
294 # revision could be a branch that already exists but is outdated, so we still
295 # have to rebase after the checkout.
296 success = self.git_checkout(revision)
297 if success:
298 success = self.git_rebase(revision)
299 return success
300
301 def git_branch_has_upstream(self, urls: set) -> bool:
302 cmd = ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{upstream}']
303 ret, upstream = quiet_git(cmd, self.repo_dir)
304 if not ret:
305 return False
306 try:
307 remote = upstream.split('/', maxsplit=1)[0]
308 except IndexError:
309 return False
310 cmd = ['remote', 'get-url', remote]
311 ret, remote_url = quiet_git(cmd, self.repo_dir)
312 return remote_url.strip() in urls
313
314 def update_git(self) -> bool:
315 options = T.cast('UpdateArguments', self.options)
316 if not os.path.exists(os.path.join(self.repo_dir, '.git')):
317 if options.reset:
318 # Delete existing directory and redownload
319 windows_proof_rmtree(self.repo_dir)
320 try:
321 self.wrap_resolver.resolve(self.wrap.name)
322 self.update_git_done()
323 return True
324 except WrapException as e:
325 self.log(' ->', mlog.red(str(e)))
326 return False
327 else:
328 self.log(' -> Not a git repository.')
329 self.log('Pass --reset option to delete directory and redownload.')
330 return False
331 revision_val = self.wrap.values.get('revision')
332 revision = revision_val if revision_val.upper() != 'HEAD' else 'HEAD'
333 url = self.wrap.values.get('url')
334 push_url = self.wrap.values.get('push-url')
335 if not revision or not url:
336 # It could be a detached git submodule for example.
337 self.log(' -> No revision or URL specified.')
338 return True
339 try:
340 origin_url = self.git_output(['remote', 'get-url', 'origin']).strip()
341 except GitException as e:
342 self.log(' -> Failed to determine current origin URL in', mlog.bold(self.repo_dir))
343 self.log(mlog.red(e.output))
344 self.log(mlog.red(str(e)))
345 return False
346 if options.reset:
347 try:
348 self.git_output(['remote', 'set-url', 'origin', url])
349 if push_url:
350 self.git_output(['remote', 'set-url', '--push', 'origin', push_url])
351 except GitException as e:
352 self.log(' -> Failed to reset origin URL in', mlog.bold(self.repo_dir))
353 self.log(mlog.red(e.output))
354 self.log(mlog.red(str(e)))
355 return False
356 elif url != origin_url:
357 self.log(f' -> URL changed from {origin_url!r} to {url!r}')
358 return False
359 try:
360 # Same as `git branch --show-current` but compatible with older git version
361 branch = self.git_output(['rev-parse', '--abbrev-ref', 'HEAD']).strip()
362 branch = branch if branch != 'HEAD' else ''
363 except GitException as e:
364 self.log(' -> Failed to determine current branch in', mlog.bold(self.repo_dir))
365 self.log(mlog.red(e.output))
366 self.log(mlog.red(str(e)))
367 return False
368 if self.wrap_resolver.is_git_full_commit_id(revision) and \
369 quiet_git(['rev-parse', '--verify', revision + '^{commit}'], self.repo_dir)[0]:
370 # The revision we need is both a commit and available. So we do not
371 # need to fetch it because it cannot be updated. Instead, trick
372 # git into setting FETCH_HEAD just in case, from the local commit.
373 self.git_output(['fetch', '.', revision])
374 else:
375 try:
376 # Fetch only the revision we need, this avoids fetching useless branches.
377 # revision can be either a branch, tag or commit id. In all cases we want
378 # FETCH_HEAD to be set to the desired commit and "git checkout <revision>"
379 # to to either switch to existing/new branch, or detach to tag/commit.
380 # It is more complicated than it first appear, see discussion there:
381 # https://github.com/mesonbuild/meson/pull/7723#discussion_r488816189.
382 heads_refmap = '+refs/heads/*:refs/remotes/origin/*'
383 tags_refmap = '+refs/tags/*:refs/tags/*'
384 self.git_output(['fetch', '--refmap', heads_refmap, '--refmap', tags_refmap, 'origin', revision])
385 except GitException as e:
386 self.log(' -> Could not fetch revision', mlog.bold(revision), 'in', mlog.bold(self.repo_dir))
387 self.log(mlog.red(e.output))
388 self.log(mlog.red(str(e)))
389 return False
390
391 if branch == '':
392 # We are currently in detached mode
393 if options.reset:
394 success = self.git_checkout_and_reset(revision)
395 else:
396 success = self.git_checkout_and_rebase(revision)
397 elif branch == revision:
398 # We are in the same branch. A reset could still be needed in the case
399 # a force push happened on remote repository.
400 if options.reset:
401 success = self.git_reset(revision)
402 else:
403 success = self.git_rebase(revision)
404 else:
405 # We are in another branch, either the user created their own branch and
406 # we should rebase it, or revision changed in the wrap file (we
407 # know this when the current branch has an upstream) and we need to
408 # checkout the new branch.
409 if options.reset:
410 success = self.git_checkout_and_reset(revision)
411 else:
412 if self.git_branch_has_upstream({url, push_url}):
413 success = self.git_checkout_and_rebase(revision)
414 else:
415 success = self.git_rebase(revision)
416 if success:
417 self.update_git_done()
418 return success
419
420 def update_git_done(self) -> None:
421 self.git_output(['submodule', 'update', '--checkout', '--recursive'])
422 self.git_show()
423
424 def update_hg(self) -> bool:
425 revno = self.wrap.get('revision')
426 if revno.lower() == 'tip':
427 # Failure to do pull is not a fatal error,
428 # because otherwise you can't develop without
429 # a working net connection.
430 subprocess.call(['hg', 'pull'], cwd=self.repo_dir)
431 else:
432 if subprocess.call(['hg', 'checkout', revno], cwd=self.repo_dir) != 0:
433 subprocess.check_call(['hg', 'pull'], cwd=self.repo_dir)
434 subprocess.check_call(['hg', 'checkout', revno], cwd=self.repo_dir)
435 return True
436
437 def update_svn(self) -> bool:
438 revno = self.wrap.get('revision')
439 _, out, _ = Popen_safe(['svn', 'info', '--show-item', 'revision', self.repo_dir])
440 current_revno = out
441 if current_revno == revno:
442 return True
443 if revno.lower() == 'head':
444 # Failure to do pull is not a fatal error,
445 # because otherwise you can't develop without
446 # a working net connection.
447 subprocess.call(['svn', 'update'], cwd=self.repo_dir)
448 else:
449 subprocess.check_call(['svn', 'update', '-r', revno], cwd=self.repo_dir)
450 return True
451
452 def update(self) -> bool:
453 self.log(f'Updating {self.wrap.name}...')
454 success = False
455 if not os.path.isdir(self.repo_dir):
456 self.log(' -> Not used.')
457 # It is not an error if we are updating all subprojects.
458 success = not self.options.subprojects
459 elif self.wrap.type == 'file':
460 success = self.update_file()
461 elif self.wrap.type == 'git':
462 success = self.update_git()
463 elif self.wrap.type == 'hg':
464 success = self.update_hg()
465 elif self.wrap.type == 'svn':
466 success = self.update_svn()
467 elif self.wrap.type is None:
468 self.log(' -> Cannot update subproject with no wrap file')
469 # It is not an error if we are updating all subprojects.
470 success = not self.options.subprojects
471 else:
472 self.log(' -> Cannot update', self.wrap.type, 'subproject')
473 if success and os.path.isdir(self.repo_dir):
474 self.wrap.update_hash_cache(self.repo_dir)
475 return success
476
477 def checkout(self) -> bool:
478 options = T.cast('CheckoutArguments', self.options)
479
480 if self.wrap.type != 'git' or not os.path.isdir(self.repo_dir):
481 return True
482 branch_name = options.branch_name if options.branch_name else self.wrap.get('revision')
483 if not branch_name:
484 # It could be a detached git submodule for example.
485 return True
486 self.log(f'Checkout {branch_name} in {self.wrap.name}...')
487 if self.git_checkout(branch_name, create=options.b):
488 self.git_show()
489 return True
490 return False
491
492 def download(self) -> bool:
493 self.log(f'Download {self.wrap.name}...')
494 if os.path.isdir(self.repo_dir):
495 self.log(' -> Already downloaded')
496 return True
497 try:
498 self.wrap_resolver.resolve(self.wrap.name)
499 self.log(' -> done')
500 except WrapException as e:
501 self.log(' ->', mlog.red(str(e)))
502 return False
503 return True
504
505 def foreach(self) -> bool:
506 options = T.cast('ForeachArguments', self.options)
507
508 self.log(f'Executing command in {self.repo_dir}')
509 if not os.path.isdir(self.repo_dir):
510 self.log(' -> Not downloaded yet')
511 return True
512 cmd = [options.command] + options.args
513 p, out, _ = Popen_safe(cmd, stderr=subprocess.STDOUT, cwd=self.repo_dir)
514 if p.returncode != 0:
515 err_message = "Command '{}' returned non-zero exit status {}.".format(" ".join(cmd), p.returncode)
516 self.log(' -> ', mlog.red(err_message))
517 self.log(out, end='')
518 return False
519
520 self.log(out, end='')
521 return True
522
523 def purge(self) -> bool:
524 options = T.cast('PurgeArguments', self.options)
525
526 # if subproject is not wrap-based, then don't remove it
527 if not self.wrap.type:
528 return True
529
530 if self.wrap.redirected:
531 wrapfile = Path(self.wrap.original_filename).resolve()
532 if options.confirm:
533 wrapfile.unlink()
534 mlog.log(f'Deleting {wrapfile}')
535
536 if options.include_cache:
537 packagecache = Path(self.wrap_resolver.cachedir).resolve()
538 try:
539 subproject_cache_file = packagecache / self.wrap.get("source_filename")
540 if subproject_cache_file.is_file():
541 if options.confirm:
542 subproject_cache_file.unlink()
543 self.log(f'Deleting {subproject_cache_file}')
544 except WrapException:
545 pass
546
547 try:
548 subproject_patch_file = packagecache / self.wrap.get("patch_filename")
549 if subproject_patch_file.is_file():
550 if options.confirm:
551 subproject_patch_file.unlink()
552 self.log(f'Deleting {subproject_patch_file}')
553 except WrapException:
554 pass
555
556 # Don't log that we will remove an empty directory. Since purge is
557 # parallelized, another thread could have deleted it already.
558 try:
559 if not any(packagecache.iterdir()):
560 windows_proof_rmtree(str(packagecache))
561 except FileNotFoundError:
562 pass
563
564 # NOTE: Do not use .resolve() here; the subproject directory may be a symlink
565 subproject_source_dir = Path(self.repo_dir)
566 # Resolve just the parent, just to print out the full path
567 subproject_source_dir = subproject_source_dir.parent.resolve() / subproject_source_dir.name
568
569 # Don't follow symlink. This is covered by the next if statement, but why
570 # not be doubly sure.
571 if subproject_source_dir.is_symlink():
572 if options.confirm:
573 subproject_source_dir.unlink()
574 self.log(f'Deleting {subproject_source_dir}')
575 return True
576 if not subproject_source_dir.is_dir():
577 return True
578
579 try:
580 if options.confirm:
581 windows_proof_rmtree(str(subproject_source_dir))
582 self.log(f'Deleting {subproject_source_dir}')
583 except OSError as e:
584 mlog.error(f'Unable to remove: {subproject_source_dir}: {e}')
585 return False
586
587 return True
588
589 @staticmethod
590 def post_purge(options: 'PurgeArguments') -> None:
591 if not options.confirm:
592 mlog.log('')
593 mlog.log('Nothing has been deleted, run again with --confirm to apply.')
594
595 def packagefiles(self) -> bool:
596 options = T.cast('PackagefilesArguments', self.options)
597
598 if options.apply and options.save:
599 # not quite so nice as argparse failure
600 print('error: --apply and --save are mutually exclusive')
601 return False
602 if options.apply:
603 self.log(f'Re-applying patchfiles overlay for {self.wrap.name}...')
604 if not os.path.isdir(self.repo_dir):
605 self.log(' -> Not downloaded yet')
606 return True
607 self.wrap_resolver.apply_patch(self.wrap.name)
608 return True
609 if options.save:
610 if 'patch_directory' not in self.wrap.values:
611 mlog.error('can only save packagefiles to patch_directory')
612 return False
613 if 'source_filename' not in self.wrap.values:
614 mlog.error('can only save packagefiles from a [wrap-file]')
615 return False
616 archive_path = Path(self.wrap_resolver.cachedir, self.wrap.values['source_filename'])
617 lead_directory_missing = bool(self.wrap.values.get('lead_directory_missing', False))
618 directory = Path(self.repo_dir)
619 packagefiles = Path(self.wrap.filesdir, self.wrap.values['patch_directory'])
620
621 base_path = directory if lead_directory_missing else directory.parent
622 archive_files = read_archive_files(archive_path, base_path)
623 directory_files = set(directory.glob('**/*'))
624
625 self.log(f'Saving {self.wrap.name} to {packagefiles}...')
626 shutil.rmtree(packagefiles)
627 for src_path in directory_files - archive_files:
628 if not src_path.is_file():
629 continue
630 rel_path = src_path.relative_to(directory)
631 dst_path = packagefiles / rel_path
632 dst_path.parent.mkdir(parents=True, exist_ok=True)
633 shutil.copyfile(src_path, dst_path)
634 return True
635
636
637 def add_common_arguments(p: argparse.ArgumentParser) -> None:
638 p.add_argument('--sourcedir', default='.',
639 help='Path to source directory')
640 p.add_argument('--types', default='',
641 help=f'Comma-separated list of subproject types. Supported types are: {ALL_TYPES_STRING} (default: all)')
642 p.add_argument('-j', '--num-processes', default=None, type=int,
643 help='How many parallel processes to use (Since 0.59.0).')
644 p.add_argument('--allow-insecure', default=False, action='store_true',
645 help='Allow insecure server connections.')
646
647 def add_subprojects_argument(p: argparse.ArgumentParser, name: str = None) -> None:
648 helpstr = 'Patterns of subprojects to operate on (default: all)'
649 if name:
650 p.add_argument(name, dest='subprojects', metavar='pattern', nargs=1, action='append',
651 default=[], help=helpstr)
652 else:
653 p.add_argument('subprojects', metavar='pattern', nargs='*', default=[],
654 help=helpstr)
655
656 def add_wrap_update_parser(subparsers: 'SubParsers') -> argparse.ArgumentParser:
657 p = subparsers.add_parser('update', help='Update wrap files from WrapDB (Since 0.63.0)')
658 p.add_argument('--force', default=False, action='store_true',
659 help='Update wraps that does not seems to come from WrapDB')
660 add_common_arguments(p)
661 add_subprojects_argument(p)
662 p.set_defaults(subprojects_func=Runner.update_wrapdb)
663 p.set_defaults(pre_func=Runner.pre_update_wrapdb)
664 return p
665
666 # Note: when adding arguments, please also add them to the completion
667 # scripts in $MESONSRC/data/shell-completions/
668 def add_arguments(parser: argparse.ArgumentParser) -> None:
669 subparsers = parser.add_subparsers(title='Commands', dest='command')
670 subparsers.required = True
671
672 p = subparsers.add_parser('update', help='Update all subprojects from wrap files')
673 p.add_argument('--rebase', default=True, action='store_true',
674 help='Rebase your branch on top of wrap\'s revision. ' +
675 'Deprecated, it is now the default behaviour. (git only)')
676 p.add_argument('--reset', default=False, action='store_true',
677 help='Checkout wrap\'s revision and hard reset to that commit. (git only)')
678 add_common_arguments(p)
679 add_subprojects_argument(p)
680 p.set_defaults(subprojects_func=Runner.update)
681
682 p = subparsers.add_parser('checkout', help='Checkout a branch (git only)')
683 p.add_argument('-b', default=False, action='store_true',
684 help='Create a new branch')
685 p.add_argument('branch_name', nargs='?',
686 help='Name of the branch to checkout or create (default: revision set in wrap file)')
687 add_common_arguments(p)
688 add_subprojects_argument(p)
689 p.set_defaults(subprojects_func=Runner.checkout)
690
691 p = subparsers.add_parser('download', help='Ensure subprojects are fetched, even if not in use. ' +
692 'Already downloaded subprojects are not modified. ' +
693 'This can be used to pre-fetch all subprojects and avoid downloads during configure.')
694 add_common_arguments(p)
695 add_subprojects_argument(p)
696 p.set_defaults(subprojects_func=Runner.download)
697
698 p = subparsers.add_parser('foreach', help='Execute a command in each subproject directory.')
699 p.add_argument('command', metavar='command ...',
700 help='Command to execute in each subproject directory')
701 p.add_argument('args', nargs=argparse.REMAINDER,
702 help=argparse.SUPPRESS)
703 add_common_arguments(p)
704 add_subprojects_argument(p, '--filter')
705 p.set_defaults(subprojects_func=Runner.foreach)
706
707 p = subparsers.add_parser('purge', help='Remove all wrap-based subproject artifacts')
708 add_common_arguments(p)
709 add_subprojects_argument(p)
710 p.add_argument('--include-cache', action='store_true', default=False, help='Remove the package cache as well')
711 p.add_argument('--confirm', action='store_true', default=False, help='Confirm the removal of subproject artifacts')
712 p.set_defaults(subprojects_func=Runner.purge)
713 p.set_defaults(post_func=Runner.post_purge)
714
715 p = subparsers.add_parser('packagefiles', help='Manage the packagefiles overlay')
716 add_common_arguments(p)
717 add_subprojects_argument(p)
718 p.add_argument('--apply', action='store_true', default=False, help='Apply packagefiles to the subproject')
719 p.add_argument('--save', action='store_true', default=False, help='Save packagefiles from the subproject')
720 p.set_defaults(subprojects_func=Runner.packagefiles)
721
722 def run(options: 'Arguments') -> int:
723 source_dir = os.path.relpath(os.path.realpath(options.sourcedir))
724 if not os.path.isfile(os.path.join(source_dir, 'meson.build')):
725 mlog.error('Directory', mlog.bold(source_dir), 'does not seem to be a Meson source directory.')
726 return 1
727 with mlog.no_logging():
728 intr = IntrospectionInterpreter(source_dir, '', 'none')
729 intr.load_root_meson_file()
730 subproject_dir = intr.extract_subproject_dir() or 'subprojects'
731 if not os.path.isdir(os.path.join(source_dir, subproject_dir)):
732 mlog.log('Directory', mlog.bold(source_dir), 'does not seem to have subprojects.')
733 return 0
734 r = Resolver(source_dir, subproject_dir, wrap_frontend=True, allow_insecure=options.allow_insecure, silent=True)
735 if options.subprojects:
736 wraps = [wrap for name, wrap in r.wraps.items()
737 if any(fnmatch.fnmatch(name, pat) for pat in options.subprojects)]
738 else:
739 wraps = list(r.wraps.values())
740 types = [t.strip() for t in options.types.split(',')] if options.types else []
741 for t in types:
742 if t not in tuple(WrapType):
743 raise MesonException(f'Unknown subproject type {t!r}, supported types are: {ALL_TYPES_STRING}')
744 tasks: T.List[T.Awaitable[bool]] = []
745 task_names: T.List[str] = []
746 loop = asyncio.new_event_loop()
747 asyncio.set_event_loop(loop)
748 executor = ThreadPoolExecutor(options.num_processes)
749 if types:
750 wraps = [wrap for wrap in wraps if wrap.type in types]
751 pre_func = getattr(options, 'pre_func', None)
752 if pre_func:
753 pre_func(options)
754 logger = Logger(len(wraps))
755 for wrap in wraps:
756 dirname = Path(source_dir, subproject_dir, wrap.directory).as_posix()
757 runner = Runner(logger, r, wrap, dirname, options)
758 task = loop.run_in_executor(executor, runner.run)
759 tasks.append(task)
760 task_names.append(wrap.name)
761 results = loop.run_until_complete(asyncio.gather(*tasks))
762 logger.flush()
763 post_func = getattr(options, 'post_func', None)
764 if post_func:
765 post_func(options)
766 failures = [name for name, success in zip(task_names, results) if not success]
767 if failures:
768 m = 'Please check logs above as command failed in some subprojects which could have been left in conflict state: '
769 m += ', '.join(failures)
770 mlog.warning(m)
771 return len(failures)