| 1 |
# SPDX-License-Identifier: Apache-2.0 |
| 2 |
# Copyright 2018 The Meson development team |
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
import asyncio.subprocess |
| 7 |
import fnmatch |
| 8 |
import itertools |
| 9 |
import json |
| 10 |
import signal |
| 11 |
import sys |
| 12 |
from pathlib import Path |
| 13 |
|
| 14 |
from .. import mlog |
| 15 |
from ..compilers import lang_suffixes |
| 16 |
from ..mesonlib import quiet_git, join_args, determine_worker_count |
| 17 |
from ..mtest import complete_all |
| 18 |
import typing as T |
| 19 |
|
| 20 |
Info = T.TypeVar("Info") |
| 21 |
|
| 22 |
async def run_with_buffered_output(cmdlist: T.List[str], env: T.Optional[T.Dict[str, str]] = None) -> int: |
| 23 |
"""Run the command in cmdlist, buffering the output so that it is |
| 24 |
not mixed for multiple child processes. Kill the child on |
| 25 |
cancellation.""" |
| 26 |
quoted_cmdline = join_args(cmdlist) |
| 27 |
p: T.Optional[asyncio.subprocess.Process] = None |
| 28 |
try: |
| 29 |
p = await asyncio.create_subprocess_exec(*cmdlist, env=env, |
| 30 |
stdin=asyncio.subprocess.DEVNULL, |
| 31 |
stdout=asyncio.subprocess.PIPE, |
| 32 |
stderr=asyncio.subprocess.STDOUT) |
| 33 |
stdo, _ = await p.communicate() |
| 34 |
except FileNotFoundError as e: |
| 35 |
print(mlog.blue('>>>'), quoted_cmdline, file=sys.stderr) |
| 36 |
print(mlog.red('not found:'), e.filename, file=sys.stderr) |
| 37 |
return 1 |
| 38 |
except asyncio.CancelledError: |
| 39 |
if p: |
| 40 |
p.kill() |
| 41 |
await p.wait() |
| 42 |
return p.returncode or 1 |
| 43 |
else: |
| 44 |
return 0 |
| 45 |
|
| 46 |
if stdo: |
| 47 |
print(mlog.blue('>>>'), quoted_cmdline, flush=True) |
| 48 |
sys.stdout.buffer.write(stdo) |
| 49 |
return p.returncode |
| 50 |
|
| 51 |
async def _run_workers(infos: T.Iterable[Info], |
| 52 |
fn: T.Callable[[Info], T.Iterable[T.Coroutine[None, None, int]]]) -> int: |
| 53 |
futures: T.List[asyncio.Future[int]] = [] |
| 54 |
semaphore = asyncio.Semaphore(determine_worker_count()) |
| 55 |
|
| 56 |
async def run_one(worker_coro: T.Coroutine[None, None, int]) -> int: |
| 57 |
try: |
| 58 |
async with semaphore: |
| 59 |
return await worker_coro |
| 60 |
except asyncio.CancelledError as e: |
| 61 |
worker_coro.throw(e) |
| 62 |
return await worker_coro |
| 63 |
|
| 64 |
def sigterm_handler() -> None: |
| 65 |
for f in futures: |
| 66 |
f.cancel() |
| 67 |
|
| 68 |
if sys.platform != 'win32': |
| 69 |
loop = asyncio.get_running_loop() |
| 70 |
loop.add_signal_handler(signal.SIGINT, sigterm_handler) |
| 71 |
loop.add_signal_handler(signal.SIGTERM, sigterm_handler) |
| 72 |
|
| 73 |
for i in infos: |
| 74 |
futures.extend((asyncio.ensure_future(run_one(x)) for x in fn(i))) |
| 75 |
if not futures: |
| 76 |
return 0 |
| 77 |
|
| 78 |
try: |
| 79 |
await complete_all(futures) |
| 80 |
except BaseException: |
| 81 |
for f in futures: |
| 82 |
f.cancel() |
| 83 |
raise |
| 84 |
|
| 85 |
return max(f.result() for f in futures if f.done() and not f.cancelled()) |
| 86 |
|
| 87 |
def parse_pattern_file(fname: Path) -> T.List[str]: |
| 88 |
patterns = [] |
| 89 |
try: |
| 90 |
with fname.open(encoding='utf-8') as f: |
| 91 |
for line in f: |
| 92 |
pattern = line.strip() |
| 93 |
if pattern and not pattern.startswith('#'): |
| 94 |
patterns.append(pattern) |
| 95 |
except FileNotFoundError: |
| 96 |
pass |
| 97 |
return patterns |
| 98 |
|
| 99 |
def all_clike_files(name: str, srcdir: Path, builddir: Path) -> T.Iterable[Path]: |
| 100 |
patterns = parse_pattern_file(srcdir / f'.{name}-include') |
| 101 |
globs: T.Sequence[T.Union[T.List[Path], T.Iterator[Path], T.Generator[Path, None, None]]] |
| 102 |
if patterns: |
| 103 |
globs = [srcdir.glob(p) for p in patterns] |
| 104 |
else: |
| 105 |
r, o = quiet_git(['ls-files'], srcdir) |
| 106 |
if r: |
| 107 |
globs = [[Path(srcdir, f) for f in o.splitlines()]] |
| 108 |
else: |
| 109 |
globs = [srcdir.glob('**/*')] |
| 110 |
patterns = parse_pattern_file(srcdir / f'.{name}-ignore') |
| 111 |
ignore = [str(builddir / '*')] |
| 112 |
ignore.extend([str(srcdir / p) for p in patterns]) |
| 113 |
suffixes = set(lang_suffixes['c']).union(set(lang_suffixes['cpp'])) |
| 114 |
suffixes.add('h') |
| 115 |
suffixes = {f'.{s}' for s in suffixes} |
| 116 |
for f in itertools.chain.from_iterable(globs): |
| 117 |
strf = str(f) |
| 118 |
if f.is_dir() or f.suffix not in suffixes or \ |
| 119 |
any(fnmatch.fnmatch(strf, i) for i in ignore): |
| 120 |
continue |
| 121 |
yield f |
| 122 |
|
| 123 |
def run_clang_tool(name: str, srcdir: Path, builddir: Path, fn: T.Callable[..., T.Coroutine[None, None, int]], *args: T.Any) -> int: |
| 124 |
if sys.platform == 'win32' and sys.version_info < (3, 8): |
| 125 |
asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) |
| 126 |
|
| 127 |
def wrapper(path: Path) -> T.Iterable[T.Coroutine[None, None, int]]: |
| 128 |
yield fn(path, *args) |
| 129 |
return asyncio.run(_run_workers(all_clike_files(name, srcdir, builddir), wrapper)) |
| 130 |
|
| 131 |
def run_clang_tool_on_sources(name: str, srcdir: Path, builddir: Path, fn: T.Callable[..., T.Coroutine[None, None, int]], *args: T.Any) -> int: |
| 132 |
if sys.platform == 'win32' and sys.version_info < (3, 8): |
| 133 |
asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) |
| 134 |
|
| 135 |
source_files = set() |
| 136 |
with open('meson-info/intro-targets.json', encoding='utf-8') as fp: |
| 137 |
targets = json.load(fp) |
| 138 |
|
| 139 |
for target in targets: |
| 140 |
for target_source in target.get('target_sources') or []: |
| 141 |
for source in target_source.get('sources') or []: |
| 142 |
source_files.add(Path(source)) |
| 143 |
|
| 144 |
clike_files = set(all_clike_files(name, srcdir, builddir)) |
| 145 |
source_files = source_files.intersection(clike_files) |
| 146 |
|
| 147 |
def wrapper(path: Path) -> T.Iterable[T.Coroutine[None, None, int]]: |
| 148 |
yield fn(path, *args) |
| 149 |
return asyncio.run(_run_workers(source_files, wrapper)) |
| 150 |
|
| 151 |
def run_tool_on_targets(fn: T.Callable[[T.Dict[str, T.Any]], |
| 152 |
T.Iterable[T.Coroutine[None, None, int]]]) -> int: |
| 153 |
if sys.platform == 'win32' and sys.version_info < (3, 8): |
| 154 |
asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) |
| 155 |
|
| 156 |
with open('meson-info/intro-targets.json', encoding='utf-8') as fp: |
| 157 |
targets = json.load(fp) |
| 158 |
return asyncio.run(_run_workers(targets, fn)) |