mesonmain.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. # Copyright 2012-2016 The Meson development team
  2. # Licensed under the Apache License, Version 2.0 (the "License");
  3. # you may not use this file except in compliance with the License.
  4. # You may obtain a copy of the License at
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. # Unless required by applicable law or agreed to in writing, software
  7. # distributed under the License is distributed on an "AS IS" BASIS,
  8. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. # See the License for the specific language governing permissions and
  10. # limitations under the License.
  11. import sys, stat, traceback, pickle, argparse
  12. import time, datetime
  13. import os.path
  14. from . import environment, interpreter, mesonlib
  15. from . import build
  16. from . import mconf, mintro, mtest, rewriter
  17. import platform
  18. from . import mlog, coredata
  19. from .mesonlib import MesonException
  20. from .wrap import WrapMode, wraptool
  21. default_warning = '1'
  22. def add_builtin_argument(p, name, **kwargs):
  23. k = kwargs.get('dest', name.replace('-', '_'))
  24. c = coredata.get_builtin_option_choices(k)
  25. b = True if kwargs.get('action', None) in ['store_true', 'store_false'] else False
  26. h = coredata.get_builtin_option_description(k)
  27. if not b:
  28. h = h.rstrip('.') + ' (default: %s).' % coredata.get_builtin_option_default(k)
  29. if c and not b:
  30. kwargs['choices'] = c
  31. default = coredata.get_builtin_option_default(k, noneIfSuppress=True)
  32. if default is not None:
  33. kwargs['default'] = default
  34. else:
  35. kwargs['default'] = argparse.SUPPRESS
  36. p.add_argument('--' + name, help=h, **kwargs)
  37. def create_parser():
  38. p = argparse.ArgumentParser(prog='meson')
  39. add_builtin_argument(p, 'prefix')
  40. add_builtin_argument(p, 'libdir')
  41. add_builtin_argument(p, 'libexecdir')
  42. add_builtin_argument(p, 'bindir')
  43. add_builtin_argument(p, 'sbindir')
  44. add_builtin_argument(p, 'includedir')
  45. add_builtin_argument(p, 'datadir')
  46. add_builtin_argument(p, 'mandir')
  47. add_builtin_argument(p, 'infodir')
  48. add_builtin_argument(p, 'localedir')
  49. add_builtin_argument(p, 'sysconfdir')
  50. add_builtin_argument(p, 'localstatedir')
  51. add_builtin_argument(p, 'sharedstatedir')
  52. add_builtin_argument(p, 'backend')
  53. add_builtin_argument(p, 'buildtype')
  54. add_builtin_argument(p, 'strip', action='store_true')
  55. add_builtin_argument(p, 'unity')
  56. add_builtin_argument(p, 'werror', action='store_true')
  57. add_builtin_argument(p, 'layout')
  58. add_builtin_argument(p, 'default-library')
  59. add_builtin_argument(p, 'warnlevel', dest='warning_level')
  60. add_builtin_argument(p, 'stdsplit', action='store_false')
  61. add_builtin_argument(p, 'errorlogs', action='store_false')
  62. p.add_argument('--cross-file', default=None,
  63. help='File describing cross compilation environment.')
  64. p.add_argument('-D', action='append', dest='projectoptions', default=[], metavar="option",
  65. help='Set the value of an option, can be used several times to set multiple options.')
  66. p.add_argument('-v', '--version', action='version',
  67. version=coredata.version)
  68. # See the mesonlib.WrapMode enum for documentation
  69. p.add_argument('--wrap-mode', default=WrapMode.default,
  70. type=wrapmodetype, choices=WrapMode,
  71. help='Special wrap mode to use')
  72. p.add_argument('directories', nargs='*')
  73. return p
  74. def wrapmodetype(string):
  75. try:
  76. return getattr(WrapMode, string)
  77. except AttributeError:
  78. msg = ', '.join([t.name.lower() for t in WrapMode])
  79. msg = 'invalid argument {!r}, use one of {}'.format(string, msg)
  80. raise argparse.ArgumentTypeError(msg)
  81. class MesonApp:
  82. def __init__(self, dir1, dir2, script_launcher, handshake, options, original_cmd_line_args):
  83. (self.source_dir, self.build_dir) = self.validate_dirs(dir1, dir2, handshake)
  84. self.meson_script_launcher = script_launcher
  85. self.options = options
  86. self.original_cmd_line_args = original_cmd_line_args
  87. def has_build_file(self, dirname):
  88. fname = os.path.join(dirname, environment.build_filename)
  89. return os.path.exists(fname)
  90. def validate_core_dirs(self, dir1, dir2):
  91. ndir1 = os.path.abspath(os.path.realpath(dir1))
  92. ndir2 = os.path.abspath(os.path.realpath(dir2))
  93. if not os.path.exists(ndir1):
  94. os.makedirs(ndir1)
  95. if not os.path.exists(ndir2):
  96. os.makedirs(ndir2)
  97. if not stat.S_ISDIR(os.stat(ndir1).st_mode):
  98. raise RuntimeError('%s is not a directory' % dir1)
  99. if not stat.S_ISDIR(os.stat(ndir2).st_mode):
  100. raise RuntimeError('%s is not a directory' % dir2)
  101. if os.path.samefile(dir1, dir2):
  102. raise RuntimeError('Source and build directories must not be the same. Create a pristine build directory.')
  103. if self.has_build_file(ndir1):
  104. if self.has_build_file(ndir2):
  105. raise RuntimeError('Both directories contain a build file %s.' % environment.build_filename)
  106. return ndir1, ndir2
  107. if self.has_build_file(ndir2):
  108. return ndir2, ndir1
  109. raise RuntimeError('Neither directory contains a build file %s.' % environment.build_filename)
  110. def validate_dirs(self, dir1, dir2, handshake):
  111. (src_dir, build_dir) = self.validate_core_dirs(dir1, dir2)
  112. priv_dir = os.path.join(build_dir, 'meson-private/coredata.dat')
  113. if os.path.exists(priv_dir):
  114. if not handshake:
  115. print('Directory already configured, exiting Meson. Just run your build command\n'
  116. '(e.g. ninja) and Meson will regenerate as necessary. If ninja fails, run ninja\n'
  117. 'reconfigure to force Meson to regenerate.\n'
  118. '\nIf build failures persist, manually wipe your build directory to clear any\n'
  119. 'stored system data.\n'
  120. '\nTo change option values, run meson configure instead.')
  121. sys.exit(0)
  122. else:
  123. if handshake:
  124. raise RuntimeError('Something went terribly wrong. Please file a bug.')
  125. return src_dir, build_dir
  126. def check_pkgconfig_envvar(self, env):
  127. curvar = os.environ.get('PKG_CONFIG_PATH', '')
  128. if curvar != env.coredata.pkgconf_envvar:
  129. mlog.warning('PKG_CONFIG_PATH has changed between invocations from "%s" to "%s".' %
  130. (env.coredata.pkgconf_envvar, curvar))
  131. env.coredata.pkgconf_envvar = curvar
  132. def generate(self):
  133. env = environment.Environment(self.source_dir, self.build_dir, self.meson_script_launcher, self.options, self.original_cmd_line_args)
  134. mlog.initialize(env.get_log_dir())
  135. try:
  136. self._generate(env)
  137. finally:
  138. mlog.shutdown()
  139. def _generate(self, env):
  140. mlog.debug('Build started at', datetime.datetime.now().isoformat())
  141. mlog.debug('Main binary:', sys.executable)
  142. mlog.debug('Python system:', platform.system())
  143. mlog.log(mlog.bold('The Meson build system'))
  144. self.check_pkgconfig_envvar(env)
  145. mlog.log('Version:', coredata.version)
  146. mlog.log('Source dir:', mlog.bold(self.source_dir))
  147. mlog.log('Build dir:', mlog.bold(self.build_dir))
  148. if env.is_cross_build():
  149. mlog.log('Build type:', mlog.bold('cross build'))
  150. else:
  151. mlog.log('Build type:', mlog.bold('native build'))
  152. b = build.Build(env)
  153. if self.options.backend == 'ninja':
  154. from .backend import ninjabackend
  155. g = ninjabackend.NinjaBackend(b)
  156. elif self.options.backend == 'vs':
  157. from .backend import vs2010backend
  158. g = vs2010backend.autodetect_vs_version(b)
  159. mlog.log('Auto detected Visual Studio backend:', mlog.bold(g.name))
  160. elif self.options.backend == 'vs2010':
  161. from .backend import vs2010backend
  162. g = vs2010backend.Vs2010Backend(b)
  163. elif self.options.backend == 'vs2015':
  164. from .backend import vs2015backend
  165. g = vs2015backend.Vs2015Backend(b)
  166. elif self.options.backend == 'vs2017':
  167. from .backend import vs2017backend
  168. g = vs2017backend.Vs2017Backend(b)
  169. elif self.options.backend == 'xcode':
  170. from .backend import xcodebackend
  171. g = xcodebackend.XCodeBackend(b)
  172. else:
  173. raise RuntimeError('Unknown backend "%s".' % self.options.backend)
  174. intr = interpreter.Interpreter(b, g)
  175. if env.is_cross_build():
  176. mlog.log('Host machine cpu family:', mlog.bold(intr.builtin['host_machine'].cpu_family_method([], {})))
  177. mlog.log('Host machine cpu:', mlog.bold(intr.builtin['host_machine'].cpu_method([], {})))
  178. mlog.log('Target machine cpu family:', mlog.bold(intr.builtin['target_machine'].cpu_family_method([], {})))
  179. mlog.log('Target machine cpu:', mlog.bold(intr.builtin['target_machine'].cpu_method([], {})))
  180. mlog.log('Build machine cpu family:', mlog.bold(intr.builtin['build_machine'].cpu_family_method([], {})))
  181. mlog.log('Build machine cpu:', mlog.bold(intr.builtin['build_machine'].cpu_method([], {})))
  182. intr.run()
  183. try:
  184. # We would like to write coredata as late as possible since we use the existence of
  185. # this file to check if we generated the build file successfully. Since coredata
  186. # includes settings, the build files must depend on it and appear newer. However, due
  187. # to various kernel caches, we cannot guarantee that any time in Python is exactly in
  188. # sync with the time that gets applied to any files. Thus, we dump this file as late as
  189. # possible, but before build files, and if any error occurs, delete it.
  190. cdf = env.dump_coredata()
  191. g.generate(intr)
  192. dumpfile = os.path.join(env.get_scratch_dir(), 'build.dat')
  193. with open(dumpfile, 'wb') as f:
  194. pickle.dump(b, f)
  195. # Post-conf scripts must be run after writing coredata or else introspection fails.
  196. g.run_postconf_scripts()
  197. except:
  198. os.unlink(cdf)
  199. raise
  200. def run_script_command(args):
  201. cmdname = args[0]
  202. cmdargs = args[1:]
  203. if cmdname == 'exe':
  204. import mesonbuild.scripts.meson_exe as abc
  205. cmdfunc = abc.run
  206. elif cmdname == 'cleantrees':
  207. import mesonbuild.scripts.cleantrees as abc
  208. cmdfunc = abc.run
  209. elif cmdname == 'install':
  210. import mesonbuild.scripts.meson_install as abc
  211. cmdfunc = abc.run
  212. elif cmdname == 'commandrunner':
  213. import mesonbuild.scripts.commandrunner as abc
  214. cmdfunc = abc.run
  215. elif cmdname == 'delsuffix':
  216. import mesonbuild.scripts.delwithsuffix as abc
  217. cmdfunc = abc.run
  218. elif cmdname == 'depfixer':
  219. import mesonbuild.scripts.depfixer as abc
  220. cmdfunc = abc.run
  221. elif cmdname == 'dirchanger':
  222. import mesonbuild.scripts.dirchanger as abc
  223. cmdfunc = abc.run
  224. elif cmdname == 'gtkdoc':
  225. import mesonbuild.scripts.gtkdochelper as abc
  226. cmdfunc = abc.run
  227. elif cmdname == 'msgfmthelper':
  228. import mesonbuild.scripts.msgfmthelper as abc
  229. cmdfunc = abc.run
  230. elif cmdname == 'regencheck':
  231. import mesonbuild.scripts.regen_checker as abc
  232. cmdfunc = abc.run
  233. elif cmdname == 'symbolextractor':
  234. import mesonbuild.scripts.symbolextractor as abc
  235. cmdfunc = abc.run
  236. elif cmdname == 'scanbuild':
  237. import mesonbuild.scripts.scanbuild as abc
  238. cmdfunc = abc.run
  239. elif cmdname == 'vcstagger':
  240. import mesonbuild.scripts.vcstagger as abc
  241. cmdfunc = abc.run
  242. elif cmdname == 'gettext':
  243. import mesonbuild.scripts.gettext as abc
  244. cmdfunc = abc.run
  245. elif cmdname == 'yelphelper':
  246. import mesonbuild.scripts.yelphelper as abc
  247. cmdfunc = abc.run
  248. elif cmdname == 'uninstall':
  249. import mesonbuild.scripts.uninstall as abc
  250. cmdfunc = abc.run
  251. elif cmdname == 'dist':
  252. import mesonbuild.scripts.dist as abc
  253. cmdfunc = abc.run
  254. elif cmdname == 'coverage':
  255. import mesonbuild.scripts.coverage as abc
  256. cmdfunc = abc.run
  257. else:
  258. raise MesonException('Unknown internal command {}.'.format(cmdname))
  259. return cmdfunc(cmdargs)
  260. def run(original_args, mainfile=None):
  261. if sys.version_info < (3, 4):
  262. print('Meson works correctly only with python 3.4+.')
  263. print('You have python %s.' % sys.version)
  264. print('Please update your environment')
  265. return 1
  266. args = original_args[:]
  267. if len(args) > 0:
  268. # First check if we want to run a subcommand.
  269. cmd_name = args[0]
  270. remaining_args = args[1:]
  271. if cmd_name == 'test':
  272. return mtest.run(remaining_args)
  273. elif cmd_name == 'setup':
  274. args = remaining_args
  275. # FALLTHROUGH like it's 1972.
  276. elif cmd_name == 'introspect':
  277. return mintro.run(remaining_args)
  278. elif cmd_name == 'test':
  279. return mtest.run(remaining_args)
  280. elif cmd_name == 'rewrite':
  281. return rewriter.run(remaining_args)
  282. elif cmd_name == 'configure':
  283. try:
  284. return mconf.run(remaining_args)
  285. except MesonException as e:
  286. mlog.log(mlog.red('\nError configuring project:'), e)
  287. sys.exit(1)
  288. elif cmd_name == 'wrap':
  289. return wraptool.run(remaining_args)
  290. elif cmd_name == 'runpython':
  291. import runpy
  292. script_file = remaining_args[0]
  293. sys.argv[1:] = remaining_args[1:]
  294. runpy.run_path(script_file, run_name='__main__')
  295. sys.exit(0)
  296. # No special command? Do the basic setup/reconf.
  297. if len(args) >= 2 and args[0] == '--internal':
  298. if args[1] != 'regenerate':
  299. script = args[1]
  300. try:
  301. sys.exit(run_script_command(args[1:]))
  302. except MesonException as e:
  303. mlog.log(mlog.red('\nError in {} helper script:'.format(script)))
  304. mlog.log(e)
  305. sys.exit(1)
  306. args = args[2:]
  307. handshake = True
  308. else:
  309. handshake = False
  310. parser = create_parser()
  311. args = mesonlib.expand_arguments(args)
  312. options = parser.parse_args(args)
  313. args = options.directories
  314. if not args or len(args) > 2:
  315. # if there's a meson.build in the dir above, and not in the current
  316. # directory, assume we're in the build directory
  317. if not args and not os.path.exists('meson.build') and os.path.exists('../meson.build'):
  318. dir1 = '..'
  319. dir2 = '.'
  320. else:
  321. print('{} <source directory> <build directory>'.format(sys.argv[0]))
  322. print('If you omit either directory, the current directory is substituted.')
  323. print('Run {} --help for more information.'.format(sys.argv[0]))
  324. return 1
  325. else:
  326. dir1 = args[0]
  327. if len(args) > 1:
  328. dir2 = args[1]
  329. else:
  330. dir2 = '.'
  331. try:
  332. if mainfile is None:
  333. raise AssertionError('I iz broken. Sorry.')
  334. app = MesonApp(dir1, dir2, mainfile, handshake, options, original_args)
  335. except Exception as e:
  336. # Log directory does not exist, so just print
  337. # to stdout.
  338. print('Error during basic setup:\n')
  339. print(e)
  340. return 1
  341. try:
  342. app.generate()
  343. except Exception as e:
  344. if isinstance(e, MesonException):
  345. if hasattr(e, 'file') and hasattr(e, 'lineno') and hasattr(e, 'colno'):
  346. mlog.log(mlog.red('\nMeson encountered an error in file %s, line %d, column %d:' % (e.file, e.lineno, e.colno)))
  347. else:
  348. mlog.log(mlog.red('\nMeson encountered an error:'))
  349. # Error message
  350. mlog.log(e)
  351. # Path to log file
  352. logfile = os.path.join(app.build_dir, environment.Environment.log_dir, mlog.log_fname)
  353. mlog.log("\nA full log can be found at", mlog.bold(logfile))
  354. if os.environ.get('MESON_FORCE_BACKTRACE'):
  355. raise
  356. else:
  357. if os.environ.get('MESON_FORCE_BACKTRACE'):
  358. raise
  359. traceback.print_exc()
  360. return 1
  361. return 0