msetup.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. # Copyright 2016-2018 The Meson development team
  2. # Licensed under the Apache License, Version 2.0 (the "License");
  3. # you may not use this file except in compliance with the License.
  4. # You may obtain a copy of the License at
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. # Unless required by applicable law or agreed to in writing, software
  7. # distributed under the License is distributed on an "AS IS" BASIS,
  8. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. # See the License for the specific language governing permissions and
  10. # limitations under the License.
  11. import time
  12. import sys, stat
  13. import datetime
  14. import os.path
  15. import platform
  16. import cProfile as profile
  17. import argparse
  18. from . import environment, interpreter, mesonlib
  19. from . import build
  20. from . import mlog, coredata
  21. from . import mintro
  22. from .mconf import make_lower_case
  23. from .mesonlib import MesonException
  24. def add_arguments(parser):
  25. coredata.register_builtin_arguments(parser)
  26. parser.add_argument('--cross-file', default=None,
  27. help='File describing cross compilation environment.')
  28. parser.add_argument('--native-file',
  29. default=[],
  30. action='append',
  31. help='File containing overrides for native compilation environment.')
  32. parser.add_argument('-v', '--version', action='version',
  33. version=coredata.version)
  34. parser.add_argument('--profile-self', action='store_true', dest='profile',
  35. help=argparse.SUPPRESS)
  36. parser.add_argument('--fatal-meson-warnings', action='store_true', dest='fatal_warnings',
  37. help='Make all Meson warnings fatal')
  38. parser.add_argument('--reconfigure', action='store_true',
  39. help='Set options and reconfigure the project. Useful when new ' +
  40. 'options have been added to the project and the default value ' +
  41. 'is not working.')
  42. parser.add_argument('--wipe', action='store_true',
  43. help='Wipe build directory and reconfigure using previous command line options. ' +
  44. 'Userful when build directory got corrupted, or when rebuilding with a ' +
  45. 'newer version of meson.')
  46. parser.add_argument('builddir', nargs='?', default=None)
  47. parser.add_argument('sourcedir', nargs='?', default=None)
  48. class MesonApp:
  49. def __init__(self, options):
  50. (self.source_dir, self.build_dir) = self.validate_dirs(options.builddir,
  51. options.sourcedir,
  52. options.reconfigure,
  53. options.wipe)
  54. if options.wipe:
  55. # Make a copy of the cmd line file to make sure we can always
  56. # restore that file if anything bad happens. For example if
  57. # configuration fails we need to be able to wipe again.
  58. filename = coredata.get_cmd_line_file(self.build_dir)
  59. try:
  60. with open(filename, 'r') as f:
  61. content = f.read()
  62. except FileNotFoundError:
  63. raise MesonException(
  64. 'Cannot find cmd_line.txt. This is probably because this '
  65. 'build directory was configured with a meson version < 0.49.0.')
  66. coredata.read_cmd_line_file(self.build_dir, options)
  67. try:
  68. # Don't delete the whole tree, just all of the files and
  69. # folders in the tree. Otherwise calling wipe form the builddir
  70. # will cause a crash
  71. for l in os.listdir(self.build_dir):
  72. l = os.path.join(self.build_dir, l)
  73. if os.path.isdir(l):
  74. mesonlib.windows_proof_rmtree(l)
  75. else:
  76. mesonlib.windows_proof_rm(l)
  77. finally:
  78. # Restore the file
  79. path = os.path.dirname(filename)
  80. os.makedirs(path, exist_ok=True)
  81. with open(filename, 'w') as f:
  82. f.write(content)
  83. self.options = options
  84. def has_build_file(self, dirname):
  85. fname = os.path.join(dirname, environment.build_filename)
  86. return os.path.exists(fname)
  87. def validate_core_dirs(self, dir1, dir2):
  88. if dir1 is None:
  89. if dir2 is None:
  90. if not os.path.exists('meson.build') and os.path.exists('../meson.build'):
  91. dir2 = '..'
  92. else:
  93. raise MesonException('Must specify at least one directory name.')
  94. dir1 = os.getcwd()
  95. if dir2 is None:
  96. dir2 = os.getcwd()
  97. ndir1 = os.path.abspath(os.path.realpath(dir1))
  98. ndir2 = os.path.abspath(os.path.realpath(dir2))
  99. if not os.path.exists(ndir1):
  100. os.makedirs(ndir1)
  101. if not os.path.exists(ndir2):
  102. os.makedirs(ndir2)
  103. if not stat.S_ISDIR(os.stat(ndir1).st_mode):
  104. raise MesonException('%s is not a directory' % dir1)
  105. if not stat.S_ISDIR(os.stat(ndir2).st_mode):
  106. raise MesonException('%s is not a directory' % dir2)
  107. if os.path.samefile(dir1, dir2):
  108. raise MesonException('Source and build directories must not be the same. Create a pristine build directory.')
  109. if self.has_build_file(ndir1):
  110. if self.has_build_file(ndir2):
  111. raise MesonException('Both directories contain a build file %s.' % environment.build_filename)
  112. return ndir1, ndir2
  113. if self.has_build_file(ndir2):
  114. return ndir2, ndir1
  115. raise MesonException('Neither directory contains a build file %s.' % environment.build_filename)
  116. def validate_dirs(self, dir1, dir2, reconfigure, wipe):
  117. (src_dir, build_dir) = self.validate_core_dirs(dir1, dir2)
  118. priv_dir = os.path.join(build_dir, 'meson-private/coredata.dat')
  119. if os.path.exists(priv_dir):
  120. if not reconfigure and not wipe:
  121. print('Directory already configured.\n'
  122. '\nJust run your build command (e.g. ninja) and Meson will regenerate as necessary.\n'
  123. 'If ninja fails, run "ninja reconfigure" or "meson --reconfigure"\n'
  124. 'to force Meson to regenerate.\n'
  125. '\nIf build failures persist, run "meson setup --wipe" to rebuild from scratch\n'
  126. 'using the same options as passed when configuring the build.'
  127. '\nTo change option values, run "meson configure" instead.')
  128. sys.exit(0)
  129. else:
  130. has_cmd_line_file = os.path.exists(coredata.get_cmd_line_file(build_dir))
  131. if (wipe and not has_cmd_line_file) or (not wipe and reconfigure):
  132. print('Directory does not contain a valid build tree:\n{}'.format(build_dir))
  133. sys.exit(1)
  134. return src_dir, build_dir
  135. def check_pkgconfig_envvar(self, env):
  136. curvar = os.environ.get('PKG_CONFIG_PATH', '')
  137. if curvar != env.coredata.pkgconf_envvar:
  138. mlog.warning('PKG_CONFIG_PATH has changed between invocations from "%s" to "%s".' %
  139. (env.coredata.pkgconf_envvar, curvar))
  140. env.coredata.pkgconf_envvar = curvar
  141. def generate(self):
  142. env = environment.Environment(self.source_dir, self.build_dir, self.options)
  143. mlog.initialize(env.get_log_dir(), self.options.fatal_warnings)
  144. if self.options.profile:
  145. mlog.set_timestamp_start(time.monotonic())
  146. with mesonlib.BuildDirLock(self.build_dir):
  147. self._generate(env)
  148. def _generate(self, env):
  149. mlog.debug('Build started at', datetime.datetime.now().isoformat())
  150. mlog.debug('Main binary:', sys.executable)
  151. mlog.debug('Python system:', platform.system())
  152. mlog.log(mlog.bold('The Meson build system'))
  153. self.check_pkgconfig_envvar(env)
  154. mlog.log('Version:', coredata.version)
  155. mlog.log('Source dir:', mlog.bold(self.source_dir))
  156. mlog.log('Build dir:', mlog.bold(self.build_dir))
  157. if env.is_cross_build():
  158. mlog.log('Build type:', mlog.bold('cross build'))
  159. else:
  160. mlog.log('Build type:', mlog.bold('native build'))
  161. b = build.Build(env)
  162. intr = interpreter.Interpreter(b)
  163. if env.is_cross_build():
  164. mlog.log('Host machine cpu family:', mlog.bold(intr.builtin['host_machine'].cpu_family_method([], {})))
  165. mlog.log('Host machine cpu:', mlog.bold(intr.builtin['host_machine'].cpu_method([], {})))
  166. mlog.log('Target machine cpu family:', mlog.bold(intr.builtin['target_machine'].cpu_family_method([], {})))
  167. mlog.log('Target machine cpu:', mlog.bold(intr.builtin['target_machine'].cpu_method([], {})))
  168. mlog.log('Build machine cpu family:', mlog.bold(intr.builtin['build_machine'].cpu_family_method([], {})))
  169. mlog.log('Build machine cpu:', mlog.bold(intr.builtin['build_machine'].cpu_method([], {})))
  170. try:
  171. if self.options.profile:
  172. fname = os.path.join(self.build_dir, 'meson-private', 'profile-interpreter.log')
  173. profile.runctx('intr.run()', globals(), locals(), filename=fname)
  174. else:
  175. intr.run()
  176. except Exception as e:
  177. mintro.write_meson_info_file(b, [e])
  178. raise
  179. # Print all default option values that don't match the current value
  180. for def_opt_name, def_opt_value, cur_opt_value in intr.get_non_matching_default_options():
  181. mlog.log('Option', mlog.bold(def_opt_name), 'is:',
  182. mlog.bold(make_lower_case(cur_opt_value.printable_value())),
  183. '[default: {}]'.format(make_lower_case(def_opt_value)))
  184. try:
  185. dumpfile = os.path.join(env.get_scratch_dir(), 'build.dat')
  186. # We would like to write coredata as late as possible since we use the existence of
  187. # this file to check if we generated the build file successfully. Since coredata
  188. # includes settings, the build files must depend on it and appear newer. However, due
  189. # to various kernel caches, we cannot guarantee that any time in Python is exactly in
  190. # sync with the time that gets applied to any files. Thus, we dump this file as late as
  191. # possible, but before build files, and if any error occurs, delete it.
  192. cdf = env.dump_coredata()
  193. if self.options.profile:
  194. fname = 'profile-{}-backend.log'.format(intr.backend.name)
  195. fname = os.path.join(self.build_dir, 'meson-private', fname)
  196. profile.runctx('intr.backend.generate(intr)', globals(), locals(), filename=fname)
  197. else:
  198. intr.backend.generate(intr)
  199. build.save(b, dumpfile)
  200. # Post-conf scripts must be run after writing coredata or else introspection fails.
  201. intr.backend.run_postconf_scripts()
  202. if env.first_invocation:
  203. coredata.write_cmd_line_file(self.build_dir, self.options)
  204. else:
  205. coredata.update_cmd_line_file(self.build_dir, self.options)
  206. # Generate an IDE introspection file with the same syntax as the already existing API
  207. if self.options.profile:
  208. fname = os.path.join(self.build_dir, 'meson-private', 'profile-introspector.log')
  209. profile.runctx('mintro.generate_introspection_file(b, intr.backend)', globals(), locals(), filename=fname)
  210. else:
  211. mintro.generate_introspection_file(b, intr.backend)
  212. mintro.write_meson_info_file(b, [], True)
  213. except Exception as e:
  214. mintro.write_meson_info_file(b, [e])
  215. if 'cdf' in locals():
  216. old_cdf = cdf + '.prev'
  217. if os.path.exists(old_cdf):
  218. os.replace(old_cdf, cdf)
  219. else:
  220. os.unlink(cdf)
  221. raise
  222. def run(options):
  223. coredata.parse_cmd_line_options(options)
  224. app = MesonApp(options)
  225. app.generate()
  226. return 0