files: # Copyright 2014-2016 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 os
  from . import (coredata, mesonlib, build)
  
  def add_arguments(parser):
      coredata.register_builtin_arguments(parser)
      parser.add_argument('builddir', nargs='?', default='.')
      parser.add_argument('--clearcache', action='store_true', default=False,
                          help='Clear cached state (e.g. found dependencies)')
  
  
  class ConfException(mesonlib.MesonException):
      pass
  
  
  class Conf:
      def __init__(self, build_dir):
          self.build_dir = build_dir
          if not os.path.isdir(os.path.join(build_dir, 'meson-private')):
              raise ConfException('Directory %s does not seem to be a Meson build directory.' % build_dir)
          self.build = build.load(self.build_dir)
          self.coredata = coredata.load(self.build_dir)
  
      def clear_cache(self):
          self.coredata.deps = {}
  
      def set_options(self, options):
          self.coredata.set_options(options)
  
      def save(self):
          # Only called if something has changed so overwrite unconditionally.
          coredata.save(self.coredata, self.build_dir)
          # We don't write the build file because any changes to it
          # are erased when Meson is executed the next time, i.e. when
          # Ninja is run.
  
      @staticmethod
      def print_aligned(arr):
          def make_lower_case(val):
              if isinstance(val, bool):
                  return str(val).lower()
              elif isinstance(val, list):
                  return [make_lower_case(i) for i in val]
              else:
                  return str(val)
  
          if not arr:
              return
  
          titles = {'name': 'Option', 'descr': 'Description', 'value': 'Current Value', 'choices': 'Possible Values'}
  
          name_col = [titles['name'], '-' * len(titles['name'])]
          value_col = [titles['value'], '-' * len(titles['value'])]
          choices_col = [titles['choices'], '-' * len(titles['choices'])]
          descr_col = [titles['descr'], '-' * len(titles['descr'])]
  
          choices_found = False
          for opt in arr:
              name_col.append(opt['name'])
              descr_col.append(opt['descr'])
              if isinstance(opt['value'], list):
                  value_col.append('[{0}]'.format(', '.join(make_lower_case(opt['value']))))
              else:
                  value_col.append(make_lower_case(opt['value']))
              if opt['choices']:
                  choices_found = True
                  if isinstance(opt['choices'], list):
                      choices_col.append('[{0}]'.format(', '.join(make_lower_case
  
  [... the rest is omitted ...]
files: mesonbuild/mconf.py
files: # Copyright 2014-2016 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 os
  import argparse
  from . import (coredata, mesonlib, build)
  
  def buildparser():
      parser = argparse.ArgumentParser(prog='meson configure')
      coredata.register_builtin_arguments(parser)
  
      parser.add_argument('builddir', nargs='?', default='.')
      parser.add_argument('--clearcache', action='store_true', default=False,
                          help='Clear cached state (e.g. found dependencies)')
      return parser
  
  
  class ConfException(mesonlib.MesonException):
      pass
  
  
  class Conf:
      def __init__(self, build_dir):
          self.build_dir = build_dir
          if not os.path.isdir(os.path.join(build_dir, 'meson-private')):
              raise ConfException('Directory %s does not seem to be a Meson build directory.' % build_dir)
          self.build = build.load(self.build_dir)
          self.coredata = coredata.load(self.build_dir)
  
      def clear_cache(self):
          self.coredata.deps = {}
  
      def set_options(self, options):
          self.coredata.set_options(options)
  
      def save(self):
          # Only called if something has changed so overwrite unconditionally.
          coredata.save(self.coredata, self.build_dir)
          # We don't write the build file because any changes to it
          # are erased when Meson is executed the next time, i.e. when
          # Ninja is run.
  
      @staticmethod
      def print_aligned(arr):
          def make_lower_case(val):
              if isinstance(val, bool):
                  return str(val).lower()
              elif isinstance(val, list):
                  return [make_lower_case(i) for i in val]
              else:
                  return str(val)
  
          if not arr:
              return
  
          titles = {'name': 'Option', 'descr': 'Description', 'value': 'Current Value', 'choices': 'Possible Values'}
  
          name_col = [titles['name'], '-' * len(titles['name'])]
          value_col = [titles['value'], '-' * len(titles['value'])]
          choices_col = [titles['choices'], '-' * len(titles['choices'])]
          descr_col = [titles['descr'], '-' * len(titles['descr'])]
  
          choices_found = False
          for opt in arr:
              name_col.append(opt['name'])
              descr_col.append(opt['descr'])
              if isinstance(opt['value'], list):
                  value_col.append('[{0}]'.format(', '.join(make_lower_case(opt['value']))))
              else:
                  value_col.append(make_lower_case(opt['value']))
              if opt['choices']:
                  choices_found = True
                  if isinstance(opt['choices'],
  
  [... the rest is omitted ...]
files: mesonbuild/mconf.py
files: # Copyright 2012-2016 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 sys
  import os.path
  import importlib
  import traceback
  import argparse
  
  from . import mesonlib
  from . import mlog
  from . import mconf, minit, minstall, mintro, msetup, mtest, rewriter
  from .mesonlib import MesonException
  from .environment import detect_msys2_arch
  from .wrap import wraptool
  
  
  class CommandLineParser:
      def __init__(self):
          self.commands = {}
          self.parser = argparse.ArgumentParser(prog='meson')
          self.subparsers = self.parser.add_subparsers(title='Commands',
                                                       description='If no command is specified it defaults to setup command.')
          self.add_command('setup', msetup.add_arguments, msetup.run,
                           help='Configure the project')
          self.add_command('configure', mconf.add_arguments, mconf.run,
                           help='Change project options',)
          self.add_command('install', minstall.add_arguments, minstall.run,
                           help='Install the project')
          self.add_command('introspect', mintro.add_arguments, mintro.run,
                           help='Introspect project')
          self.add_command('init', minit.add_arguments, minit.run,
                           help='Create a new project')
          self.add_command('test', mtest.add_arguments, mtest.run,
                           help='Run tests')
          self.add_command('rewrite', rewriter.add_arguments, rewriter.run,
                           help='Edit project files')
          self.add_command('wrap', wraptool.add_arguments, wraptool.run,
                           help='Wrap tools')
          self.add_command('runpython', self.add_runpython_arguments, self.run_runpython_command,
                           help='Run a python script')
          self.add_command('help', self.add_help_arguments, self.run_help_command,
                           help='Print help of a subcommand')
  
      def add_command(self, name, add_arguments_func, run_func, help):
          p = self.subparsers.add_parser(name, help=help)
          add_arguments_func(p)
          p.set_defaults(run_func=run_func)
          self.commands[name] = p
  
      def add_runpython_arguments(self, parser):
          parser.add_argument('script_file')
          parser.add_argument('script_args', nargs=argparse.REMAINDER)
  
      def run_runpython_command(self, options):
          import runpy
          sys.argv[1:] = options.script_args
          runpy.run_path(options.script_file, run_name='__main__')
          return 0
  
      def add_help_arguments(self, parser):
          parser.add_argument('command', nargs='?')
  
      def run_help_command(self, options):
          if options.command:
             
  
  [... the rest is omitted ...]
files: mesonbuild/mesonmain.py
files: # Copyright 2012-2016 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 sys
  import os.path
  import importlib
  
  from . import mesonlib
  from . import mlog
  from .mesonlib import MesonException
  from .environment import detect_msys2_arch
  
  def run_script_command(script_name, script_args):
      # Map script name to module name for those that doesn't match
      script_map = {'exe': 'meson_exe',
                    'install': 'meson_install',
                    'delsuffix': 'delwithsuffix',
                    'gtkdoc': 'gtkdochelper',
                    'hotdoc': 'hotdochelper',
                    'regencheck': 'regen_checker'}
      module_name = script_map.get(script_name, script_name)
  
      try:
          module = importlib.import_module('mesonbuild.scripts.' + module_name)
      except ModuleNotFoundError as e:
          mlog.exception(e)
          return 1
  
      try:
          return module.run(script_args)
      except MesonException as e:
          mlog.error('Error in {} helper script:'.format(script_name))
          mlog.exception(e)
          return 1
  
  def run(original_args, mainfile):
      if sys.version_info < (3, 5):
          print('Meson works correctly only with python 3.5+.')
          print('You have python %s.' % sys.version)
          print('Please update your environment')
          return 1
      # https://github.com/mesonbuild/meson/issues/3653
      if sys.platform.lower() == 'msys':
          mlog.error('This python3 seems to be msys/python on MSYS2 Windows, which is known to have path semantics incompatible with Meson')
          msys2_arch = detect_msys2_arch()
          if msys2_arch:
              mlog.error('Please install and use mingw-w64-i686-python3 and/or mingw-w64-x86_64-python3 with Pacman')
          else:
              mlog.error('Please download and use Python as detailed at: https://mesonbuild.com/Getting-meson.html')
          return 2
  
      # Set the meson command that will be used to run scripts and so on
      mesonlib.set_meson_command(mainfile)
  
      args = original_args[:]
  
      # Special handling of internal commands called from backends, they don't
      # need to go through argparse.
      if len(args) >= 2 and args[0] == '--internal':
          if args[1] == 'regenerate':
              # Rewrite "meson --internal regenerate" command line to
              # "meson --reconfigure"
              args = ['--reconfigure'] + args[2:]
          else:
              return run_script_command(args
  
  [... the rest is omitted ...]
files: mesonbuild/mesonmain.py
files: # Copyright 2017 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.
  
  """Code that creates simple startup projects."""
  
  import os, sys, re, shutil, subprocess
  from glob import glob
  from mesonbuild import mesonlib
  from mesonbuild.environment import detect_ninja
  
  lib_h_template = '''#pragma once
  #if defined _WIN32 || defined __CYGWIN__
    #ifdef BUILDING_{utoken}
      #define {utoken}_PUBLIC __declspec(dllexport)
    #else
      #define {utoken}_PUBLIC __declspec(dllimport)
    #endif
  #else
    #ifdef BUILDING_{utoken}
        #define {utoken}_PUBLIC __attribute__ ((visibility ("default")))
    #else
        #define {utoken}_PUBLIC
    #endif
  #endif
  
  int {utoken}_PUBLIC {function_name}();
  
  '''
  
  lib_c_template = '''#include <{header_file}>
  
  /* This function will not be exported and is not
   * directly callable by users of this library.
   */
  int internal_function() {{
      return 0;
  }}
  
  int {function_name}() {{
      return internal_function();
  }}
  '''
  
  lib_c_test_template = '''#include <{header_file}>
  #include <stdio.h>
  
  int main(int argc, char **argv) {{
      if(argc != 1) {{
          printf("%s takes no arguments.\\n", argv[0]);
          return 1;
      }}
      return {function_name}();
  }}
  '''
  
  lib_c_meson_template = '''project('{project_name}', 'c',
    version : '{version}',
    default_options : ['warning_level=3'])
  
  # These arguments are only used to build the shared library
  # not the executables that use the library.
  lib_args = ['-DBUILDING_{utoken}']
  
  shlib = shared_library('{lib_name}', '{source_file}',
    install : true,
    c_args : lib_args,
    gnu_symbol_visibility : 'hidden',
  )
  
  test_exe = executable('{test_exe_name}', '{test_source_file}',
    link_with : shlib)
  test('{test_name}', test_exe)
  
  # Make this library usable as a Meson subproject.
  {ltoken}_dep = declare_dependency(
    include_directories: include_directories('.'),
    link_with : shlib)
  
  # Make this library usable from the system's
  # package manager.
  install_headers('{header_file}', subdir : '{header_dir}')
  
  pkg_mod = import('pkgconfig')
  pkg_mod.generate(
    name : '{project_name}',
    filebase : '{ltoken}',
    description : 'Meson sample project.',
    subdirs : '{header_dir}',
    libraries : shlib,
    version : '{version}',
  )
  '''
  
  hello
  
  [... the rest is omitted ...]
files: mesonbuild/minit.py
files: # Copyright 2017 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.
  
  """Code that creates simple startup projects."""
  
  import os, sys, argparse, re, shutil, subprocess
  from glob import glob
  from mesonbuild import mesonlib
  from mesonbuild.environment import detect_ninja
  
  lib_h_template = '''#pragma once
  #if defined _WIN32 || defined __CYGWIN__
    #ifdef BUILDING_{utoken}
      #define {utoken}_PUBLIC __declspec(dllexport)
    #else
      #define {utoken}_PUBLIC __declspec(dllimport)
    #endif
  #else
    #ifdef BUILDING_{utoken}
        #define {utoken}_PUBLIC __attribute__ ((visibility ("default")))
    #else
        #define {utoken}_PUBLIC
    #endif
  #endif
  
  int {utoken}_PUBLIC {function_name}();
  
  '''
  
  lib_c_template = '''#include <{header_file}>
  
  /* This function will not be exported and is not
   * directly callable by users of this library.
   */
  int internal_function() {{
      return 0;
  }}
  
  int {function_name}() {{
      return internal_function();
  }}
  '''
  
  lib_c_test_template = '''#include <{header_file}>
  #include <stdio.h>
  
  int main(int argc, char **argv) {{
      if(argc != 1) {{
          printf("%s takes no arguments.\\n", argv[0]);
          return 1;
      }}
      return {function_name}();
  }}
  '''
  
  lib_c_meson_template = '''project('{project_name}', 'c',
    version : '{version}',
    default_options : ['warning_level=3'])
  
  # These arguments are only used to build the shared library
  # not the executables that use the library.
  lib_args = ['-DBUILDING_{utoken}']
  
  shlib = shared_library('{lib_name}', '{source_file}',
    install : true,
    c_args : lib_args,
    gnu_symbol_visibility : 'hidden',
  )
  
  test_exe = executable('{test_exe_name}', '{test_source_file}',
    link_with : shlib)
  test('{test_name}', test_exe)
  
  # Make this library usable as a Meson subproject.
  {ltoken}_dep = declare_dependency(
    include_directories: include_directories('.'),
    link_with : shlib)
  
  # Make this library usable from the system's
  # package manager.
  install_headers('{header_file}', subdir : '{header_dir}')
  
  pkg_mod = import('pkgconfig')
  pkg_mod.generate(
    name : '{project_name}',
    filebase : '{ltoken}',
    description : 'Meson sample project.',
    subdirs : '{header_dir}',
    libraries : shlib,
    version : '{version}',
  )
  
  
  [... the rest is omitted ...]
files: mesonbuild/minit.py
files: # Copyright 2013-2014 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 sys, pickle, os, shutil, subprocess, gzip, errno
  import shlex
  from glob import glob
  from .scripts import depfixer
  from .scripts import destdir_join
  from .mesonlib import is_windows, Popen_safe
  from .mtest import rebuild_all
  try:
      from __main__ import __file__ as main_file
  except ImportError:
      # Happens when running as meson.exe which is native Windows.
      # This is only used for pkexec which is not, so this is fine.
      main_file = None
  
  symlink_warning = '''Warning: trying to copy a symlink that points to a file. This will copy the file,
  but this will be changed in a future version of Meson to copy the symlink as is. Please update your
  build definitions so that it will not break when the change happens.'''
  
  selinux_updates = []
  
  def add_arguments(parser):
      parser.add_argument('-C', default='.', dest='wd',
                          help='directory to cd into before running')
      parser.add_argument('--no-rebuild', default=False, action='store_true',
                          help='Do not rebuild before installing.')
      parser.add_argument('--only-changed', default=False, action='store_true',
                          help='Only overwrite files that are older than the copied file.')
  
  class DirMaker:
      def __init__(self, lf):
          self.lf = lf
          self.dirs = []
  
      def makedirs(self, path, exist_ok=False):
          dirname = os.path.normpath(path)
          dirs = []
          while dirname != os.path.dirname(dirname):
              if not os.path.exists(dirname):
                  dirs.append(dirname)
              dirname = os.path.dirname(dirname)
          os.makedirs(path, exist_ok=exist_ok)
  
          # store the directories in creation order, with the parent directory
          # before the child directories. Future calls of makedir() will not
          # create the parent directories, so the last element in the list is
          # the last one to be created. That is the first one to be removed on
          # __exit__
          dirs.reverse()
          self.dirs += dirs
  
      def __enter__(self):
          return self
  
      def __exit__(self, type, value, traceback):
          self.dirs.reverse()
          for d in self.dirs:
              append_to_log(self.lf, d)
  
  def is_executable(path, follow_symlinks=False):
      '''Checks whether any of the "x" bits are set in the source file mode.'''
      return bool(os.stat(path, follow_symlinks=follow_symlinks).st_mode & 0o111)
  
  def append_to_log
  
  [... the rest is omitted ...]
files: mesonbuild/minstall.py
files: # Copyright 2013-2014 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 sys, pickle, os, shutil, subprocess, gzip, errno
  import shlex
  import argparse
  from glob import glob
  from .scripts import depfixer
  from .scripts import destdir_join
  from .mesonlib import is_windows, Popen_safe
  from .mtest import rebuild_all
  try:
      from __main__ import __file__ as main_file
  except ImportError:
      # Happens when running as meson.exe which is native Windows.
      # This is only used for pkexec which is not, so this is fine.
      main_file = None
  
  symlink_warning = '''Warning: trying to copy a symlink that points to a file. This will copy the file,
  but this will be changed in a future version of Meson to copy the symlink as is. Please update your
  build definitions so that it will not break when the change happens.'''
  
  selinux_updates = []
  
  def buildparser():
      parser = argparse.ArgumentParser(prog='meson install')
      parser.add_argument('-C', default='.', dest='wd',
                          help='directory to cd into before running')
      parser.add_argument('--no-rebuild', default=False, action='store_true',
                          help='Do not rebuild before installing.')
      parser.add_argument('--only-changed', default=False, action='store_true',
                          help='Only overwrite files that are older than the copied file.')
      return parser
  
  class DirMaker:
      def __init__(self, lf):
          self.lf = lf
          self.dirs = []
  
      def makedirs(self, path, exist_ok=False):
          dirname = os.path.normpath(path)
          dirs = []
          while dirname != os.path.dirname(dirname):
              if not os.path.exists(dirname):
                  dirs.append(dirname)
              dirname = os.path.dirname(dirname)
          os.makedirs(path, exist_ok=exist_ok)
  
          # store the directories in creation order, with the parent directory
          # before the child directories. Future calls of makedir() will not
          # create the parent directories, so the last element in the list is
          # the last one to be created. That is the first one to be removed on
          # __exit__
          dirs.reverse()
          self.dirs += dirs
  
      def __enter__(self):
          return self
  
      def __exit__(self, type, value, traceback):
          self.dirs.reverse()
          for d in self.dirs:
              append_to_log(self.lf, d)
  
  def is_executable(path, follow_symlinks=False):
      '''Checks whether any of the "x" bits are set in the source file mode.'''
      return bool(os.stat(path, follow_symlinks
  
  [... the rest is omitted ...]
files: mesonbuild/minstall.py
files: # Copyright 2014-2016 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.
  
  """This is a helper script for IDE developers. It allows you to
  extract information such as list of targets, files, compiler flags,
  tests and so on. All output is in JSON for simple parsing.
  
  Currently only works for the Ninja backend. Others use generated
  project files and don't need this info."""
  
  import json
  from . import build, mtest, coredata as cdata
  from . import mesonlib
  from .backend import ninjabackend
  import sys, os
  import pathlib
  
  def add_arguments(parser):
      parser.add_argument('--targets', action='store_true', dest='list_targets', default=False,
                          help='List top level targets.')
      parser.add_argument('--installed', action='store_true', dest='list_installed', default=False,
                          help='List all installed files and directories.')
      parser.add_argument('--target-files', action='store', dest='target_files', default=None,
                          help='List source files for a given target.')
      parser.add_argument('--buildsystem-files', action='store_true', dest='buildsystem_files', default=False,
                          help='List files that make up the build system.')
      parser.add_argument('--buildoptions', action='store_true', dest='buildoptions', default=False,
                          help='List all build options.')
      parser.add_argument('--tests', action='store_true', dest='tests', default=False,
                          help='List all unit tests.')
      parser.add_argument('--benchmarks', action='store_true', dest='benchmarks', default=False,
                          help='List all benchmarks.')
      parser.add_argument('--dependencies', action='store_true', dest='dependencies', default=False,
                          help='List external dependencies.')
      parser.add_argument('--projectinfo', action='store_true', dest='projectinfo', default=False,
                          help='Information about projects.')
      parser.add_argument('builddir', nargs='?', default='.', help='The build directory')
  
  def determine_installed_path(target, installdata):
      install_target = None
      for i in installdata.targets:
          if os.path.basename(i.fname) == target.get_filename(): # FIXME, might clash due to subprojects.
              install_target = i
              break
      if install_target is None:
          raise RuntimeError('Something weird happened. File a bug.')
      outname = os.path.join(installdata.prefix, i.outdir, os.path.basename(i.fname))
      # Normalize the path by using os.path.sep consistently, etc.
      # Does not change the effective path.
      return str(pathlib.PurePath(outname))
  
  
  def list_installed(installdata):
      res = {}
      if installdata is not None:
          for
  
  [... the rest is omitted ...]
files: mesonbuild/mintro.py
files: # Copyright 2014-2016 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.
  
  """This is a helper script for IDE developers. It allows you to
  extract information such as list of targets, files, compiler flags,
  tests and so on. All output is in JSON for simple parsing.
  
  Currently only works for the Ninja backend. Others use generated
  project files and don't need this info."""
  
  import json
  from . import build, mtest, coredata as cdata
  from . import mesonlib
  from .backend import ninjabackend
  import argparse
  import sys, os
  import pathlib
  
  def buildparser():
      parser = argparse.ArgumentParser(prog='meson introspect')
      parser.add_argument('--targets', action='store_true', dest='list_targets', default=False,
                          help='List top level targets.')
      parser.add_argument('--installed', action='store_true', dest='list_installed', default=False,
                          help='List all installed files and directories.')
      parser.add_argument('--target-files', action='store', dest='target_files', default=None,
                          help='List source files for a given target.')
      parser.add_argument('--buildsystem-files', action='store_true', dest='buildsystem_files', default=False,
                          help='List files that make up the build system.')
      parser.add_argument('--buildoptions', action='store_true', dest='buildoptions', default=False,
                          help='List all build options.')
      parser.add_argument('--tests', action='store_true', dest='tests', default=False,
                          help='List all unit tests.')
      parser.add_argument('--benchmarks', action='store_true', dest='benchmarks', default=False,
                          help='List all benchmarks.')
      parser.add_argument('--dependencies', action='store_true', dest='dependencies', default=False,
                          help='List external dependencies.')
      parser.add_argument('--projectinfo', action='store_true', dest='projectinfo', default=False,
                          help='Information about projects.')
      parser.add_argument('builddir', nargs='?', default='.', help='The build directory')
      return parser
  
  def determine_installed_path(target, installdata):
      install_target = None
      for i in installdata.targets:
          if os.path.basename(i.fname) == target.get_filename(): # FIXME, might clash due to subprojects.
              install_target = i
              break
      if install_target is None:
          raise RuntimeError('Something weird happened. File a bug.')
      outname = os.path.join(installdata.prefix, i.outdir, os.path.basename(i.fname))
      # Normalize the path by using os.path.sep consistently, etc.
      # Does not change the effective path.
      return str(pathlib.PurePath(outname))
  
  
  def list_installed(
  
  [... the rest is omitted ...]
files: mesonbuild/mintro.py
files: # Copyright 2016-2018 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 time
  import sys, stat
  import datetime
  import os.path
  import platform
  import cProfile as profile
  import argparse
  
  from . import environment, interpreter, mesonlib
  from . import build
  from . import mlog, coredata
  from .mesonlib import MesonException
  from .wrap import WrapMode
  
  def add_arguments(parser):
      coredata.register_builtin_arguments(parser)
      parser.add_argument('--cross-file', default=None,
                          help='File describing cross compilation environment.')
      parser.add_argument('-v', '--version', action='version',
                          version=coredata.version)
      # See the mesonlib.WrapMode enum for documentation
      parser.add_argument('--wrap-mode', default=None,
                          type=wrapmodetype, choices=WrapMode,
                          help='Special wrap mode to use')
      parser.add_argument('--profile-self', action='store_true', dest='profile',
                          help=argparse.SUPPRESS)
      parser.add_argument('--fatal-meson-warnings', action='store_true', dest='fatal_warnings',
                          help='Make all Meson warnings fatal')
      parser.add_argument('--reconfigure', action='store_true',
                          help='Set options and reconfigure the project. Useful when new ' +
                               'options have been added to the project and the default value ' +
                               'is not working.')
      parser.add_argument('builddir', nargs='?', default=None)
      parser.add_argument('sourcedir', nargs='?', default=None)
  
  def wrapmodetype(string):
      try:
          return getattr(WrapMode, string)
      except AttributeError:
          msg = ', '.join([t.name.lower() for t in WrapMode])
          msg = 'invalid argument {!r}, use one of {}'.format(string, msg)
          raise argparse.ArgumentTypeError(msg)
  
  class MesonApp:
      def __init__(self, options):
          (self.source_dir, self.build_dir) = self.validate_dirs(options.builddir,
                                                                 options.sourcedir,
                                                                 options.reconfigure)
          self.options = options
  
      def has_build_file(self, dirname):
          fname = os.path.join(dirname, environment.build_filename)
          return os.path.exists(fname)
  
      def validate_core_dirs(self, dir1, dir2):
          if dir1 is None:
              if dir2 is None:
                  if not os.path.exists('meson.build') and os.path.exists('../meson.build'):
                      dir2 = '..'
                  else:
                      raise MesonException('Must specify at least one directory name.')
              dir1 = os.getcwd()
          if dir2 is None:
              dir2 = os.getcwd()
          ndir1 = os.path.abspath(os.path.real
  
  [... the rest is omitted ...]
files: mesonbuild/msetup.py
files: # Copyright 2016-2018 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 time
  import sys, stat
  import datetime
  import os.path
  import platform
  import cProfile as profile
  import argparse
  import traceback
  
  from . import environment, interpreter, mesonlib
  from . import build
  from . import mlog, coredata
  from .mesonlib import MesonException
  from .wrap import WrapMode
  
  def buildparser():
      parser = argparse.ArgumentParser(prog='meson')
      coredata.register_builtin_arguments(parser)
      parser.add_argument('--cross-file', default=None,
                          help='File describing cross compilation environment.')
      parser.add_argument('-v', '--version', action='version',
                          version=coredata.version)
      # See the mesonlib.WrapMode enum for documentation
      parser.add_argument('--wrap-mode', default=None,
                          type=wrapmodetype, choices=WrapMode,
                          help='Special wrap mode to use')
      parser.add_argument('--profile-self', action='store_true', dest='profile',
                          help=argparse.SUPPRESS)
      parser.add_argument('--fatal-meson-warnings', action='store_true', dest='fatal_warnings',
                          help='Make all Meson warnings fatal')
      parser.add_argument('--reconfigure', action='store_true',
                          help='Set options and reconfigure the project. Useful when new ' +
                               'options have been added to the project and the default value ' +
                               'is not working.')
      parser.add_argument('builddir', nargs='?', default=None)
      parser.add_argument('sourcedir', nargs='?', default=None)
      return parser
  
  def wrapmodetype(string):
      try:
          return getattr(WrapMode, string)
      except AttributeError:
          msg = ', '.join([t.name.lower() for t in WrapMode])
          msg = 'invalid argument {!r}, use one of {}'.format(string, msg)
          raise argparse.ArgumentTypeError(msg)
  
  class MesonApp:
      def __init__(self, options):
          (self.source_dir, self.build_dir) = self.validate_dirs(options.builddir,
                                                                 options.sourcedir,
                                                                 options.reconfigure)
          self.options = options
  
      def has_build_file(self, dirname):
          fname = os.path.join(dirname, environment.build_filename)
          return os.path.exists(fname)
  
      def validate_core_dirs(self, dir1, dir2):
          if dir1 is None:
              if dir2 is None:
                  if not os.path.exists('meson.build') and os.path.exists('../meson.build'):
                      dir2 = '..'
                  else:
                      raise MesonException('Must specify at least one directory name.')
              dir1 = os.getcwd()
          if dir2 is None:
              dir2 =
  
  [... the rest is omitted ...]
files: mesonbuild/msetup.py
files: # Copyright 2016-2017 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.
  
  # A tool to run tests in many different ways.
  
  import shlex
  import subprocess, sys, os, argparse
  import pickle
  from mesonbuild import build
  from mesonbuild import environment
  from mesonbuild.dependencies import ExternalProgram
  from mesonbuild.mesonlib import substring_is_in_list, MesonException
  from mesonbuild import mlog
  
  import time, datetime, multiprocessing, json
  import concurrent.futures as conc
  import platform
  import signal
  import random
  from copy import deepcopy
  import enum
  
  # GNU autotools interprets a return code of 77 from tests it executes to
  # mean that the test should be skipped.
  GNU_SKIP_RETURNCODE = 77
  
  def is_windows():
      platname = platform.system().lower()
      return platname == 'windows' or 'mingw' in platname
  
  def is_cygwin():
      platname = platform.system().lower()
      return 'cygwin' in platname
  
  def determine_worker_count():
      varname = 'MESON_TESTTHREADS'
      if varname in os.environ:
          try:
              num_workers = int(os.environ[varname])
          except ValueError:
              print('Invalid value in %s, using 1 thread.' % varname)
              num_workers = 1
      else:
          try:
              # Fails in some weird environments such as Debian
              # reproducible build.
              num_workers = multiprocessing.cpu_count()
          except Exception:
              num_workers = 1
      return num_workers
  
  def add_arguments(parser):
      parser.add_argument('--repeat', default=1, dest='repeat', type=int,
                          help='Number of times to run the tests.')
      parser.add_argument('--no-rebuild', default=False, action='store_true',
                          help='Do not rebuild before running tests.')
      parser.add_argument('--gdb', default=False, dest='gdb', action='store_true',
                          help='Run test under gdb.')
      parser.add_argument('--list', default=False, dest='list', action='store_true',
                          help='List available tests.')
      parser.add_argument('--wrapper', default=None, dest='wrapper', type=shlex.split,
                          help='wrapper to run tests with (e.g. Valgrind)')
      parser.add_argument('-C', default='.', dest='wd',
                          help='directory to cd into before running')
      parser.add_argument('--suite', default=[], dest='include_suites', action='append', metavar='SUITE',
                          help='Only run tests belonging to the given suite.')
      parser.add_argument('--no-suite', default=[], dest='exclude_suites', action='append', metavar
  
  [... the rest is omitted ...]
files: mesonbuild/mtest.py
files: # Copyright 2016-2017 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.
  
  # A tool to run tests in many different ways.
  
  import shlex
  import subprocess, sys, os, argparse
  import pickle
  from mesonbuild import build
  from mesonbuild import environment
  from mesonbuild.dependencies import ExternalProgram
  from mesonbuild.mesonlib import substring_is_in_list, MesonException
  from mesonbuild import mlog
  
  import time, datetime, multiprocessing, json
  import concurrent.futures as conc
  import platform
  import signal
  import random
  from copy import deepcopy
  import enum
  
  # GNU autotools interprets a return code of 77 from tests it executes to
  # mean that the test should be skipped.
  GNU_SKIP_RETURNCODE = 77
  
  def is_windows():
      platname = platform.system().lower()
      return platname == 'windows' or 'mingw' in platname
  
  def is_cygwin():
      platname = platform.system().lower()
      return 'cygwin' in platname
  
  def determine_worker_count():
      varname = 'MESON_TESTTHREADS'
      if varname in os.environ:
          try:
              num_workers = int(os.environ[varname])
          except ValueError:
              print('Invalid value in %s, using 1 thread.' % varname)
              num_workers = 1
      else:
          try:
              # Fails in some weird environments such as Debian
              # reproducible build.
              num_workers = multiprocessing.cpu_count()
          except Exception:
              num_workers = 1
      return num_workers
  
  def buildparser():
      parser = argparse.ArgumentParser(prog='meson test')
      parser.add_argument('--repeat', default=1, dest='repeat', type=int,
                          help='Number of times to run the tests.')
      parser.add_argument('--no-rebuild', default=False, action='store_true',
                          help='Do not rebuild before running tests.')
      parser.add_argument('--gdb', default=False, dest='gdb', action='store_true',
                          help='Run test under gdb.')
      parser.add_argument('--list', default=False, dest='list', action='store_true',
                          help='List available tests.')
      parser.add_argument('--wrapper', default=None, dest='wrapper', type=shlex.split,
                          help='wrapper to run tests with (e.g. Valgrind)')
      parser.add_argument('-C', default='.', dest='wd',
                          help='directory to cd into before running')
      parser.add_argument('--suite', default=[], dest='include_suites', action='append', metavar='SUITE',
                          help='Only run tests belonging to the given suite.')
      parser.add_argument('--no-suite', default=[], dest='
  
  [... the rest is omitted ...]
files: mesonbuild/mtest.py
files: #!/usr/bin/env python3
  # Copyright 2016 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.
  
  # This class contains the basic functionality needed to run any interpreter
  # or an interpreter-based tool.
  
  # This tool is used to manipulate an existing Meson build definition.
  #
  # - add a file to a target
  # - remove files from a target
  # - move targets
  # - reindent?
  
  import mesonbuild.astinterpreter
  from mesonbuild.mesonlib import MesonException
  from mesonbuild import mlog
  import sys, traceback
  
  def add_arguments(parser):
      parser.add_argument('--sourcedir', default='.',
                          help='Path to source directory.')
      parser.add_argument('--target', default=None,
                          help='Name of target to edit.')
      parser.add_argument('--filename', default=None,
                          help='Name of source file to add or remove to target.')
      parser.add_argument('commands', nargs='+')
  
  def run(options):
      if options.target is None or options.filename is None:
          sys.exit("Must specify both target and filename.")
      print('This tool is highly experimental, use with care.')
      rewriter = mesonbuild.astinterpreter.AstInterpreter(options.sourcedir, '')
      try:
          if options.commands[0] == 'add':
              rewriter.add_source(options.target, options.filename)
          elif options.commands[0] == 'remove':
              rewriter.remove_source(options.target, options.filename)
          else:
              sys.exit('Unknown command: ' + options.commands[0])
      except Exception as e:
          if isinstance(e, MesonException):
              mlog.exception(e)
          else:
              traceback.print_exc()
          return 1
      return 0
  
  
  [... the rest is omitted ...]
files: mesonbuild/rewriter.py
files: #!/usr/bin/env python3
  # Copyright 2016 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.
  
  # This class contains the basic functionality needed to run any interpreter
  # or an interpreter-based tool.
  
  # This tool is used to manipulate an existing Meson build definition.
  #
  # - add a file to a target
  # - remove files from a target
  # - move targets
  # - reindent?
  
  import mesonbuild.astinterpreter
  from mesonbuild.mesonlib import MesonException
  from mesonbuild import mlog
  import sys, traceback
  import argparse
  
  def buildparser():
      parser = argparse.ArgumentParser(prog='meson rewrite')
  
      parser.add_argument('--sourcedir', default='.',
                          help='Path to source directory.')
      parser.add_argument('--target', default=None,
                          help='Name of target to edit.')
      parser.add_argument('--filename', default=None,
                          help='Name of source file to add or remove to target.')
      parser.add_argument('commands', nargs='+')
      return parser
  
  def run(args):
      options = buildparser().parse_args(args)
      if options.target is None or options.filename is None:
          sys.exit("Must specify both target and filename.")
      print('This tool is highly experimental, use with care.')
      rewriter = mesonbuild.astinterpreter.AstInterpreter(options.sourcedir, '')
      try:
          if options.commands[0] == 'add':
              rewriter.add_source(options.target, options.filename)
          elif options.commands[0] == 'remove':
              rewriter.remove_source(options.target, options.filename)
          else:
              sys.exit('Unknown command: ' + options.commands[0])
      except Exception as e:
          if isinstance(e, MesonException):
              mlog.exception(e)
          else:
              traceback.print_exc()
          return 1
      return 0
  
  
  [... the rest is omitted ...]
files: mesonbuild/rewriter.py
files: # Copyright 2015-2016 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 json
  import sys, os
  import configparser
  import shutil
  
  from glob import glob
  
  from .wrap import API_ROOT, open_wrapdburl
  
  from .. import mesonlib
  
  def add_arguments(parser):
      subparsers = parser.add_subparsers(title='Commands', dest='command')
      subparsers.required = True
  
      p = subparsers.add_parser('list', help='show all available projects')
      p.set_defaults(wrap_func=list_projects)
  
      p = subparsers.add_parser('search', help='search the db by name')
      p.add_argument('name')
      p.set_defaults(wrap_func=search)
  
      p = subparsers.add_parser('install', help='install the specified project')
      p.add_argument('name')
      p.set_defaults(wrap_func=install)
  
      p = subparsers.add_parser('update', help='update the project to its newest available release')
      p.add_argument('name')
      p.set_defaults(wrap_func=update)
  
      p = subparsers.add_parser('info', help='show available versions of a project')
      p.add_argument('name')
      p.set_defaults(wrap_func=info)
  
      p = subparsers.add_parser('status', help='show installed and available versions of your projects')
      p.set_defaults(wrap_func=status)
  
      p = subparsers.add_parser('promote', help='bring a subsubproject up to the master project')
      p.add_argument('project_path')
      p.set_defaults(wrap_func=promote)
  
  def get_result(urlstring):
      u = open_wrapdburl(urlstring)
      data = u.read().decode('utf-8')
      jd = json.loads(data)
      if jd['output'] != 'ok':
          print('Got bad output from server.')
          print(data)
          sys.exit(1)
      return jd
  
  def get_projectlist():
      jd = get_result(API_ROOT + 'projects')
      projects = jd['projects']
      return projects
  
  def list_projects(options):
      projects = get_projectlist()
      for p in projects:
          print(p)
  
  def search(options):
      name = options.name
      jd = get_result(API_ROOT + 'query/byname/' + name)
      for p in jd['projects']:
          print(p)
  
  def get_latest_version(name):
      jd = get_result(API_ROOT + 'query/get_latest/' + name)
      branch = jd['branch']
      revision = jd['revision']
      return branch, revision
  
  def install(options):
      name = options.name
      if not os.path.isdir('subprojects'):
          print('Subprojects dir not found. Run this script in your source
  
  [... the rest is omitted ...]
files: mesonbuild/wrap/wraptool.py
files: # Copyright 2015-2016 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 json
  import sys, os
  import configparser
  import shutil
  import argparse
  
  from glob import glob
  
  from .wrap import API_ROOT, open_wrapdburl
  
  from .. import mesonlib
  
  def add_arguments(parser):
      subparsers = parser.add_subparsers(title='Commands', dest='command')
      subparsers.required = True
  
      p = subparsers.add_parser('list', help='show all available projects')
      p.set_defaults(wrap_func=list_projects)
  
      p = subparsers.add_parser('search', help='search the db by name')
      p.add_argument('name')
      p.set_defaults(wrap_func=search)
  
      p = subparsers.add_parser('install', help='install the specified project')
      p.add_argument('name')
      p.set_defaults(wrap_func=install)
  
      p = subparsers.add_parser('update', help='update the project to its newest available release')
      p.add_argument('name')
      p.set_defaults(wrap_func=update)
  
      p = subparsers.add_parser('info', help='show available versions of a project')
      p.add_argument('name')
      p.set_defaults(wrap_func=info)
  
      p = subparsers.add_parser('status', help='show installed and available versions of your projects')
      p.set_defaults(wrap_func=status)
  
      p = subparsers.add_parser('promote', help='bring a subsubproject up to the master project')
      p.add_argument('project_path')
      p.set_defaults(wrap_func=promote)
  
  def get_result(urlstring):
      u = open_wrapdburl(urlstring)
      data = u.read().decode('utf-8')
      jd = json.loads(data)
      if jd['output'] != 'ok':
          print('Got bad output from server.')
          print(data)
          sys.exit(1)
      return jd
  
  def get_projectlist():
      jd = get_result(API_ROOT + 'projects')
      projects = jd['projects']
      return projects
  
  def list_projects(options):
      projects = get_projectlist()
      for p in projects:
          print(p)
  
  def search(options):
      name = options.name
      jd = get_result(API_ROOT + 'query/byname/' + name)
      for p in jd['projects']:
          print(p)
  
  def get_latest_version(name):
      jd = get_result(API_ROOT + 'query/get_latest/' + name)
      branch = jd['branch']
      revision = jd['revision']
      return branch, revision
  
  def install(options):
      name = options.name
      if not os.path.isdir('subprojects'):
          print('Subprojects dir not found. Run this script
  
  [... the rest is omitted ...]
files: mesonbuild/wrap/wraptool.py
files: #!/usr/bin/env python3
  
  # Copyright 2012-2016 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 itertools
  import os
  import subprocess
  import shutil
  import sys
  import signal
  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 mesonlib
  from mesonbuild import mlog
  from mesonbuild import mtest
  from mesonbuild.mesonlib import stringlistify, Popen_safe
  from mesonbuild.coredata import backendlist
  import argparse
  import xml.etree.ElementTree as ET
  import time
  import multiprocessing
  from concurrent.futures import ProcessPoolExecutor
  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
  
  
  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, conftime=0, buildtime=0, testtime=0):
          self.msg = msg
          self.step = step
          self.stdo = stdo
          self.stde = stde
          self.mlog = mlog
          self.conftime = conftime
          self.buildtime = buildtime
          self.testtime = testtime
  
  
  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 = not {'TRAVIS', 'APPVEYOR'}.isdisjoint(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
  
  [... the rest is omitted ...]
files: run_project_tests.py
files: #!/usr/bin/env python3
  
  # Copyright 2012-2016 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 itertools
  import os
  import subprocess
  import shutil
  import sys
  import signal
  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 mesonlib
  from mesonbuild import mlog
  from mesonbuild import mtest
  from mesonbuild.mesonlib import stringlistify, Popen_safe
  from mesonbuild.coredata import backendlist
  import argparse
  import xml.etree.ElementTree as ET
  import time
  import multiprocessing
  from concurrent.futures import ProcessPoolExecutor
  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
  
  
  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, conftime=0, buildtime=0, testtime=0):
          self.msg = msg
          self.step = step
          self.stdo = stdo
          self.stde = stde
          self.mlog = mlog
          self.conftime = conftime
          self.buildtime = buildtime
          self.testtime = testtime
  
  
  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 = not {'TRAVIS', 'APPVEYOR'}.isdisjoint(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
  
  [... the rest is omitted ...]
files: run_project_tests.py
files: #!/usr/bin/env python3
  
  # Copyright 2012-2017 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 os
  import sys
  import time
  import shutil
  import subprocess
  import tempfile
  import platform
  from io import StringIO
  from enum import Enum
  from glob import glob
  from pathlib import Path
  
  import mesonbuild
  from mesonbuild import mesonlib
  from mesonbuild import mesonmain
  from mesonbuild import mtest
  from mesonbuild import mlog
  from mesonbuild.environment import Environment, detect_ninja
  
  
  # Fake classes and objects for mocking
  class FakeBuild:
      def __init__(self, env):
          self.environment = env
  
  class FakeCompilerOptions:
      def __init__(self):
          self.value = []
  
  def get_fake_options(prefix):
      import argparse
      opts = argparse.Namespace()
      opts.cross_file = None
      opts.wrap_mode = None
      opts.prefix = prefix
      opts.cmd_line_options = {}
      return opts
  
  def get_fake_env(sdir, bdir, prefix):
      env = Environment(sdir, bdir, get_fake_options(prefix))
      env.coredata.compiler_options['c_args'] = FakeCompilerOptions()
      return env
  
  
  Backend = Enum('Backend', 'ninja vs xcode')
  
  if 'MESON_EXE' in os.environ:
      import shlex
      meson_exe = shlex.split(os.environ['MESON_EXE'])
  else:
      meson_exe = None
  
  if mesonlib.is_windows() or mesonlib.is_cygwin():
      exe_suffix = '.exe'
  else:
      exe_suffix = ''
  
  def get_meson_script():
      '''
      Guess the meson that corresponds to the `mesonbuild` that has been imported
      so we can run configure and other commands in-process, since mesonmain.run
      needs to know the meson_command to use.
  
      Also used by run_unittests.py to determine what meson to run when not
      running in-process (which is the default).
      '''
      # Is there a meson.py next to the mesonbuild currently in use?
      mesonbuild_dir = Path(mesonbuild.__file__).resolve().parent.parent
      meson_script = mesonbuild_dir / 'meson.py'
      if meson_script.is_file():
          return str(meson_script)
      # Then if mesonbuild is in PYTHONPATH, meson must be in PATH
      mlog.warning('Could not find meson.py next to the mesonbuild module. '
                   'Trying system meson...')
      meson_cmd = shutil.which('meson')
      if meson_cmd:
          return meson_cmd
  
  
  [... the rest is omitted ...]
files: run_tests.py
files: #!/usr/bin/env python3
  
  # Copyright 2012-2017 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 os
  import sys
  import time
  import shutil
  import subprocess
  import tempfile
  import platform
  from io import StringIO
  from enum import Enum
  from glob import glob
  from pathlib import Path
  
  import mesonbuild
  from mesonbuild import mesonlib
  from mesonbuild import mesonmain
  from mesonbuild import mtest
  from mesonbuild import mlog
  from mesonbuild.environment import Environment, detect_ninja
  
  
  # Fake classes and objects for mocking
  class FakeBuild:
      def __init__(self, env):
          self.environment = env
  
  class FakeCompilerOptions:
      def __init__(self):
          self.value = []
  
  def get_fake_options(prefix):
      import argparse
      opts = argparse.Namespace()
      opts.cross_file = None
      opts.wrap_mode = None
      opts.prefix = prefix
      opts.cmd_line_options = {}
      return opts
  
  def get_fake_env(sdir, bdir, prefix):
      env = Environment(sdir, bdir, get_fake_options(prefix))
      env.coredata.compiler_options['c_args'] = FakeCompilerOptions()
      return env
  
  
  Backend = Enum('Backend', 'ninja vs xcode')
  
  if 'MESON_EXE' in os.environ:
      import shlex
      meson_exe = shlex.split(os.environ['MESON_EXE'])
  else:
      meson_exe = None
  
  if mesonlib.is_windows() or mesonlib.is_cygwin():
      exe_suffix = '.exe'
  else:
      exe_suffix = ''
  
  def get_meson_script():
      '''
      Guess the meson that corresponds to the `mesonbuild` that has been imported
      so we can run configure and other commands in-process, since mesonmain.run
      needs to know the meson_command to use.
  
      Also used by run_unittests.py to determine what meson to run when not
      running in-process (which is the default).
      '''
      # Is there a meson.py next to the mesonbuild currently in use?
      mesonbuild_dir = Path(mesonbuild.__file__).resolve().parent.parent
      meson_script = mesonbuild_dir / 'meson.py'
      if meson_script.is_file():
          return str(meson_script)
      # Then if mesonbuild is in PYTHONPATH, meson must be in PATH
      mlog.warning('Could not find meson.py next to the mesonbuild module. '
                   'Trying system meson...')
      meson_cmd = shutil.which('meson')
      if meson_cmd:
          return meson_cmd
  
  
  [... the rest is omitted ...]
files: run_tests.py