Debian Codegraph @

mesonbuild/mlog.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2013-2014 The Meson development team
3
4 """This is (mostly) a standalone module used to write logging
5 information about Meson runs. Some output goes to screen,
6 some to logging dir and some goes to both."""
7
8 from __future__ import annotations
9
10 import enum
11 import os
12 import io
13 import sys
14 import time
15 import platform
16 import shlex
17 import subprocess
18 import shutil
19 import typing as T
20 from contextlib import contextmanager
21 from dataclasses import dataclass, field
22 from pathlib import Path
23
24 if T.TYPE_CHECKING:
25 from typing_extensions import Literal
26
27 from ._typing import StringProtocol, SizedStringProtocol
28 from .mparser import BaseNode
29
30 TV_Loggable = T.Union[str, 'AnsiDecorator', StringProtocol]
31 TV_LoggableList = T.List[TV_Loggable]
32
33 def is_windows() -> bool:
34 platname = platform.system().lower()
35 return platname == 'windows'
36
37 def _windows_ansi() -> bool:
38 # windll only exists on windows, so mypy will get mad
39 from ctypes import windll, byref # type: ignore
40 from ctypes.wintypes import DWORD
41
42 kernel = windll.kernel32
43 stdout = kernel.GetStdHandle(-11)
44 mode = DWORD()
45 if not kernel.GetConsoleMode(stdout, byref(mode)):
46 return False
47 # ENABLE_VIRTUAL_TERMINAL_PROCESSING == 0x4
48 # If the call to enable VT processing fails (returns 0), we fallback to
49 # original behavior
50 return bool(kernel.SetConsoleMode(stdout, mode.value | 0x4) or os.environ.get('ANSICON'))
51
52 _in_ci = 'CI' in os.environ
53 _ci_is_github = 'GITHUB_ACTIONS' in os.environ
54
55
56 class _Severity(enum.Enum):
57
58 NOTICE = enum.auto()
59 WARNING = enum.auto()
60 ERROR = enum.auto()
61 DEPRECATION = enum.auto()
62
63 @dataclass
64 class _Logger:
65
66 log_dir: T.Optional[str] = None
67 log_depth: T.List[str] = field(default_factory=list)
68 log_to_stderr: bool = False
69 log_file: T.Optional[T.TextIO] = None
70 slog_file: T.Optional[T.TextIO] = None
71 log_timestamp_start: T.Optional[float] = None
72 log_fatal_warnings = False
73 log_disable_stdout = False
74 log_errors_only = False
75 logged_once: T.Set[T.Tuple[str, ...]] = field(default_factory=set)
76 log_warnings_counter = 0
77 log_pager: T.Optional['subprocess.Popen'] = None
78
79 _LOG_FNAME: T.ClassVar[str] = 'meson-log.txt'
80 _SLOG_FNAME: T.ClassVar[str] = 'meson-setup.txt'
81
82 @contextmanager
83 def no_logging(self) -> T.Iterator[None]:
84 self.log_disable_stdout = True
85 try:
86 yield
87 finally:
88 self.log_disable_stdout = False
89
90 @contextmanager
91 def force_logging(self) -> T.Iterator[None]:
92 restore = self.log_disable_stdout
93 self.log_disable_stdout = False
94 try:
95 yield
96 finally:
97 self.log_disable_stdout = restore
98
99 def set_quiet(self) -> None:
100 self.log_errors_only = True
101
102 def set_verbose(self) -> None:
103 self.log_errors_only = False
104
105 def set_timestamp_start(self, start: float) -> None:
106 self.log_timestamp_start = start
107
108 def shutdown(self) -> T.Optional[str]:
109 if self.log_file is not None:
110 path = self.log_file.name
111 exception_around_goer = self.log_file
112 self.log_file = None
113 exception_around_goer.close()
114 return path
115 if self.slog_file is not None:
116 path = self.slog_file.name
117 exception_around_goer = self.slog_file
118 self.slog_file = None
119 exception_around_goer.close()
120 return path
121 self.stop_pager()
122 return None
123
124 def start_pager(self) -> None:
125 if not self.colorize_console():
126 return
127 pager_cmd = []
128 if 'PAGER' in os.environ:
129 pager_cmd = shlex.split(os.environ['PAGER'])
130 else:
131 less = shutil.which('less')
132 if not less and is_windows():
133 git = shutil.which('git')
134 if git:
135 path = Path(git).parents[1] / 'usr' / 'bin'
136 less = shutil.which('less', path=str(path))
137 if less:
138 pager_cmd = [less]
139 if not pager_cmd:
140 return
141 try:
142 # Set 'LESS' environment variable, rather than arguments in
143 # pager_cmd, to also support the case where the user has 'PAGER'
144 # set to 'less'. Arguments set are:
145 # "R" : support color
146 # "X" : do not clear the screen when leaving the pager
147 # "F" : skip the pager if content fits into the screen
148 env = os.environ.copy()
149 if 'LESS' not in env:
150 env['LESS'] = 'RXF'
151 # Set "-c" for lv to support color
152 if 'LV' not in env:
153 env['LV'] = '-c'
154 self.log_pager = subprocess.Popen(pager_cmd, stdin=subprocess.PIPE,
155 text=True, encoding='utf-8', env=env)
156 except Exception as e:
157 # Ignore errors, unless it is a user defined pager.
158 if 'PAGER' in os.environ:
159 from .mesonlib import MesonException
160 raise MesonException(f'Failed to start pager: {str(e)}')
161
162 def stop_pager(self) -> None:
163 if self.log_pager and (stdin := self.log_pager.stdin) is not None:
164 try:
165 stdin.flush()
166 stdin.close()
167 except OSError:
168 pass
169 self.log_pager.wait()
170 self.log_pager = None
171
172 def initialize(self, logdir: str, fatal_warnings: bool = False) -> None:
173 self.log_dir = logdir
174 self.log_file = open(os.path.join(logdir, self._LOG_FNAME), 'w', encoding='utf-8')
175 self.slog_file = open(os.path.join(logdir, self._SLOG_FNAME), 'w', encoding='utf-8')
176 self.log_fatal_warnings = fatal_warnings
177
178 def process_markup(self, args: T.Sequence[TV_Loggable], keep: bool, display_timestamp: bool = True) -> T.List[str]:
179 arr: T.List[str] = []
180 if self.log_timestamp_start is not None and display_timestamp:
181 arr = ['[{:.3f}]'.format(time.monotonic() - self.log_timestamp_start)]
182 for arg in args:
183 if arg is None:
184 continue
185 if isinstance(arg, str):
186 arr.append(arg)
187 elif isinstance(arg, AnsiDecorator):
188 arr.append(arg.get_text(keep))
189 else:
190 arr.append(str(arg))
191 return arr
192
193 def force_print(self, *args: str, nested: bool, sep: T.Optional[str] = None,
194 end: T.Optional[str] = None) -> None:
195 if self.log_disable_stdout:
196 return
197 iostr = io.StringIO()
198 print(*args, sep=sep, end=end, file=iostr)
199
200 raw = iostr.getvalue()
201 if self.log_depth:
202 prepend = self.log_depth[-1] + '| ' if nested else ''
203 lines = []
204 for l in raw.split('\n'):
205 l = l.strip()
206 lines.append(prepend + l if l else '')
207 raw = '\n'.join(lines)
208
209 # _Something_ is going to get printed.
210 if self.log_pager:
211 output = self.log_pager.stdin
212 elif self.log_to_stderr:
213 output = sys.stderr
214 else:
215 output = sys.stdout
216 try:
217 print(raw, end='', file=output)
218 except UnicodeEncodeError:
219 cleaned = raw.encode('ascii', 'replace').decode('ascii')
220 print(cleaned, end='', file=output)
221
222 def debug(self, *args: TV_Loggable, sep: T.Optional[str] = None,
223 end: T.Optional[str] = None, display_timestamp: bool = True) -> None:
224 arr = process_markup(args, False, display_timestamp)
225 if self.log_file is not None:
226 print(*arr, file=self.log_file, sep=sep, end=end)
227 self.log_file.flush()
228
229 def _log(self, *args: TV_Loggable, is_error: bool = False,
230 nested: bool = True, sep: T.Optional[str] = None,
231 end: T.Optional[str] = None, display_timestamp: bool = True) -> None:
232 arr = process_markup(args, False, display_timestamp)
233 if self.log_file is not None:
234 print(*arr, file=self.log_file, sep=sep, end=end)
235 self.log_file.flush()
236 if self.slog_file is not None:
237 print(*arr, file=self.slog_file, sep=sep, end=end)
238 self.slog_file.flush()
239 if self.colorize_console():
240 arr = process_markup(args, True, display_timestamp)
241 if not self.log_errors_only or is_error:
242 force_print(*arr, nested=nested, sep=sep, end=end)
243
244 def _debug_log_cmd(self, cmd: str, args: T.List[str]) -> None:
245 if not _in_ci:
246 return
247 args = [f'"{x}"' for x in args] # Quote all args, just in case
248 self.debug('!meson_ci!/{} {}'.format(cmd, ' '.join(args)))
249
250 def cmd_ci_include(self, file: str) -> None:
251 self._debug_log_cmd('ci_include', [file])
252
253 def log(self, *args: TV_Loggable, is_error: bool = False,
254 once: bool = False, nested: bool = True,
255 sep: T.Optional[str] = None,
256 end: T.Optional[str] = None,
257 display_timestamp: bool = True) -> None:
258 if self._should_log(*args, once=once):
259 self._log(*args, is_error=is_error, nested=nested, sep=sep, end=end, display_timestamp=display_timestamp)
260
261 def log_timestamp(self, *args: TV_Loggable) -> None:
262 if self.log_timestamp_start:
263 self.log(*args)
264
265 def _should_log(self, *args: TV_Loggable, once: bool) -> bool:
266 def to_str(x: TV_Loggable) -> str:
267 if isinstance(x, str):
268 return x
269 if isinstance(x, AnsiDecorator):
270 return x.text
271 return str(x)
272 if not once:
273 return True
274 t = tuple(to_str(a) for a in args)
275 if t in self.logged_once:
276 return False
277 self.logged_once.add(t)
278 return True
279
280 def _log_error(self, severity: _Severity, *rargs: TV_Loggable,
281 once: bool = False, fatal: bool = True,
282 location: T.Optional[BaseNode] = None,
283 nested: bool = True, sep: T.Optional[str] = None,
284 end: T.Optional[str] = None,
285 is_error: bool = True) -> None:
286 from .mesonlib import MesonException, relpath
287
288 # The typing requirements here are non-obvious. Lists are invariant,
289 # therefore T.List[A] and T.List[T.Union[A, B]] are not able to be joined
290 if severity is _Severity.NOTICE:
291 label: TV_LoggableList = [bold('NOTICE:')]
292 elif severity is _Severity.WARNING:
293 label = [yellow('WARNING:')]
294 elif severity is _Severity.ERROR:
295 label = [red('ERROR:')]
296 elif severity is _Severity.DEPRECATION:
297 label = [red('DEPRECATION:')]
298 # rargs is a tuple, not a list
299 args = label + list(rargs)
300
301 if not self._should_log(*args, once=once):
302 return
303
304 if location is not None:
305 location_file = relpath(location.filename, os.getcwd())
306 location_str = get_error_location_string(location_file, location.lineno)
307 # Unions are frankly awful, and we have to T.cast here to get mypy
308 # to understand that the list concatenation is safe
309 location_list = T.cast('TV_LoggableList', [location_str])
310 args = location_list + args
311
312 self._log(*args, nested=nested, sep=sep, end=end, is_error=is_error)
313
314 self.log_warnings_counter += 1
315
316 if self.log_fatal_warnings and fatal:
317 raise MesonException("Fatal warnings enabled, aborting")
318
319 def error(self, *args: TV_Loggable,
320 once: bool = False, fatal: bool = True,
321 location: T.Optional[BaseNode] = None,
322 nested: bool = True, sep: T.Optional[str] = None,
323 end: T.Optional[str] = None) -> None:
324 return self._log_error(_Severity.ERROR, *args, once=once, fatal=fatal, location=location,
325 nested=nested, sep=sep, end=end, is_error=True)
326
327 def warning(self, *args: TV_Loggable,
328 once: bool = False, fatal: bool = True,
329 location: T.Optional[BaseNode] = None,
330 nested: bool = True, sep: T.Optional[str] = None,
331 end: T.Optional[str] = None) -> None:
332 return self._log_error(_Severity.WARNING, *args, once=once, fatal=fatal, location=location,
333 nested=nested, sep=sep, end=end, is_error=True)
334
335 def deprecation(self, *args: TV_Loggable,
336 once: bool = False, fatal: bool = True,
337 location: T.Optional[BaseNode] = None,
338 nested: bool = True, sep: T.Optional[str] = None,
339 end: T.Optional[str] = None) -> None:
340 return self._log_error(_Severity.DEPRECATION, *args, once=once, fatal=fatal, location=location,
341 nested=nested, sep=sep, end=end, is_error=True)
342
343 def notice(self, *args: TV_Loggable,
344 once: bool = False, fatal: bool = True,
345 location: T.Optional[BaseNode] = None,
346 nested: bool = True, sep: T.Optional[str] = None,
347 end: T.Optional[str] = None) -> None:
348 return self._log_error(_Severity.NOTICE, *args, once=once, fatal=fatal, location=location,
349 nested=nested, sep=sep, end=end, is_error=False)
350
351 def exception(self, e: Exception, prefix: T.Optional[AnsiDecorator] = None) -> None:
352 if prefix is None:
353 prefix = red('ERROR:')
354 self.log()
355 args: T.List[T.Union[AnsiDecorator, str]] = []
356 if all(getattr(e, a, None) is not None for a in ['file', 'lineno', 'colno']):
357 # Mypy doesn't follow hasattr, and it's pretty easy to visually inspect
358 # that this is correct, so we'll just ignore it.
359 path = get_relative_path(Path(e.file), Path(os.getcwd())) # type: ignore
360 args.append(f'{path}:{e.lineno}:{e.colno}:') # type: ignore
361 if prefix:
362 args.append(prefix)
363 args.append(str(e))
364
365 with self.force_logging():
366 self.log(*args, is_error=True)
367
368 @contextmanager
369 def nested(self, name: str = '') -> T.Generator[None, None, None]:
370 self.log_depth.append(name)
371 try:
372 yield
373 finally:
374 self.log_depth.pop()
375
376 def get_log_dir(self) -> str:
377 assert self.log_dir is not None, 'attempted to use logger without initializing'
378 return self.log_dir
379
380 def get_log_depth(self) -> int:
381 return len(self.log_depth)
382
383 @contextmanager
384 def nested_warnings(self) -> T.Iterator[None]:
385 old = self.log_warnings_counter
386 self.log_warnings_counter = 0
387 try:
388 yield
389 finally:
390 self.log_warnings_counter = old
391
392 def get_warning_count(self) -> int:
393 return self.log_warnings_counter
394
395 def redirect(self, to_stderr: bool) -> None:
396 self.log_to_stderr = to_stderr
397
398 def colorize_console(self) -> bool:
399 output = sys.stderr if self.log_to_stderr else sys.stdout
400 _colorize_console: bool | None = getattr(output, 'colorize_console', None)
401 if _colorize_console is not None:
402 return _colorize_console
403 try:
404 if is_windows():
405 _colorize_console = os.isatty(output.fileno()) and _windows_ansi()
406 else:
407 _colorize_console = os.isatty(output.fileno()) and os.environ.get('TERM', 'dumb') != 'dumb'
408 except Exception:
409 _colorize_console = False
410 output.colorize_console = _colorize_console # type: ignore
411 return _colorize_console
412
413 def setup_console(self) -> None:
414 # on Windows, a subprocess might call SetConsoleMode() on the console
415 # connected to stdout and turn off ANSI escape processing. Call this after
416 # running a subprocess to ensure we turn it on again.
417 output = sys.stderr if self.log_to_stderr else sys.stdout
418 if is_windows():
419 try:
420 delattr(output, 'colorize_console')
421 except AttributeError:
422 pass
423
424 _logger = _Logger()
425 cmd_ci_include = _logger.cmd_ci_include
426 colorize_console = _logger.colorize_console
427 debug = _logger.debug
428 deprecation = _logger.deprecation
429 error = _logger.error
430 exception = _logger.exception
431 force_print = _logger.force_print
432 get_log_depth = _logger.get_log_depth
433 get_log_dir = _logger.get_log_dir
434 get_warning_count = _logger.get_warning_count
435 initialize = _logger.initialize
436 log = _logger.log
437 log_timestamp = _logger.log_timestamp
438 nested = _logger.nested
439 nested_warnings = _logger.nested_warnings
440 no_logging = _logger.no_logging
441 notice = _logger.notice
442 process_markup = _logger.process_markup
443 redirect = _logger.redirect
444 set_quiet = _logger.set_quiet
445 set_timestamp_start = _logger.set_timestamp_start
446 set_verbose = _logger.set_verbose
447 setup_console = _logger.setup_console
448 shutdown = _logger.shutdown
449 start_pager = _logger.start_pager
450 stop_pager = _logger.stop_pager
451 warning = _logger.warning
452
453 class AnsiDecorator:
454 plain_code = "\033[0m"
455
456 def __init__(self, text: str, code: str, quoted: bool = False):
457 self.text = text
458 self.code = code
459 self.quoted = quoted
460
461 def get_text(self, with_codes: bool) -> str:
462 text = self.text
463 if with_codes and self.code:
464 text = self.code + self.text + AnsiDecorator.plain_code
465 if self.quoted:
466 text = f'"{text}"'
467 return text
468
469 def __len__(self) -> int:
470 return len(self.text)
471
472 def __str__(self) -> str:
473 return self.get_text(colorize_console())
474
475 class AnsiText:
476 def __init__(self, *args: 'SizedStringProtocol'):
477 self.args = args
478
479 def __len__(self) -> int:
480 return sum(len(x) for x in self.args)
481
482 def __str__(self) -> str:
483 return ''.join(str(x) for x in self.args)
484
485
486 def bold(text: str, quoted: bool = False) -> AnsiDecorator:
487 return AnsiDecorator(text, "\033[1m", quoted=quoted)
488
489 def italic(text: str, quoted: bool = False) -> AnsiDecorator:
490 return AnsiDecorator(text, "\033[3m", quoted=quoted)
491
492 def plain(text: str) -> AnsiDecorator:
493 return AnsiDecorator(text, "")
494
495 def red(text: str) -> AnsiDecorator:
496 return AnsiDecorator(text, "\033[1;31m")
497
498 def green(text: str) -> AnsiDecorator:
499 return AnsiDecorator(text, "\033[1;32m")
500
501 def yellow(text: str) -> AnsiDecorator:
502 return AnsiDecorator(text, "\033[1;33m")
503
504 def blue(text: str) -> AnsiDecorator:
505 return AnsiDecorator(text, "\033[1;34m")
506
507 def cyan(text: str) -> AnsiDecorator:
508 return AnsiDecorator(text, "\033[1;36m")
509
510 def normal_red(text: str) -> AnsiDecorator:
511 return AnsiDecorator(text, "\033[31m")
512
513 def normal_green(text: str) -> AnsiDecorator:
514 return AnsiDecorator(text, "\033[32m")
515
516 def normal_yellow(text: str) -> AnsiDecorator:
517 return AnsiDecorator(text, "\033[33m")
518
519 def normal_blue(text: str) -> AnsiDecorator:
520 return AnsiDecorator(text, "\033[34m")
521
522 def normal_cyan(text: str) -> AnsiDecorator:
523 return AnsiDecorator(text, "\033[36m")
524
525 def get_error_location_string(fname: StringProtocol, lineno: int) -> str:
526 return f'{fname}:{lineno}:'
527
528 def get_relative_path(target: Path, current: Path) -> Path:
529 """Get the path to target from current"""
530 # Go up "current" until we find a common ancestor to target
531 acc = ['.']
532 for part in [current, *current.parents]:
533 try:
534 path = target.relative_to(part)
535 return Path(*acc, path)
536 except ValueError:
537 pass
538 acc += ['..']
539
540 # we failed, should not get here
541 return target
542
543 # Format a list for logging purposes as a string. It separates
544 # all but the last item with commas, and the last with 'and'.
545 def format_list(input_list: T.List[str]) -> str:
546 l = len(input_list)
547 if l > 2:
548 return ' and '.join([', '.join(input_list[:-1]), input_list[-1]])
549 elif l == 2:
550 return ' and '.join(input_list)
551 elif l == 1:
552 return input_list[0]
553 else:
554 return ''
555
556
557 def code_line(text: str, line: str, colno: int) -> str:
558 """Print a line with a caret pointing to the colno
559
560 :param text: A message to display before the line
561 :param line: The line of code to be pointed to
562 :param colno: The column number to point at
563 :return: A formatted string of the text, line, and a caret
564 """
565 return f'{text}\n{line}\n{" " * colno}^'
566
567 @T.overload
568 def ci_fold_file(fname: T.Union[str, os.PathLike], banner: str, force: Literal[True] = True) -> str: ...
569
570 @T.overload
571 def ci_fold_file(fname: T.Union[str, os.PathLike], banner: str, force: Literal[False] = False) -> T.Optional[str]: ...
572
573 def ci_fold_file(fname: T.Union[str, os.PathLike], banner: str, force: bool = False) -> T.Optional[str]:
574 if not _in_ci and not force:
575 return None
576
577 if _ci_is_github:
578 header = f'::group::==== {banner} ===='
579 footer = '::endgroup::'
580 elif force:
581 header = banner
582 footer = ''
583 elif 'MESON_FORCE_SHOW_LOGS' in os.environ:
584 header = f'==== Forcing display of logs for {os.path.basename(fname)} ===='
585 footer = ''
586 else:
587 # only github is implemented
588 return None
589
590 with open(fname, 'r', encoding='utf-8') as f:
591 data = f.read()
592 return f'{header}\n{data}\n{footer}\n'