files: #!/usr/bin/env python3
  
  # Copyright 2012-2019 The Meson development team
  
  # Licensed under the Apache License, Version 2.0 (the "License");
  # you may not use this file except in compliance with the License.
  # You may obtain a copy of the License at
  
  #     http://www.apache.org/licenses/LICENSE-2.0
  
  # Unless required by applicable law or agreed to in writing, software
  # distributed under the License is distributed on an "AS IS" BASIS,
  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  # See the License for the specific language governing permissions and
  # limitations under the License.
  
  import typing as T
  import functools
  import itertools
  import os
  import subprocess
  import shutil
  import sys
  import signal
  import shlex
  from io import StringIO
  from ast import literal_eval
  from enum import Enum
  import tempfile
  from pathlib import Path, PurePath
  from mesonbuild import build
  from mesonbuild import environment
  from mesonbuild import compilers
  from mesonbuild import mesonlib
  from mesonbuild import mlog
  from mesonbuild import mtest
  from mesonbuild.mesonlib import MachineChoice, stringlistify, Popen_safe
  from mesonbuild.coredata import backendlist
  import argparse
  import json
  import xml.etree.ElementTree as ET
  import time
  import multiprocessing
  from concurrent.futures import ProcessPoolExecutor, CancelledError
  import re
  from run_tests import get_fake_options, run_configure, get_meson_script
  from run_tests import get_backend_commands, get_backend_args_for_dir, Backend
  from run_tests import ensure_backend_detects_changes
  from run_tests import guess_backend
  
  ALL_TESTS = ['cmake', 'common', 'warning-meson', 'failing-meson', 'failing-build', 'failing-test',
               'kconfig', 'platform-osx', 'platform-windows', 'platform-linux',
               'java', 'C#', 'vala',  'rust', 'd', 'objective c', 'objective c++',
               'fortran', 'swift', 'cuda', 'python3', 'python', 'fpga', 'frameworks', 'nasm', 'wasm'
               ]
  
  
  class BuildStep(Enum):
      configure = 1
      build = 2
      test = 3
      install = 4
      clean = 5
      validate = 6
  
  
  class TestResult:
      def __init__(self, cicmds):
          self.msg = ''  # empty msg indicates test success
          self.stdo = ''
          self.stde = ''
          self.mlog = ''
          self.cicmds = cicmds
          self.conftime = 0
          self.buildtime = 0
          self.testtime = 0
  
      def add_step(self, step, stdo, stde, mlog='', time=0):
          self.step = step
          self.stdo += stdo
          self.stde += stde
          self.mlog += mlog
          if step == BuildStep.configure:
              self.conftime = time
          elif step == BuildStep.build:
              self.buildtime = time
          elif step == BuildStep.test:
              self.testtime = time
  
      def fail(self, msg):
          self.msg = msg
  
  @functools.total_ordering
  class TestDef:
      def __init__(self, path: Path, name: T.Optional[str], args: T.List[str], skip: bool = False):
          self.path = path
          self.name = name
          self.args = args
          self.skip = skip
  
      def __repr__(self) -> str:
          return '<{}: {:<48} [{}: {}] -- {}>'.format(type(self).__name__, str(self.path), self.name, self.args, self.skip)
  
      def display_name(self) -> str:
          if self.name:
              return '{}   ({})'.format(self.path.as_posix(), self.name)
          return self.path.as_posix()
  
      def __lt__(self, other: T.Any) -> T.Union[bool, type(NotImplemented)]:
          if isinstance(other, TestDef):
              # None is not sortable, so replace it with an empty string
              return (self.path, self.name or '') < (other.path, other.name or '')
          return NotImplemented
  
  class AutoDeletedDir:
      def __init__(self, d):
          self.dir = d
  
      def __enter__(self):
          os.makedirs(self.dir, exist_ok=True)
          return self.dir
  
      def __exit__(self, _type, value, traceback):
          # We don't use tempfile.TemporaryDirectory, but wrap the
          # deletion in the AutoDeletedDir class because
          # it fails on Windows due antivirus programs
          # holding files open.
          mesonlib.windows_proof_rmtree(self.dir)
  
  failing_logs = []
  print_debug = 'MESON_PRINT_TEST_OUTPUT' in os.environ
  under_ci = 'CI' in os.environ
  under_xenial_ci = under_ci and ('XENIAL' in os.environ)
  skip_scientific = under_ci and ('SKIP_SCIENTIFIC' in os.environ)
  do_debug = under_ci or print_debug
  no_meson_log_msg = 'No meson-log.txt found.'
  
  system_compiler = None
  
  class StopException(Exception):
      def __init__(self):
          super().__init__('Stopped by user')
  
  stop = False
  def stop_handler(signal, frame):
      global stop
      stop = True
  signal.signal(signal.SIGINT, stop_handler)
  signal.signal(signal.SIGTERM, stop_handler)
  
  def setup_commands(optbackend):
      global do_debug, backend, backend_flags
      global compile_commands, clean_commands, test_commands, install_commands, uninstall_commands
      backend, backend_flags = guess_backend(optbackend, shutil.which('msbuild'))
      compile_commands, clean_commands, test_commands, install_commands, \
          uninstall_commands = get_backend_commands(backend, do_debug)
  
  def get_relative_files_list_from_dir(fromdir: Path) -> T.List[Path]:
      return [file.relative_to(fromdir) for file in fromdir.rglob('*') if file.is_file()]
  
  def platform_fix_name(fname: str, compiler, env) -> str:
      # canonicalize compiler
      if (compiler in {'clang-cl', 'intel-cl'} or
         (env.machines.host.is_windows() and compiler == 'pgi')):
          canonical_compiler = 'msvc'
      else:
          canonical_compiler = compiler
  
      if '?lib' in fname:
          if env.machines.host.is_windows() and canonical_compiler == 'msvc':
              fname = re.sub(r'lib/\?lib(.*)\.', r'bin/\1.', fname)
              fname = re.sub(r'/\?lib/', r'/bin/', fname)
          elif env.machines.host.is_windows():
              fname = re.sub(r'lib/\?lib(.*)\.', r'bin/lib\1.', fname)
              fname = re.sub(r'\?lib(.*)\.dll$', r'lib\1.dll', fname)
              fname = re.sub(r'/\?lib/', r'/bin/', fname)
          elif env.machines.host.is_cygwin():
              fname = re.sub(r'lib/\?lib(.*)\.so$', r'bin/cyg\1.dll', fname)
              fname = re.sub(r'lib/\?lib(.*)\.', r'bin/cyg\1.', fname)
              fname = re.sub(r'\?lib(.*)\.dll$', r'cyg\1.dll', fname)
              fname = re.sub(r'/\?lib/', r'/bin/', fname)
          else:
              fname = re.sub(r'\?lib', 'lib', fname)
  
      if fname.endswith('?exe'):
          fname = fname[:-4]
          if env.machines.host.is_windows() or env.machines.host.is_cygwin():
              return fname + '.exe'
  
      if fname.startswith('?msvc:'):
          fname = fname[6:]
          if canonical_compiler != 'msvc':
              return None
  
      if fname.startswith('?gcc:'):
          fname = fname[5:]
          if canonical_compiler == 'msvc':
              return None
  
      if fname.startswith('?cygwin:'):
          fname = fname[8:]
          if not env.machines.host.is_cygwin():
              return None
  
      if fname.startswith('?!cygwin:'):
          fname = fname[9:]
          if env.machines.host.is_cygwin():
              return None
  
      if fname.endswith('?so'):
          if env.machines.host.is_windows() and canonical_compiler == 'msvc':
              fname = re.sub(r'lib/([^/]*)\?so$', r'bin/\1.dll', fname)
              fname = re.sub(r'/(?:lib|)([^/]*?)\?so$', r'/\1.dll', fname)
              return fname
          elif env.machines.host.is_windows():
              fname = re.sub(r'lib/([^/]*)\?so$', r'bin/\1.dll', fname)
              fname = re.sub(r'/([^/]*?)\?so$', r'/\1.dll', fname)
              return fname
          elif env.machines.host.is_cygwin():
              fname = re.sub(r'lib/([^/]*)\?so$', r'bin/\1.dll', fname)
              fname = re.sub(r'/lib([^/]*?)\?so$', r'/cyg\1.dll', fname)
              fname = re.sub(r'/([^/]*?)\?so$', r'/\1.dll', fname)
              return fname
          elif env.machines.host.is_darwin():
              return fname[:-3] + '.dylib'
          else:
              return fname[:-3] + '.so'
  
      if fname.endswith('?implib') or fname.endswith('?implibempty'):
          if env.machines.host.is_windows() and canonical_compiler == 'msvc':
              # only MSVC doesn't generate empty implibs
              if fname.endswith('?implibempty') and compiler == 'msvc':
                  return None
              return re.sub(r'/(?:lib|)([^/]*?)\?implib(?:empty|)$', r'/\1.lib', fname)
          elif env.machines.host.is_windows() or env.machines.host.is_cygwin():
              return re.sub(r'\?implib(?:empty|)$', r'.dll.a', fname)
          else:
              return None
  
      return fname
  
  def validate_install(srcdir: str, installdir: Path, compiler, env) -> str:
      # List of installed files
      info_file = Path(srcdir) / 'installed_files.txt'
      installdir = Path(installdir)
      # If this exists, the test does not install any other files
      noinst_file = Path('usr/no-installed-files')
      expected = {}  # type: T.Dict[Path, bool]
      ret_msg = ''
      # Generate list of expected files
      if (installdir / noinst_file).is_file():
          expected[noinst_file] = False
      elif info_file.is_file():
          with info_file.open() as f:
              for line in f:
                  line = platform_fix_name(line.strip(), compiler, env)
                  if line:
                      expected[Path(line)] = False
      # Check if expected files were found
      for fname in expected:
          file_path = installdir / fname
          if file_path.is_file() or file_path.is_symlink():
              expected[fname] = True
      for (fname, found) in expected.items():
          if not found:
              ret_msg += 'Expected file {} missing.\n'.format(fname)
      # Check if there are any unexpected files
      found = get_relative_files_list_from_dir(installdir)
      for fname in found:
          if fname not in expected:
              ret_msg += 'Extra file {} found.\n'.format(fname)
      if ret_msg != '':
          ret_msg += '\nInstall dir contents:\n'
          for i in found:
              ret_msg += '  - {}'.format(i)
      return ret_msg
  
  def log_text_file(logfile, testdir, stdo, stde):
      global stop, executor, futures
      logfile.write('%s\nstdout\n\n---\n' % testdir.as_posix())
      logfile.write(stdo)
      logfile.write('\n\n---\n\nstderr\n\n---\n')
      logfile.write(stde)
      logfile.write('\n\n---\n\n')
      if print_debug:
          try:
              print(stdo)
          except UnicodeError:
              sanitized_out = stdo.encode('ascii', errors='replace').decode()
              print(sanitized_out)
          try:
              print(stde, file=sys.stderr)
          except UnicodeError:
              sanitized_err = stde.encode('ascii', errors='replace').decode()
              print(sanitized_err, file=sys.stderr)
      if stop:
          print("Aborting..")
          for f in futures:
              f[2].cancel()
          executor.shutdown()
          raise StopException()
  
  
  def bold(text):
      return mlog.bold(text).get_text(mlog.colorize_console)
  
  
  def green(text):
      return mlog.green(text).get_text(mlog.colorize_console)
  
  
  def red(text):
      return mlog.red(text).get_text(mlog.colorize_console)
  
  
  def yellow(text):
      return mlog.yellow(text).get_text(mlog.colorize_console)
  
  
  def _run_ci_include(args: T.List[str]) -> str:
      if not args:
          return 'At least one parameter required'
      try:
          file_path = Path(args[0])
          data = file_path.open(errors='ignore', encoding='utf-8').read()
          return 'Included file {}:\n{}\n'.format(args[0], data)
      except Exception:
          return 'Failed to open {} ({})'.format(args[0])
  
  ci_commands = {
      'ci_include': _run_ci_include
  }
  
  def run_ci_commands(raw_log: str) -> T.List[str]:
      res = []
      for l in raw_log.splitlines():
          if not l.startswith('!meson_ci!/'):
              continue
          cmd = shlex.split(l[11:])
          if not cmd or cmd[0] not in ci_commands:
              continue
          res += ['CI COMMAND {}:\n{}\n'.format(cmd[0], ci_commands[cmd[0]](cmd[1:]))]
      return res
  
  
  def run_test_inprocess(testdir):
      old_stdout = sys.stdout
      sys.stdout = mystdout = StringIO()
      old_stderr = sys.stderr
      sys.stderr = mystderr = StringIO()
      old_cwd = os.getcwd()
      os.chdir(testdir)
      test_log_fname = Path('meson-logs', 'testlog.txt')
      try:
          returncode_test = mtest.run_with_args(['--no-rebuild'])
          if test_log_fname.exists():
              test_log = test_log_fname.open(errors='ignore').read()
          else:
              test_log = ''
          returncode_benchmark = mtest.run_with_args(['--no-rebuild', '--benchmark', '--logbase', 'benchmarklog'])
      finally:
          sys.stdout = old_stdout
          sys.stderr = old_stderr
          os.chdir(old_cwd)
      return max(returncode_test, returncode_benchmark), mystdout.getvalue(), mystderr.getvalue(), test_log
  
  def parse_test_args(testdir):
      args = []
      try:
          with open(os.path.join(testdir, 'test_args.txt'), 'r') as f:
              content = f.read()
              try:
                  args = literal_eval(content)
              except Exception:
                  raise Exception('Malformed test_args file.')
              args = stringlistify(args)
      except FileNotFoundError:
          pass
      return args
  
  # Build directory name must be the same so Ccache works over
  # consecutive invocations.
  def create_deterministic_builddir(src_dir, name):
      import hashlib
      if name:
          src_dir += name
      rel_dirname = 'b ' + hashlib.sha256(src_dir.encode(errors='ignore')).hexdigest()[0:10]
      os.mkdir(rel_dirname)
      abs_pathname = os.path.join(os.getcwd(), rel_dirname)
      return abs_pathname
  
  def run_test(skipped, testdir, name, extra_args, compiler, backend, flags, commands, should_fail):
      if skipped:
          return None
      with AutoDeletedDir(create_deterministic_builddir(testdir, name)) as build_dir:
          with AutoDeletedDir(tempfile.mkdtemp(prefix='i ', dir=os.getcwd())) as install_dir:
              try:
                  return _run_test(testdir, build_dir, install_dir, extra_args, compiler, backend, flags, commands, should_fail)
              finally:
                  mlog.shutdown() # Close the log file because otherwise Windows wets itself.
  
  def pass_prefix_to_test(dirname):
      if '39 prefix absolute' in dirname:
          return False
  
  
  [... the rest is omitted ...]
files: run_project_tests.py
files: #!/usr/bin/env python3
  
  # Copyright 2012-2019 The Meson development team
  
  # Licensed under the Apache License, Version 2.0 (the "License");
  # you may not use this file except in compliance with the License.
  # You may obtain a copy of the License at
  
  #     http://www.apache.org/licenses/LICENSE-2.0
  
  # Unless required by applicable law or agreed to in writing, software
  # distributed under the License is distributed on an "AS IS" BASIS,
  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  # See the License for the specific language governing permissions and
  # limitations under the License.
  
  import typing as T
  import functools
  import itertools
  import os
  import subprocess
  import shutil
  import sys
  import signal
  import shlex
  from io import StringIO
  from ast import literal_eval
  from enum import Enum
  import tempfile
  from pathlib import Path, PurePath
  from mesonbuild import build
  from mesonbuild import environment
  from mesonbuild import compilers
  from mesonbuild import mesonlib
  from mesonbuild import mlog
  from mesonbuild import mtest
  from mesonbuild.mesonlib import MachineChoice, stringlistify, Popen_safe
  from mesonbuild.coredata import backendlist
  import argparse
  import json
  import xml.etree.ElementTree as ET
  import time
  import multiprocessing
  from concurrent.futures import ProcessPoolExecutor, CancelledError
  import re
  from run_tests import get_fake_options, run_configure, get_meson_script
  from run_tests import get_backend_commands, get_backend_args_for_dir, Backend
  from run_tests import ensure_backend_detects_changes
  from run_tests import guess_backend
  
  ALL_TESTS = ['cmake', 'common', 'warning-meson', 'failing-meson', 'failing-build', 'failing-test',
               'kconfig', 'platform-osx', 'platform-windows', 'platform-linux',
               'java', 'C#', 'vala',  'rust', 'd', 'objective c', 'objective c++',
               'fortran', 'swift', 'cuda', 'python3', 'python', 'fpga', 'frameworks', 'nasm', 'wasm'
               ]
  
  
  class BuildStep(Enum):
      configure = 1
      build = 2
      test = 3
      install = 4
      clean = 5
      validate = 6
  
  
  class TestResult:
      def __init__(self, msg, step, stdo, stde, mlog, cicmds, conftime=0, buildtime=0, testtime=0):
          self.msg = msg
          self.step = step
          self.stdo = stdo
          self.stde = stde
          self.mlog = mlog
          self.cicmds = cicmds
          self.conftime = conftime
          self.buildtime = buildtime
          self.testtime = testtime
  
  
  @functools.total_ordering
  class TestDef:
      def __init__(self, path: Path, name: T.Optional[str], args: T.List[str], skip: bool = False):
          self.path = path
          self.name = name
          self.args = args
          self.skip = skip
  
      def __repr__(self) -> str:
          return '<{}: {:<48} [{}: {}] -- {}>'.format(type(self).__name__, str(self.path), self.name, self.args, self.skip)
  
      def display_name(self) -> str:
          if self.name:
              return '{}   ({})'.format(self.path.as_posix(), self.name)
          return self.path.as_posix()
  
      def __lt__(self, other: T.Any) -> T.Union[bool, type(NotImplemented)]:
          if isinstance(other, TestDef):
              # None is not sortable, so replace it with an empty string
              return (self.path, self.name or '') < (other.path, other.name or '')
          return NotImplemented
  
  class AutoDeletedDir:
      def __init__(self, d):
          self.dir = d
  
      def __enter__(self):
          os.makedirs(self.dir, exist_ok=True)
          return self.dir
  
      def __exit__(self, _type, value, traceback):
          # We don't use tempfile.TemporaryDirectory, but wrap the
          # deletion in the AutoDeletedDir class because
          # it fails on Windows due antivirus programs
          # holding files open.
          mesonlib.windows_proof_rmtree(self.dir)
  
  failing_logs = []
  print_debug = 'MESON_PRINT_TEST_OUTPUT' in os.environ
  under_ci = 'CI' in os.environ
  under_xenial_ci = under_ci and ('XENIAL' in os.environ)
  skip_scientific = under_ci and ('SKIP_SCIENTIFIC' in os.environ)
  do_debug = under_ci or print_debug
  no_meson_log_msg = 'No meson-log.txt found.'
  
  system_compiler = None
  
  class StopException(Exception):
      def __init__(self):
          super().__init__('Stopped by user')
  
  stop = False
  def stop_handler(signal, frame):
      global stop
      stop = True
  signal.signal(signal.SIGINT, stop_handler)
  signal.signal(signal.SIGTERM, stop_handler)
  
  def setup_commands(optbackend):
      global do_debug, backend, backend_flags
      global compile_commands, clean_commands, test_commands, install_commands, uninstall_commands
      backend, backend_flags = guess_backend(optbackend, shutil.which('msbuild'))
      compile_commands, clean_commands, test_commands, install_commands, \
          uninstall_commands = get_backend_commands(backend, do_debug)
  
  def get_relative_files_list_from_dir(fromdir: Path) -> T.List[Path]:
      return [file.relative_to(fromdir) for file in fromdir.rglob('*') if file.is_file()]
  
  def platform_fix_name(fname: str, compiler, env) -> str:
      # canonicalize compiler
      if (compiler in {'clang-cl', 'intel-cl'} or
         (env.machines.host.is_windows() and compiler == 'pgi')):
          canonical_compiler = 'msvc'
      else:
          canonical_compiler = compiler
  
      if '?lib' in fname:
          if env.machines.host.is_windows() and canonical_compiler == 'msvc':
              fname = re.sub(r'lib/\?lib(.*)\.', r'bin/\1.', fname)
              fname = re.sub(r'/\?lib/', r'/bin/', fname)
          elif env.machines.host.is_windows():
              fname = re.sub(r'lib/\?lib(.*)\.', r'bin/lib\1.', fname)
              fname = re.sub(r'\?lib(.*)\.dll$', r'lib\1.dll', fname)
              fname = re.sub(r'/\?lib/', r'/bin/', fname)
          elif env.machines.host.is_cygwin():
              fname = re.sub(r'lib/\?lib(.*)\.so$', r'bin/cyg\1.dll', fname)
              fname = re.sub(r'lib/\?lib(.*)\.', r'bin/cyg\1.', fname)
              fname = re.sub(r'\?lib(.*)\.dll$', r'cyg\1.dll', fname)
              fname = re.sub(r'/\?lib/', r'/bin/', fname)
          else:
              fname = re.sub(r'\?lib', 'lib', fname)
  
      if fname.endswith('?exe'):
          fname = fname[:-4]
          if env.machines.host.is_windows() or env.machines.host.is_cygwin():
              return fname + '.exe'
  
      if fname.startswith('?msvc:'):
          fname = fname[6:]
          if canonical_compiler != 'msvc':
              return None
  
      if fname.startswith('?gcc:'):
          fname = fname[5:]
          if canonical_compiler == 'msvc':
              return None
  
      if fname.startswith('?cygwin:'):
          fname = fname[8:]
          if not env.machines.host.is_cygwin():
              return None
  
      if fname.startswith('?!cygwin:'):
          fname = fname[9:]
          if env.machines.host.is_cygwin():
              return None
  
      if fname.endswith('?so'):
          if env.machines.host.is_windows() and canonical_compiler == 'msvc':
              fname = re.sub(r'lib/([^/]*)\?so$', r'bin/\1.dll', fname)
              fname = re.sub(r'/(?:lib|)([^/]*?)\?so$', r'/\1.dll', fname)
              return fname
          elif env.machines.host.is_windows():
              fname = re.sub(r'lib/([^/]*)\?so$', r'bin/\1.dll', fname)
              fname = re.sub(r'/([^/]*?)\?so$', r'/\1.dll', fname)
              return fname
          elif env.machines.host.is_cygwin():
              fname = re.sub(r'lib/([^/]*)\?so$', r'bin/\1.dll', fname)
              fname = re.sub(r'/lib([^/]*?)\?so$', r'/cyg\1.dll', fname)
              fname = re.sub(r'/([^/]*?)\?so$', r'/\1.dll', fname)
              return fname
          elif env.machines.host.is_darwin():
              return fname[:-3] + '.dylib'
          else:
              return fname[:-3] + '.so'
  
      if fname.endswith('?implib') or fname.endswith('?implibempty'):
          if env.machines.host.is_windows() and canonical_compiler == 'msvc':
              # only MSVC doesn't generate empty implibs
              if fname.endswith('?implibempty') and compiler == 'msvc':
                  return None
              return re.sub(r'/(?:lib|)([^/]*?)\?implib(?:empty|)$', r'/\1.lib', fname)
          elif env.machines.host.is_windows() or env.machines.host.is_cygwin():
              return re.sub(r'\?implib(?:empty|)$', r'.dll.a', fname)
          else:
              return None
  
      return fname
  
  def validate_install(srcdir: str, installdir: Path, compiler, env) -> str:
      # List of installed files
      info_file = Path(srcdir) / 'installed_files.txt'
      installdir = Path(installdir)
      # If this exists, the test does not install any other files
      noinst_file = Path('usr/no-installed-files')
      expected = {}  # type: T.Dict[Path, bool]
      ret_msg = ''
      # Generate list of expected files
      if (installdir / noinst_file).is_file():
          expected[noinst_file] = False
      elif info_file.is_file():
          with info_file.open() as f:
              for line in f:
                  line = platform_fix_name(line.strip(), compiler, env)
                  if line:
                      expected[Path(line)] = False
      # Check if expected files were found
      for fname in expected:
          file_path = installdir / fname
          if file_path.is_file() or file_path.is_symlink():
              expected[fname] = True
      for (fname, found) in expected.items():
          if not found:
              ret_msg += 'Expected file {} missing.\n'.format(fname)
      # Check if there are any unexpected files
      found = get_relative_files_list_from_dir(installdir)
      for fname in found:
          if fname not in expected:
              ret_msg += 'Extra file {} found.\n'.format(fname)
      if ret_msg != '':
          ret_msg += '\nInstall dir contents:\n'
          for i in found:
              ret_msg += '  - {}'.format(i)
      return ret_msg
  
  def log_text_file(logfile, testdir, stdo, stde):
      global stop, executor, futures
      logfile.write('%s\nstdout\n\n---\n' % testdir.as_posix())
      logfile.write(stdo)
      logfile.write('\n\n---\n\nstderr\n\n---\n')
      logfile.write(stde)
      logfile.write('\n\n---\n\n')
      if print_debug:
          try:
              print(stdo)
          except UnicodeError:
              sanitized_out = stdo.encode('ascii', errors='replace').decode()
              print(sanitized_out)
          try:
              print(stde, file=sys.stderr)
          except UnicodeError:
              sanitized_err = stde.encode('ascii', errors='replace').decode()
              print(sanitized_err, file=sys.stderr)
      if stop:
          print("Aborting..")
          for f in futures:
              f[2].cancel()
          executor.shutdown()
          raise StopException()
  
  
  def bold(text):
      return mlog.bold(text).get_text(mlog.colorize_console)
  
  
  def green(text):
      return mlog.green(text).get_text(mlog.colorize_console)
  
  
  def red(text):
      return mlog.red(text).get_text(mlog.colorize_console)
  
  
  def yellow(text):
      return mlog.yellow(text).get_text(mlog.colorize_console)
  
  
  def _run_ci_include(args: T.List[str]) -> str:
      if not args:
          return 'At least one parameter required'
      try:
          file_path = Path(args[0])
          data = file_path.open(errors='ignore', encoding='utf-8').read()
          return 'Included file {}:\n{}\n'.format(args[0], data)
      except Exception:
          return 'Failed to open {} ({})'.format(args[0])
  
  ci_commands = {
      'ci_include': _run_ci_include
  }
  
  def run_ci_commands(raw_log: str) -> T.List[str]:
      res = []
      for l in raw_log.splitlines():
          if not l.startswith('!meson_ci!/'):
              continue
          cmd = shlex.split(l[11:])
          if not cmd or cmd[0] not in ci_commands:
              continue
          res += ['CI COMMAND {}:\n{}\n'.format(cmd[0], ci_commands[cmd[0]](cmd[1:]))]
      return res
  
  
  def run_test_inprocess(testdir):
      old_stdout = sys.stdout
      sys.stdout = mystdout = StringIO()
      old_stderr = sys.stderr
      sys.stderr = mystderr = StringIO()
      old_cwd = os.getcwd()
      os.chdir(testdir)
      test_log_fname = Path('meson-logs', 'testlog.txt')
      try:
          returncode_test = mtest.run_with_args(['--no-rebuild'])
          if test_log_fname.exists():
              test_log = test_log_fname.open(errors='ignore').read()
          else:
              test_log = ''
          returncode_benchmark = mtest.run_with_args(['--no-rebuild', '--benchmark', '--logbase', 'benchmarklog'])
      finally:
          sys.stdout = old_stdout
          sys.stderr = old_stderr
          os.chdir(old_cwd)
      return max(returncode_test, returncode_benchmark), mystdout.getvalue(), mystderr.getvalue(), test_log
  
  def parse_test_args(testdir):
      args = []
      try:
          with open(os.path.join(testdir, 'test_args.txt'), 'r') as f:
              content = f.read()
              try:
                  args = literal_eval(content)
              except Exception:
                  raise Exception('Malformed test_args file.')
              args = stringlistify(args)
      except FileNotFoundError:
          pass
      return args
  
  # Build directory name must be the same so Ccache works over
  # consecutive invocations.
  def create_deterministic_builddir(src_dir, name):
      import hashlib
      if name:
          src_dir += name
      rel_dirname = 'b ' + hashlib.sha256(src_dir.encode(errors='ignore')).hexdigest()[0:10]
      os.mkdir(rel_dirname)
      abs_pathname = os.path.join(os.getcwd(), rel_dirname)
      return abs_pathname
  
  def run_test(skipped, testdir, name, extra_args, compiler, backend, flags, commands, should_fail):
      if skipped:
          return None
      with AutoDeletedDir(create_deterministic_builddir(testdir, name)) as build_dir:
          with AutoDeletedDir(tempfile.mkdtemp(prefix='i ', dir=os.getcwd())) as install_dir:
              try:
                  return _run_test(testdir, build_dir, install_dir, extra_args, compiler, backend, flags, commands, should_fail)
              finally:
                  mlog.shutdown() # Close the log file because otherwise Windows wets itself.
  
  def pass_prefix_to_test(dirname):
      if '39 prefix absolute' in dirname:
          return False
      return True
  
  def pass_libdir_to_test(dirname):
      if '8 install' in dirname:
          return False
      if '38 libdir must be inside prefix' in dirname:
          return False
      if '195 install_mode' in dirname:
          return False
      return True
  
  def _run_test(testdir, test_build_dir,
  
  [... the rest is omitted ...]
files: run_project_tests.py