mlog.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. # Copyright 2013-2014 The Meson development team
  2. # Licensed under the Apache License, Version 2.0 (the "License");
  3. # you may not use this file except in compliance with the License.
  4. # You may obtain a copy of the License at
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. # Unless required by applicable law or agreed to in writing, software
  7. # distributed under the License is distributed on an "AS IS" BASIS,
  8. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. # See the License for the specific language governing permissions and
  10. # limitations under the License.
  11. import sys, os, platform, io
  12. from contextlib import contextmanager
  13. """This is (mostly) a standalone module used to write logging
  14. information about Meson runs. Some output goes to screen,
  15. some to logging dir and some goes to both."""
  16. def _windows_ansi():
  17. from ctypes import windll, byref
  18. from ctypes.wintypes import DWORD
  19. kernel = windll.kernel32
  20. stdout = kernel.GetStdHandle(-11)
  21. mode = DWORD()
  22. if not kernel.GetConsoleMode(stdout, byref(mode)):
  23. return False
  24. # ENABLE_VIRTUAL_TERMINAL_PROCESSING == 0x4
  25. # If the call to enable VT processing fails (returns 0), we fallback to
  26. # original behavior
  27. return kernel.SetConsoleMode(stdout, mode.value | 0x4) or os.environ.get('ANSICON')
  28. if platform.system().lower() == 'windows':
  29. colorize_console = os.isatty(sys.stdout.fileno()) and _windows_ansi()
  30. else:
  31. colorize_console = os.isatty(sys.stdout.fileno()) and os.environ.get('TERM') != 'dumb'
  32. log_dir = None
  33. log_file = None
  34. log_fname = 'meson-log.txt'
  35. log_depth = 0
  36. def initialize(logdir):
  37. global log_dir, log_file
  38. log_dir = logdir
  39. log_file = open(os.path.join(logdir, log_fname), 'w', encoding='utf8')
  40. def shutdown():
  41. global log_file
  42. if log_file is not None:
  43. exception_around_goer = log_file
  44. log_file = None
  45. exception_around_goer.close()
  46. class AnsiDecorator:
  47. plain_code = "\033[0m"
  48. def __init__(self, text, code):
  49. self.text = text
  50. self.code = code
  51. def get_text(self, with_codes):
  52. if with_codes:
  53. return self.code + self.text + AnsiDecorator.plain_code
  54. return self.text
  55. def bold(text):
  56. return AnsiDecorator(text, "\033[1m")
  57. def red(text):
  58. return AnsiDecorator(text, "\033[1;31m")
  59. def green(text):
  60. return AnsiDecorator(text, "\033[1;32m")
  61. def yellow(text):
  62. return AnsiDecorator(text, "\033[1;33m")
  63. def cyan(text):
  64. return AnsiDecorator(text, "\033[1;36m")
  65. def process_markup(args, keep):
  66. arr = []
  67. for arg in args:
  68. if isinstance(arg, str):
  69. arr.append(arg)
  70. elif isinstance(arg, AnsiDecorator):
  71. arr.append(arg.get_text(keep))
  72. else:
  73. arr.append(str(arg))
  74. return arr
  75. def force_print(*args, **kwargs):
  76. iostr = io.StringIO()
  77. kwargs['file'] = iostr
  78. print(*args, **kwargs)
  79. raw = iostr.getvalue()
  80. if log_depth > 0:
  81. prepend = '|' * log_depth
  82. raw = prepend + raw.replace('\n', '\n' + prepend, raw.count('\n') - 1)
  83. # _Something_ is going to get printed.
  84. try:
  85. print(raw, end='')
  86. except UnicodeEncodeError:
  87. cleaned = raw.encode('ascii', 'replace').decode('ascii')
  88. print(cleaned, end='')
  89. def debug(*args, **kwargs):
  90. arr = process_markup(args, False)
  91. if log_file is not None:
  92. print(*arr, file=log_file, **kwargs) # Log file never gets ANSI codes.
  93. log_file.flush()
  94. def log(*args, **kwargs):
  95. arr = process_markup(args, False)
  96. if log_file is not None:
  97. print(*arr, file=log_file, **kwargs) # Log file never gets ANSI codes.
  98. log_file.flush()
  99. if colorize_console:
  100. arr = process_markup(args, True)
  101. force_print(*arr, **kwargs)
  102. def _log_error(severity, *args, **kwargs):
  103. from . import environment
  104. if severity == 'warning':
  105. args = (yellow('WARNING:'),) + args
  106. elif severity == 'error':
  107. args = (red('ERROR:'),) + args
  108. else:
  109. assert False, 'Invalid severity ' + severity
  110. location = kwargs.pop('location', None)
  111. if location is not None:
  112. location_str = '{}:{}:'.format(os.path.join(location.subdir,
  113. environment.build_filename),
  114. location.lineno)
  115. args = (location_str,) + args
  116. log(*args, **kwargs)
  117. def error(*args, **kwargs):
  118. return _log_error('error', *args, **kwargs)
  119. def warning(*args, **kwargs):
  120. return _log_error('warning', *args, **kwargs)
  121. def exception(e):
  122. log()
  123. if hasattr(e, 'file') and hasattr(e, 'lineno') and hasattr(e, 'colno'):
  124. log('%s:%d:%d:' % (e.file, e.lineno, e.colno), red('ERROR: '), e)
  125. else:
  126. log(red('ERROR:'), e)
  127. # Format a list for logging purposes as a string. It separates
  128. # all but the last item with commas, and the last with 'and'.
  129. def format_list(list):
  130. l = len(list)
  131. if l > 2:
  132. return ' and '.join([', '.join(list[:-1]), list[-1]])
  133. elif l == 2:
  134. return ' and '.join(list)
  135. elif l == 1:
  136. return list[0]
  137. else:
  138. return ''
  139. @contextmanager
  140. def nested():
  141. global log_depth
  142. log_depth += 1
  143. try:
  144. yield
  145. finally:
  146. log_depth -= 1