Debian Codegraph @

mesonbuild/scripts/run_tool.py

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