aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.travis.yml5
-rw-r--r--ciimage/Dockerfile3
-rw-r--r--docs/markdown/D.md10
-rw-r--r--docs/markdown/Dependencies.md11
-rw-r--r--docs/markdown/Reference-manual.md14
-rw-r--r--docs/markdown/Reference-tables.md5
-rw-r--r--docs/markdown/Release-notes-for-0.49.0.md5
-rw-r--r--mesonbuild/backend/xcodebackend.py30
-rw-r--r--mesonbuild/build.py6
-rw-r--r--mesonbuild/compilers/c.py51
-rw-r--r--mesonbuild/compilers/d.py50
-rw-r--r--mesonbuild/dependencies/__init__.py3
-rw-r--r--mesonbuild/dependencies/dev.py81
-rw-r--r--mesonbuild/dependencies/misc.py31
-rw-r--r--mesonbuild/interpreter.py9
-rw-r--r--mesonbuild/mconf.py10
-rw-r--r--mesonbuild/mesonlib.py17
-rw-r--r--mesonbuild/mesonmain.py464
-rw-r--r--mesonbuild/minit.py8
-rw-r--r--mesonbuild/minstall.py12
-rw-r--r--mesonbuild/mintro.py8
-rw-r--r--mesonbuild/modules/windows.py64
-rw-r--r--mesonbuild/msetup.py197
-rw-r--r--mesonbuild/mtest.py14
-rw-r--r--mesonbuild/rewriter.py9
-rw-r--r--mesonbuild/scripts/dist.py21
-rw-r--r--mesonbuild/scripts/meson_exe.py2
-rw-r--r--mesonbuild/wrap/wraptool.py6
-rwxr-xr-xrun_project_tests.py4
-rwxr-xr-xrun_tests.py2
-rw-r--r--test cases/common/14 configure file/meson.build43
-rw-r--r--test cases/d/9 features/app.d24
-rw-r--r--test cases/d/9 features/meson.build62
-rw-r--r--test cases/frameworks/24 libgcrypt/libgcrypt_prog.c8
-rw-r--r--test cases/frameworks/24 libgcrypt/meson.build23
-rw-r--r--test cases/unit/35 dist script/meson.build2
-rwxr-xr-xtest cases/unit/35 dist script/replacer.py6
37 files changed, 835 insertions, 485 deletions
diff --git a/.travis.yml b/.travis.yml
index dd5cebb..bd8d48c 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -41,7 +41,7 @@ matrix:
before_install:
- python ./skip_ci.py --base-branch-env=TRAVIS_BRANCH --is-pull-env=TRAVIS_PULL_REQUEST
- if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then brew update; fi
- - if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then brew install qt; fi
+ - if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then brew install qt llvm; fi
# # Run one macOS build without pkg-config available, and the other (unity=on) with pkg-config
- if [[ "$TRAVIS_OS_NAME" == "osx" && "$MESON_ARGS" =~ .*unity=on.* ]]; then brew install pkg-config; fi
# Use a Ninja with QuLogic's patch: https://github.com/ninja-build/ninja/issues/1219
@@ -62,4 +62,5 @@ script:
withgit \
/bin/sh -c "cd /root && mkdir -p tools; wget -c http://nirbheek.in/files/binaries/ninja/linux-amd64/ninja -O /root/tools/ninja; chmod +x /root/tools/ninja; CC=$CC CXX=$CXX OBJC=$CC OBJCXX=$CXX PATH=/root/tools:$PATH MESON_FIXED_NINJA=1 ./run_tests.py $RUN_TESTS_ARGS -- $MESON_ARGS && chmod -R a+rwX .coverage"
fi
- - if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then SDKROOT=$(xcodebuild -version -sdk macosx Path) CPPFLAGS=-I/usr/local/include LDFLAGS=-L/usr/local/lib OBJC=$CC OBJCXX=$CXX PATH=$HOME/tools:/usr/local/opt/qt/bin:$PATH MESON_FIXED_NINJA=1 ./run_tests.py --backend=ninja -- $MESON_ARGS ; fi
+ # Ensure that llvm is added after $PATH, otherwise the clang from that llvm install will be used instead of the native apple clang.
+ - if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then SDKROOT=$(xcodebuild -version -sdk macosx Path) CPPFLAGS=-I/usr/local/include LDFLAGS=-L/usr/local/lib OBJC=$CC OBJCXX=$CXX PATH=$HOME/tools:/usr/local/opt/qt/bin:$PATH:$(brew --prefix llvm)/bin MESON_FIXED_NINJA=1 ./run_tests.py --backend=ninja -- $MESON_ARGS ; fi
diff --git a/ciimage/Dockerfile b/ciimage/Dockerfile
index 326013b..ac59ca9 100644
--- a/ciimage/Dockerfile
+++ b/ciimage/Dockerfile
@@ -12,7 +12,8 @@ RUN apt-get -y update && apt-get -y upgrade \
&& apt-get -y install qt4-linguist-tools \
&& apt-get -y install python-dev \
&& apt-get -y install libomp-dev openssh-client \
-&& apt-get -y install -y clang libclang-dev llvm-dev flex \
+&& apt-get -y install clang libclang-dev llvm-dev flex \
+&& apt-get -y install libgcrypt11-dev \
&& apt-get -y install gdc ldc \
&& python3 -m pip install hotdoc codecov \
&& dub fetch urld \
diff --git a/docs/markdown/D.md b/docs/markdown/D.md
index 15de2f7..2b0eaac 100644
--- a/docs/markdown/D.md
+++ b/docs/markdown/D.md
@@ -14,15 +14,21 @@ project('myapp', 'd')
executable('myapp', 'app.d')
```
-## Compiling different versions
+## [Conditional compilation](https://dlang.org/spec/version.html)
-If you are using the [version()](https://dlang.org/spec/version.html) feature for conditional compilation,
+If you are using the [version()](https://dlang.org/spec/version.html#version-specification) feature for conditional compilation,
you can use it using the `d_module_versions` target property:
```meson
project('myapp', 'd')
executable('myapp', 'app.d', d_module_versions: ['Demo', 'FeatureA'])
```
+For debugging, [debug()](https://dlang.org/spec/version.html#debug) conditions are compiled automatically in debug builds, and extra identifiers can be added with the `d_debug` argument:
+```meson
+project('myapp', 'd')
+executable('myapp', 'app.d', d_debug: [3, 'DebugFeatureA'])
+```
+
## Using embedded unittests
If you are using embedded [unittest functions](https://dlang.org/spec/unittest.html), your source code needs
diff --git a/docs/markdown/Dependencies.md b/docs/markdown/Dependencies.md
index 08ff1e2..c853677 100644
--- a/docs/markdown/Dependencies.md
+++ b/docs/markdown/Dependencies.md
@@ -165,15 +165,16 @@ wmf_dep = dependency('libwmf', method : 'config-tool')
## Dependencies using config tools
[CUPS](#cups), [LLVM](#llvm), [pcap](#pcap), [WxWidgets](#wxwidgets),
-[libwmf](#libwmf), and GnuStep either do not provide pkg-config
+[libwmf](#libwmf), [GCrypt](#libgcrypt), and GnuStep either do not provide pkg-config
modules or additionally can be detected via a config tool
-(cups-config, llvm-config, etc). Meson has native support for these
+(cups-config, llvm-config, libgcrypt-config, etc). Meson has native support for these
tools, and they can be found like other dependencies:
```meson
pcap_dep = dependency('pcap', version : '>=1.0')
cups_dep = dependency('cups', version : '>=1.4')
llvm_dep = dependency('llvm', version : '>=4.0')
+libgcrypt_dep = dependency('libgcrypt', version: '>= 1.8')
```
## AppleFrameworks
@@ -309,6 +310,12 @@ The `language` keyword may used.
`method` may be `auto`, `config-tool` or `pkg-config`.
+## libgcrypt
+
+*(added 0.49.0)*
+
+`method` may be `auto`, `config-tool` or `pkg-config`.
+
## Python3
Python3 is handled specially by meson:
diff --git a/docs/markdown/Reference-manual.md b/docs/markdown/Reference-manual.md
index 7902f19..0fb9f17 100644
--- a/docs/markdown/Reference-manual.md
+++ b/docs/markdown/Reference-manual.md
@@ -242,7 +242,7 @@ Create a custom top level build target. The only positional argument
is the name of this target and the keyword arguments are the
following.
-- `build_by_default` *(added 0.38.0)* causes, when set to true, to
+- `build_by_default` *(added 0.38)* causes, when set to true, to
have this target be built by default, that is, when invoking plain
`ninja`; the default value is false
- `build_always` (deprecated) if `true` this target is always considered out of
@@ -256,7 +256,7 @@ following.
this argument is set to true, Meson captures `stdout` and writes it
to the target file. Note that your command argument list may not
contain `@OUTPUT@` when capture mode is active.
-- `console` keyword argument conflicts with `capture`, and is meant
+- `console` *(added 0.48)* keyword argument conflicts with `capture`, and is meant
for commands that are resource-intensive and take a long time to
finish. With the Ninja backend, setting this will add this target
to [Ninja's `console` pool](https://ninja-build.org/manual.html#_the_literal_console_literal_pool),
@@ -537,7 +537,8 @@ be passed to [shared and static libraries](#library).
- `d_import_dirs` list of directories to look in for string imports used
in the D programming language
- `d_unittest`, when set to true, the D modules are compiled in debug mode
-- `d_module_versions` list of module versions set when compiling D sources
+- `d_module_versions` list of module version identifiers set when compiling D sources
+- `d_debug` list of module debug identifiers set when compiling D sources
The list of `sources`, `objects`, and `dependencies` is always
flattened, which means you can freely nest and add lists while
@@ -1432,14 +1433,14 @@ The `meson` object allows you to introspect various properties of the
system. This object is always mapped in the `meson` variable. It has
the following methods.
-- `add_dist_script` causes the script given as argument to run during
+- `add_dist_script(script_name, arg1, arg, ...)` causes the script given as argument to run during
`dist` operation after the distribution source has been generated
but before it is archived. Note that this runs the script file that
is in the _staging_ directory, not the one in the source
directory. If the script file can not be found in the staging
directory, it is a hard error. This command can only invoked from
the main project, calling it from a subproject is a hard
- error. Available since 0.48.0.
+ error. Available since 0.48.0. Before 0.49.0, the function only accepted a single argument.
- `add_install_script(script_name, arg1, arg2, ...)` causes the script
given as an argument to be run during the install step, this script
@@ -1626,6 +1627,9 @@ the following methods:
the positional argument, you can specify external dependencies to
use with `dependencies` keyword argument.
+- `cmd_array()` returns an array containing the command arguments for
+ the current compiler.
+
- `compiles(code)` returns true if the code fragment given in the
positional argument compiles, you can specify external dependencies
to use with `dependencies` keyword argument, `code` can be either a
diff --git a/docs/markdown/Reference-tables.md b/docs/markdown/Reference-tables.md
index ccdcb34..39ec1cd 100644
--- a/docs/markdown/Reference-tables.md
+++ b/docs/markdown/Reference-tables.md
@@ -65,6 +65,11 @@ set in the cross file.
Any cpu family not listed in the above list is not guaranteed to
remain stable in future releases.
+Those porting from autotools should note that meson does not add
+endianness to the name of the cpu_family. For example, autotools
+will call little endian PPC64 "ppc64le", meson will not, you must
+also check the `.endian()` value of the machine for this information.
+
## Operating system names
These are provided by the `.system()` method call.
diff --git a/docs/markdown/Release-notes-for-0.49.0.md b/docs/markdown/Release-notes-for-0.49.0.md
index b294ad5..bdf5769 100644
--- a/docs/markdown/Release-notes-for-0.49.0.md
+++ b/docs/markdown/Release-notes-for-0.49.0.md
@@ -15,3 +15,8 @@ whose contents should look like this:
A short description explaining the new feature and how it should be used.
+## Libgcrypt dependency now supports libgcrypt-config
+
+Earlier, `dependency('libgcrypt')` could only detect the library with pkg-config
+files. Now, if pkg-config files are not found, Meson will look for
+`libgcrypt-config` and if it's found, will use that to find the library.
diff --git a/mesonbuild/backend/xcodebackend.py b/mesonbuild/backend/xcodebackend.py
index b0fcfa4..11f8bb8 100644
--- a/mesonbuild/backend/xcodebackend.py
+++ b/mesonbuild/backend/xcodebackend.py
@@ -786,6 +786,7 @@ class XCodeBackend(backends.Backend):
self.write_line('PRODUCT_NAME = %s;' % product_name)
self.write_line('SECTORDER_FLAGS = "";')
self.write_line('SYMROOT = "%s";' % symroot)
+ self.write_build_setting_line('SYSTEM_HEADER_SEARCH_PATHS', [self.environment.get_build_dir()])
self.write_line('USE_HEADERMAP = NO;')
self.write_build_setting_line('WARNING_CFLAGS', ['-Wmost', '-Wno-four-char-constants', '-Wno-unknown-pragmas'])
self.indent_level -= 1
@@ -860,16 +861,29 @@ class XCodeBackend(backends.Backend):
self.write_line('};')
self.ofile.write('/* End XCConfigurationList section */\n')
- def write_build_setting_line(self, flag_name, flag_values):
+ def write_build_setting_line(self, flag_name, flag_values, explicit=False):
if flag_values:
- self.write_line('%s = (' % flag_name)
- self.indent_level += 1
- for value in flag_values:
- self.write_line('"%s",' % value)
- self.indent_level -= 1
- self.write_line(');')
+ if len(flag_values) == 1:
+ value = flag_values[0]
+ if (' ' in value):
+ # If path contains spaces surround it with double colon
+ self.write_line('%s = "\\"%s\\"";' % (flag_name, value))
+ else:
+ self.write_line('"%s",' % value)
+ else:
+ self.write_line('%s = (' % flag_name)
+ self.indent_level += 1
+ for value in flag_values:
+ if (' ' in value):
+ # If path contains spaces surround it with double colon
+ self.write_line('"\\"%s\\"",' % value)
+ else:
+ self.write_line('"%s",' % value)
+ self.indent_level -= 1
+ self.write_line(');')
else:
- self.write_line('%s = "";' % flag_name)
+ if explicit:
+ self.write_line('%s = "";' % flag_name)
def generate_prefix(self):
self.ofile.write('// !$*UTF8*$!\n{\n')
diff --git a/mesonbuild/build.py b/mesonbuild/build.py
index 9c7b6a4..8ba5465 100644
--- a/mesonbuild/build.py
+++ b/mesonbuild/build.py
@@ -37,6 +37,7 @@ lang_arg_kwargs = set([
'd_import_dirs',
'd_unittest',
'd_module_versions',
+ 'd_debug',
'fortran_args',
'java_args',
'objc_args',
@@ -772,9 +773,12 @@ just like those detected with the dependency() function.''')
dfeature_unittest = kwargs.get('d_unittest', False)
if dfeature_unittest:
dfeatures['unittest'] = dfeature_unittest
- dfeature_versions = kwargs.get('d_module_versions', None)
+ dfeature_versions = kwargs.get('d_module_versions', [])
if dfeature_versions:
dfeatures['versions'] = dfeature_versions
+ dfeature_debug = kwargs.get('d_debug', [])
+ if dfeature_debug:
+ dfeatures['debug'] = dfeature_debug
if 'd_import_dirs' in kwargs:
dfeature_import_dirs = extract_as_list(kwargs, 'd_import_dirs', unholder=True)
for d in dfeature_import_dirs:
diff --git a/mesonbuild/compilers/c.py b/mesonbuild/compilers/c.py
index 72b9f24..73721e4 100644
--- a/mesonbuild/compilers/c.py
+++ b/mesonbuild/compilers/c.py
@@ -217,7 +217,7 @@ class CCompiler(Compiler):
paths = []
for p in pathstr.split(sep):
p = Path(p)
- if p.exists():
+ if p.exists() and p.resolve().as_posix() not in paths:
paths.append(p.resolve().as_posix())
return tuple(paths)
@@ -232,8 +232,34 @@ class CCompiler(Compiler):
return ()
@functools.lru_cache()
- def get_library_dirs(self, env):
- return self.get_compiler_dirs(env, 'libraries')
+ def get_library_dirs(self, env, elf_class = None):
+ dirs = self.get_compiler_dirs(env, 'libraries')
+ if elf_class is None or elf_class == 0:
+ return dirs
+
+ # if we do have an elf class for 32-bit or 64-bit, we want to check that
+ # the directory in question contains libraries of the appropriate class. Since
+ # system directories aren't mixed, we only need to check one file for each
+ # directory and go by that. If we can't check the file for some reason, assume
+ # the compiler knows what it's doing, and accept the directory anyway.
+ retval = []
+ for d in dirs:
+ files = [f for f in os.listdir(d) if f.endswith('.so') and os.path.isfile(os.path.join(d, f))]
+ # if no files, accept directory and move on
+ if len(files) == 0:
+ retval.append(d)
+ continue
+ file_to_check = os.path.join(d, files[0])
+ with open(file_to_check, 'rb') as fd:
+ header = fd.read(5)
+ # if file is not an ELF file, it's weird, but accept dir
+ # if it is elf, and the class matches, accept dir
+ if header[1:4] != b'ELF' or int(header[4]) == elf_class:
+ retval.append(d)
+ # at this point, it's an ELF file which doesn't match the
+ # appropriate elf_class, so skip this one
+ pass
+ return tuple(retval)
@functools.lru_cache()
def get_program_dirs(self, env):
@@ -935,6 +961,13 @@ class CCompiler(Compiler):
return f
return None
+ @functools.lru_cache()
+ def output_is_64bit(self, env):
+ '''
+ returns true if the output produced is 64-bit, false if 32-bit
+ '''
+ return self.sizeof('void *', '', env) == 8
+
def find_library_real(self, libname, env, extra_dirs, code, libtype):
# First try if we can just add the library as -l.
# Gcc + co seem to prefer builtin lib dirs to -L dirs.
@@ -950,8 +983,18 @@ class CCompiler(Compiler):
# Not found or we want to use a specific libtype? Try to find the
# library file itself.
patterns = self.get_library_naming(env, libtype)
+ # try to detect if we are 64-bit or 32-bit. If we can't
+ # detect, we will just skip path validity checks done in
+ # get_library_dirs() call
+ try:
+ if self.output_is_64bit(env):
+ elf_class = 2
+ else:
+ elf_class = 1
+ except:
+ elf_class = 0
# Search in the specified dirs, and then in the system libraries
- for d in itertools.chain(extra_dirs, self.get_library_dirs(env)):
+ for d in itertools.chain(extra_dirs, self.get_library_dirs(env, elf_class)):
for p in patterns:
trial = self._get_trials_from_pattern(p, d, libname)
if not trial:
diff --git a/mesonbuild/compilers/d.py b/mesonbuild/compilers/d.py
index e9ceafb..2865b1f 100644
--- a/mesonbuild/compilers/d.py
+++ b/mesonbuild/compilers/d.py
@@ -30,14 +30,17 @@ from .compilers import (
)
d_feature_args = {'gcc': {'unittest': '-funittest',
+ 'debug': '-fdebug',
'version': '-fversion',
'import_dir': '-J'
},
'llvm': {'unittest': '-unittest',
+ 'debug': '-d-debug',
'version': '-d-version',
'import_dir': '-J'
},
'dmd': {'unittest': '-unittest',
+ 'debug': '-debug',
'version': '-version',
'import_dir': '-J'
}
@@ -168,16 +171,53 @@ class DCompiler(Compiler):
if unittest:
res.append(unittest_arg)
+ if 'debug' in kwargs:
+ debug_level = -1
+ debugs = kwargs.pop('debug')
+ if not isinstance(debugs, list):
+ debugs = [debugs]
+
+ debug_arg = d_feature_args[self.id]['debug']
+ if not debug_arg:
+ raise EnvironmentException('D compiler %s does not support conditional debug identifiers.' % self.name_string())
+
+ # Parse all debug identifiers and the largest debug level identifier
+ for d in debugs:
+ if isinstance(d, int):
+ if d > debug_level:
+ debug_level = d
+ elif isinstance(d, str) and d.isdigit():
+ if int(d) > debug_level:
+ debug_level = int(d)
+ else:
+ res.append('{0}={1}'.format(debug_arg, d))
+
+ if debug_level >= 0:
+ res.append('{0}={1}'.format(debug_arg, debug_level))
+
if 'versions' in kwargs:
+ version_level = -1
versions = kwargs.pop('versions')
if not isinstance(versions, list):
versions = [versions]
version_arg = d_feature_args[self.id]['version']
if not version_arg:
- raise EnvironmentException('D compiler %s does not support the "feature versions" feature.' % self.name_string())
+ raise EnvironmentException('D compiler %s does not support conditional version identifiers.' % self.name_string())
+
+ # Parse all version identifiers and the largest version level identifier
for v in versions:
- res.append('{0}={1}'.format(version_arg, v))
+ if isinstance(v, int):
+ if v > version_level:
+ version_level = v
+ elif isinstance(v, str) and v.isdigit():
+ if int(v) > version_level:
+ version_level = int(v)
+ else:
+ res.append('{0}={1}'.format(version_arg, v))
+
+ if version_level >= 0:
+ res.append('{0}={1}'.format(version_arg, version_level))
if 'import_dirs' in kwargs:
import_dirs = kwargs.pop('import_dirs')
@@ -378,7 +418,11 @@ class DCompiler(Compiler):
return args
def get_debug_args(self, is_debug):
- return clike_debug_args[is_debug]
+ ddebug_args = []
+ if is_debug:
+ ddebug_args = [d_feature_args[self.id]['debug']]
+
+ return clike_debug_args[is_debug] + ddebug_args
def get_crt_args(self, crt_val, buildtype):
if not is_windows():
diff --git a/mesonbuild/dependencies/__init__.py b/mesonbuild/dependencies/__init__.py
index 00b6fa2..0375537 100644
--- a/mesonbuild/dependencies/__init__.py
+++ b/mesonbuild/dependencies/__init__.py
@@ -18,7 +18,7 @@ from .base import ( # noqa: F401
ExternalDependency, NotFoundDependency, ExternalLibrary, ExtraFrameworkDependency, InternalDependency,
PkgConfigDependency, find_external_dependency, get_dep_identifier, packages, _packages_accept_language)
from .dev import GMockDependency, GTestDependency, LLVMDependency, ValgrindDependency
-from .misc import (MPIDependency, OpenMPDependency, Python3Dependency, ThreadDependency, PcapDependency, CupsDependency, LibWmfDependency)
+from .misc import (MPIDependency, OpenMPDependency, Python3Dependency, ThreadDependency, PcapDependency, CupsDependency, LibWmfDependency, LibGCryptDependency)
from .platform import AppleFrameworks
from .ui import GLDependency, GnuStepDependency, Qt4Dependency, Qt5Dependency, SDL2Dependency, WxDependency, VulkanDependency
@@ -39,6 +39,7 @@ packages.update({
'pcap': PcapDependency,
'cups': CupsDependency,
'libwmf': LibWmfDependency,
+ 'libgcrypt': LibGCryptDependency,
# From platform:
'appleframeworks': AppleFrameworks,
diff --git a/mesonbuild/dependencies/dev.py b/mesonbuild/dependencies/dev.py
index d8289c5..1e7c3e8 100644
--- a/mesonbuild/dependencies/dev.py
+++ b/mesonbuild/dependencies/dev.py
@@ -16,6 +16,7 @@
# development purposes, such as testing, debugging, etc..
import functools
+import glob
import os
import re
@@ -27,6 +28,17 @@ from .base import (
)
+def get_shared_library_suffix(environment, native):
+ """This is only gauranteed to work for languages that compile to machine
+ code, not for languages like C# that use a bytecode and always end in .dll
+ """
+ if mesonlib.for_windows(native, environment):
+ return '.dll'
+ elif mesonlib.for_darwin(native, environment):
+ return '.dylib'
+ return '.so'
+
+
class GTestDependency(ExternalDependency):
def __init__(self, environment, kwargs):
super().__init__('gtest', environment, 'cpp', kwargs)
@@ -235,7 +247,7 @@ class LLVMDependency(ConfigToolDependency):
self.compile_args = list(cargs.difference(self.__cpp_blacklist))
if version_compare(self.version, '>= 3.9'):
- self._set_new_link_args()
+ self._set_new_link_args(environment)
else:
self._set_old_link_args()
self.link_args = strip_system_libdirs(environment, self.link_args)
@@ -258,18 +270,63 @@ class LLVMDependency(ConfigToolDependency):
new_args.append(arg)
return new_args
- def _set_new_link_args(self):
+ def __check_libfiles(self, shared):
+ """Use llvm-config's --libfiles to check if libraries exist."""
+ mode = '--link-shared' if shared else '--link-static'
+
+ # Set self.required to true to force an exception in get_config_value
+ # if the returncode != 0
+ restore = self.required
+ self.required = True
+
+ try:
+ # It doesn't matter what the stage is, the caller needs to catch
+ # the exception anyway.
+ self.link_args = self.get_config_value(['--libfiles', mode], '')
+ finally:
+ self.required = restore
+
+ def _set_new_link_args(self, environment):
"""How to set linker args for LLVM versions >= 3.9"""
- if ((mesonlib.is_dragonflybsd() or mesonlib.is_freebsd()) and not
- self.static and version_compare(self.version, '>= 4.0')):
- # llvm-config on DragonFly BSD and FreeBSD for versions 4.0, 5.0,
- # and 6.0 have an error when generating arguments for shared mode
- # linking, even though libLLVM.so is installed, because for some
- # reason the tool expects to find a .so for each static library.
- # This works around that.
- self.link_args = self.get_config_value(['--ldflags'], 'link_args')
- self.link_args.append('-lLLVM')
- return
+ mode = self.get_config_value(['--shared-mode'], 'link_args')[0]
+ if not self.static and mode == 'static':
+ # If llvm is configured with LLVM_BUILD_LLVM_DYLIB but not with
+ # LLVM_LINK_LLVM_DYLIB and not LLVM_BUILD_SHARED_LIBS (which
+ # upstreams doesn't recomend using), then llvm-config will lie to
+ # you about how to do shared-linking. It wants to link to a a bunch
+ # of individual shared libs (which don't exist because llvm wasn't
+ # built with LLVM_BUILD_SHARED_LIBS.
+ #
+ # Therefore, we'll try to get the libfiles, if the return code is 0
+ # or we get an empty list, then we'll try to build a working
+ # configuration by hand.
+ try:
+ self.__check_libfiles(True)
+ except DependencyException:
+ lib_ext = get_shared_library_suffix(environment, self.native)
+ libdir = self.get_config_value(['--libdir'], 'link_args')[0]
+ # Sort for reproducability
+ matches = sorted(glob.iglob(os.path.join(libdir, 'libLLVM*{}'.format(lib_ext))))
+ if not matches:
+ if self.required:
+ raise
+ return
+
+ self.link_args = self.get_config_value(['--ldflags'], 'link_args')
+ libname = os.path.basename(matches[0]).rstrip(lib_ext).lstrip('lib')
+ self.link_args.append('-l{}'.format(libname))
+ return
+ elif self.static and mode == 'shared':
+ # If, however LLVM_BUILD_SHARED_LIBS is true # (*cough* gentoo *cough*)
+ # then this is correct. Building with LLVM_BUILD_SHARED_LIBS has a side
+ # effect, it stops the generation of static archives. Therefore we need
+ # to check for that and error out on static if this is the case
+ try:
+ self.__check_libfiles(False)
+ except DependencyException:
+ if self.required:
+ raise
+
link_args = ['--link-static', '--system-libs'] if self.static else ['--link-shared']
self.link_args = self.get_config_value(
['--libs', '--ldflags'] + link_args + list(self.required_modules),
diff --git a/mesonbuild/dependencies/misc.py b/mesonbuild/dependencies/misc.py
index 5164512..a2f7daf 100644
--- a/mesonbuild/dependencies/misc.py
+++ b/mesonbuild/dependencies/misc.py
@@ -506,3 +506,34 @@ class LibWmfDependency(ExternalDependency):
@staticmethod
def get_methods():
return [DependencyMethods.PKGCONFIG, DependencyMethods.CONFIG_TOOL]
+
+
+class LibGCryptDependency(ExternalDependency):
+ def __init__(self, environment, kwargs):
+ super().__init__('libgcrypt', environment, None, kwargs)
+
+ @classmethod
+ def _factory(cls, environment, kwargs):
+ methods = cls._process_method_kw(kwargs)
+ candidates = []
+
+ if DependencyMethods.PKGCONFIG in methods:
+ candidates.append(functools.partial(PkgConfigDependency, 'libgcrypt', environment, kwargs))
+
+ if DependencyMethods.CONFIG_TOOL in methods:
+ candidates.append(functools.partial(ConfigToolDependency.factory,
+ 'libgcrypt', environment, None, kwargs, ['libgcrypt-config'],
+ 'libgcrypt-config',
+ LibGCryptDependency.tool_finish_init))
+
+ return candidates
+
+ @staticmethod
+ def tool_finish_init(ctdep):
+ ctdep.compile_args = ctdep.get_config_value(['--cflags'], 'compile_args')
+ ctdep.link_args = ctdep.get_config_value(['--libs'], 'link_args')
+ ctdep.version = ctdep.get_config_value(['--version'], 'version')[0]
+
+ @staticmethod
+ def get_methods():
+ return [DependencyMethods.PKGCONFIG, DependencyMethods.CONFIG_TOOL]
diff --git a/mesonbuild/interpreter.py b/mesonbuild/interpreter.py
index 131c24e..a4d9472 100644
--- a/mesonbuild/interpreter.py
+++ b/mesonbuild/interpreter.py
@@ -1686,12 +1686,15 @@ class MesonMain(InterpreterObject):
@permittedKwargs({})
def add_dist_script_method(self, args, kwargs):
- if len(args) != 1:
- raise InterpreterException('add_dist_script takes exactly one argument')
+ if len(args) < 1:
+ raise InterpreterException('add_dist_script takes one or more arguments')
+ if len(args) > 1:
+ FeatureNew('Calling "add_dist_script" with multiple arguments', '0.49.0').use(self.interpreter.subproject)
check_stringlist(args, 'add_dist_script argument must be a string')
if self.interpreter.subproject != '':
raise InterpreterException('add_dist_script may not be used in a subproject.')
- self.build.dist_scripts.append(os.path.join(self.interpreter.subdir, args[0]))
+ script = self._find_source_script(args[0], args[1:])
+ self.build.dist_scripts.append(script)
@noPosargs
@permittedKwargs({})
diff --git a/mesonbuild/mconf.py b/mesonbuild/mconf.py
index 2fd69b0..576c574 100644
--- a/mesonbuild/mconf.py
+++ b/mesonbuild/mconf.py
@@ -13,17 +13,13 @@
# limitations under the License.
import os
-import argparse
from . import (coredata, mesonlib, build)
-def buildparser():
- parser = argparse.ArgumentParser(prog='meson configure')
+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)')
- return parser
class ConfException(mesonlib.MesonException):
@@ -149,9 +145,7 @@ class Conf:
self.print_options('Testing options', test_options)
-def run(args):
- args = mesonlib.expand_arguments(args)
- options = buildparser().parse_args(args)
+def run(options):
coredata.parse_cmd_line_options(options)
builddir = os.path.abspath(os.path.realpath(options.builddir))
try:
diff --git a/mesonbuild/mesonlib.py b/mesonbuild/mesonlib.py
index 8648a0d..33900b6 100644
--- a/mesonbuild/mesonlib.py
+++ b/mesonbuild/mesonlib.py
@@ -48,6 +48,23 @@ else:
python_command = [sys.executable]
meson_command = None
+def set_meson_command(mainfile):
+ global python_command
+ global meson_command
+ # On UNIX-like systems `meson` is a Python script
+ # On Windows `meson` and `meson.exe` are wrapper exes
+ if not mainfile.endswith('.py'):
+ meson_command = [mainfile]
+ elif os.path.isabs(mainfile) and mainfile.endswith('mesonmain.py'):
+ # Can't actually run meson with an absolute path to mesonmain.py, it must be run as -m mesonbuild.mesonmain
+ meson_command = python_command + ['-m', 'mesonbuild.mesonmain']
+ else:
+ # Either run uninstalled, or full path to meson-script.py
+ meson_command = python_command + [mainfile]
+ # We print this value for unit tests.
+ if 'MESON_COMMAND_TESTS' in os.environ:
+ mlog.log('meson_command is {!r}'.format(meson_command))
+
def is_ascii_string(astring):
try:
if isinstance(astring, str):
diff --git a/mesonbuild/mesonmain.py b/mesonbuild/mesonmain.py
index dfad2e7..ebe2c8e 100644
--- a/mesonbuild/mesonmain.py
+++ b/mesonbuild/mesonmain.py
@@ -12,261 +12,139 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-import time
-import sys, stat, traceback, argparse
-import datetime
+import sys
import os.path
-import platform
-import cProfile as profile
+import importlib
+import traceback
+import argparse
-from . import environment, interpreter, mesonlib
-from . import build
-from . import mlog, coredata
+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 WrapMode
-
-default_warning = '1'
-
-def create_parser():
- p = argparse.ArgumentParser(prog='meson')
- coredata.register_builtin_arguments(p)
- p.add_argument('--cross-file', default=None,
- help='File describing cross compilation environment.')
- p.add_argument('-v', '--version', action='version',
- version=coredata.version)
- # See the mesonlib.WrapMode enum for documentation
- p.add_argument('--wrap-mode', default=None,
- type=wrapmodetype, choices=WrapMode,
- help='Special wrap mode to use')
- p.add_argument('--profile-self', action='store_true', dest='profile',
- help=argparse.SUPPRESS)
- p.add_argument('--fatal-meson-warnings', action='store_true', dest='fatal_warnings',
- help='Make all Meson warnings fatal')
- p.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.')
- p.add_argument('builddir', nargs='?', default=None)
- p.add_argument('sourcedir', nargs='?', default=None)
- return p
-
-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.realpath(dir1))
- ndir2 = os.path.abspath(os.path.realpath(dir2))
- if not os.path.exists(ndir1):
- os.makedirs(ndir1)
- if not os.path.exists(ndir2):
- os.makedirs(ndir2)
- if not stat.S_ISDIR(os.stat(ndir1).st_mode):
- raise MesonException('%s is not a directory' % dir1)
- if not stat.S_ISDIR(os.stat(ndir2).st_mode):
- raise MesonException('%s is not a directory' % dir2)
- if os.path.samefile(dir1, dir2):
- raise MesonException('Source and build directories must not be the same. Create a pristine build directory.')
- if self.has_build_file(ndir1):
- if self.has_build_file(ndir2):
- raise MesonException('Both directories contain a build file %s.' % environment.build_filename)
- return ndir1, ndir2
- if self.has_build_file(ndir2):
- return ndir2, ndir1
- raise MesonException('Neither directory contains a build file %s.' % environment.build_filename)
-
- def validate_dirs(self, dir1, dir2, reconfigure):
- (src_dir, build_dir) = self.validate_core_dirs(dir1, dir2)
- priv_dir = os.path.join(build_dir, 'meson-private/coredata.dat')
- if os.path.exists(priv_dir):
- if not reconfigure:
- print('Directory already configured.\n'
- '\nJust run your build command (e.g. ninja) and Meson will regenerate as necessary.\n'
- 'If ninja fails, run "ninja reconfigure" or "meson --reconfigure"\n'
- 'to force Meson to regenerate.\n'
- '\nIf build failures persist, manually wipe your build directory to clear any\n'
- 'stored system data.\n'
- '\nTo change option values, run "meson configure" instead.')
- sys.exit(0)
+from .wrap import wraptool
+
+
+class CommandLineParser:
+ def __init__(self):
+ self.commands = {}
+ self.hidden_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('wrap', wraptool.add_arguments, wraptool.run,
+ help='Wrap tools')
+ self.add_command('help', self.add_help_arguments, self.run_help_command,
+ help='Print help of a subcommand')
+
+ # Hidden commands
+ self.add_command('rewrite', rewriter.add_arguments, rewriter.run,
+ help=argparse.SUPPRESS)
+ self.add_command('runpython', self.add_runpython_arguments, self.run_runpython_command,
+ help=argparse.SUPPRESS)
+
+ def add_command(self, name, add_arguments_func, run_func, help):
+ # FIXME: Cannot have hidden subparser:
+ # https://bugs.python.org/issue22848
+ if help == argparse.SUPPRESS:
+ p = argparse.ArgumentParser(prog='meson ' + name)
+ self.hidden_commands.append(name)
else:
- if reconfigure:
- print('Directory does not contain a valid build tree:\n{}'.format(build_dir))
- sys.exit(1)
- return src_dir, build_dir
-
- def check_pkgconfig_envvar(self, env):
- curvar = os.environ.get('PKG_CONFIG_PATH', '')
- if curvar != env.coredata.pkgconf_envvar:
- mlog.warning('PKG_CONFIG_PATH has changed between invocations from "%s" to "%s".' %
- (env.coredata.pkgconf_envvar, curvar))
- env.coredata.pkgconf_envvar = curvar
-
- def generate(self):
- env = environment.Environment(self.source_dir, self.build_dir, self.options)
- mlog.initialize(env.get_log_dir(), self.options.fatal_warnings)
- if self.options.profile:
- mlog.set_timestamp_start(time.monotonic())
- with mesonlib.BuildDirLock(self.build_dir):
- self._generate(env)
-
- def _generate(self, env):
- mlog.debug('Build started at', datetime.datetime.now().isoformat())
- mlog.debug('Main binary:', sys.executable)
- mlog.debug('Python system:', platform.system())
- mlog.log(mlog.bold('The Meson build system'))
- self.check_pkgconfig_envvar(env)
- mlog.log('Version:', coredata.version)
- mlog.log('Source dir:', mlog.bold(self.source_dir))
- mlog.log('Build dir:', mlog.bold(self.build_dir))
- if env.is_cross_build():
- mlog.log('Build type:', mlog.bold('cross build'))
+ 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:
+ self.commands[options.command].print_help()
else:
- mlog.log('Build type:', mlog.bold('native build'))
- b = build.Build(env)
-
- intr = interpreter.Interpreter(b)
- if env.is_cross_build():
- mlog.log('Host machine cpu family:', mlog.bold(intr.builtin['host_machine'].cpu_family_method([], {})))
- mlog.log('Host machine cpu:', mlog.bold(intr.builtin['host_machine'].cpu_method([], {})))
- mlog.log('Target machine cpu family:', mlog.bold(intr.builtin['target_machine'].cpu_family_method([], {})))
- mlog.log('Target machine cpu:', mlog.bold(intr.builtin['target_machine'].cpu_method([], {})))
- mlog.log('Build machine cpu family:', mlog.bold(intr.builtin['build_machine'].cpu_family_method([], {})))
- mlog.log('Build machine cpu:', mlog.bold(intr.builtin['build_machine'].cpu_method([], {})))
- if self.options.profile:
- fname = os.path.join(self.build_dir, 'meson-private', 'profile-interpreter.log')
- profile.runctx('intr.run()', globals(), locals(), filename=fname)
+ self.parser.print_help()
+ return 0
+
+ def run(self, args):
+ # If first arg is not a known command, assume user wants to run the setup
+ # command.
+ known_commands = list(self.commands.keys()) + ['-h', '--help']
+ if len(args) == 0 or args[0] not in known_commands:
+ args = ['setup'] + args
+
+ # Hidden commands have their own parser instead of using the global one
+ if args[0] in self.hidden_commands:
+ parser = self.commands[args[0]]
+ args = args[1:]
else:
- intr.run()
- # Print all default option values that don't match the current value
- for def_opt_name, def_opt_value, cur_opt_value in intr.get_non_matching_default_options():
- mlog.log('Option', mlog.bold(def_opt_name), 'is:',
- mlog.bold(str(cur_opt_value)),
- '[default: {}]'.format(str(def_opt_value)))
+ parser = self.parser
+
+ args = mesonlib.expand_arguments(args)
+ options = parser.parse_args(args)
+
try:
- dumpfile = os.path.join(env.get_scratch_dir(), 'build.dat')
- # We would like to write coredata as late as possible since we use the existence of
- # this file to check if we generated the build file successfully. Since coredata
- # includes settings, the build files must depend on it and appear newer. However, due
- # to various kernel caches, we cannot guarantee that any time in Python is exactly in
- # sync with the time that gets applied to any files. Thus, we dump this file as late as
- # possible, but before build files, and if any error occurs, delete it.
- cdf = env.dump_coredata()
- if self.options.profile:
- fname = 'profile-{}-backend.log'.format(intr.backend.name)
- fname = os.path.join(self.build_dir, 'meson-private', fname)
- profile.runctx('intr.backend.generate(intr)', globals(), locals(), filename=fname)
- else:
- intr.backend.generate(intr)
- build.save(b, dumpfile)
- # Post-conf scripts must be run after writing coredata or else introspection fails.
- intr.backend.run_postconf_scripts()
- except:
- if 'cdf' in locals():
- old_cdf = cdf + '.prev'
- if os.path.exists(old_cdf):
- os.replace(old_cdf, cdf)
- else:
- os.unlink(cdf)
- raise
+ return options.run_func(options)
+ except MesonException as e:
+ mlog.exception(e)
+ logfile = mlog.shutdown()
+ if logfile is not None:
+ mlog.log("\nA full log can be found at", mlog.bold(logfile))
+ if os.environ.get('MESON_FORCE_BACKTRACE'):
+ raise
+ return 1
+ except Exception as e:
+ if os.environ.get('MESON_FORCE_BACKTRACE'):
+ raise
+ traceback.print_exc()
+ return 2
+ finally:
+ mlog.shutdown()
-def run_script_command(args):
- cmdname = args[0]
- cmdargs = args[1:]
- if cmdname == 'exe':
- import mesonbuild.scripts.meson_exe as abc
- cmdfunc = abc.run
- elif cmdname == 'cleantrees':
- import mesonbuild.scripts.cleantrees as abc
- cmdfunc = abc.run
- elif cmdname == 'commandrunner':
- import mesonbuild.scripts.commandrunner as abc
- cmdfunc = abc.run
- elif cmdname == 'delsuffix':
- import mesonbuild.scripts.delwithsuffix as abc
- cmdfunc = abc.run
- elif cmdname == 'dirchanger':
- import mesonbuild.scripts.dirchanger as abc
- cmdfunc = abc.run
- elif cmdname == 'gtkdoc':
- import mesonbuild.scripts.gtkdochelper as abc
- cmdfunc = abc.run
- elif cmdname == 'msgfmthelper':
- import mesonbuild.scripts.msgfmthelper as abc
- cmdfunc = abc.run
- elif cmdname == 'hotdoc':
- import mesonbuild.scripts.hotdochelper as abc
- cmdfunc = abc.run
- elif cmdname == 'regencheck':
- import mesonbuild.scripts.regen_checker as abc
- cmdfunc = abc.run
- elif cmdname == 'symbolextractor':
- import mesonbuild.scripts.symbolextractor as abc
- cmdfunc = abc.run
- elif cmdname == 'scanbuild':
- import mesonbuild.scripts.scanbuild as abc
- cmdfunc = abc.run
- elif cmdname == 'vcstagger':
- import mesonbuild.scripts.vcstagger as abc
- cmdfunc = abc.run
- elif cmdname == 'gettext':
- import mesonbuild.scripts.gettext as abc
- cmdfunc = abc.run
- elif cmdname == 'yelphelper':
- import mesonbuild.scripts.yelphelper as abc
- cmdfunc = abc.run
- elif cmdname == 'uninstall':
- import mesonbuild.scripts.uninstall as abc
- cmdfunc = abc.run
- elif cmdname == 'dist':
- import mesonbuild.scripts.dist as abc
- cmdfunc = abc.run
- elif cmdname == 'coverage':
- import mesonbuild.scripts.coverage as abc
- cmdfunc = abc.run
- else:
- raise MesonException('Unknown internal command {}.'.format(cmdname))
- return cmdfunc(cmdargs)
+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)
-def set_meson_command(mainfile):
- # On UNIX-like systems `meson` is a Python script
- # On Windows `meson` and `meson.exe` are wrapper exes
- if not mainfile.endswith('.py'):
- mesonlib.meson_command = [mainfile]
- elif os.path.isabs(mainfile) and mainfile.endswith('mesonmain.py'):
- # Can't actually run meson with an absolute path to mesonmain.py, it must be run as -m mesonbuild.mesonmain
- mesonlib.meson_command = mesonlib.python_command + ['-m', 'mesonbuild.mesonmain']
- else:
- # Either run uninstalled, or full path to meson-script.py
- mesonlib.meson_command = mesonlib.python_command + [mainfile]
- # We print this value for unit tests.
- if 'MESON_COMMAND_TESTS' in os.environ:
- mlog.log('meson_command is {!r}'.format(mesonlib.meson_command))
+ 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):
@@ -274,6 +152,7 @@ def run(original_args, mainfile):
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')
@@ -283,104 +162,23 @@ def run(original_args, mainfile):
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
- set_meson_command(mainfile)
+ mesonlib.set_meson_command(mainfile)
+
args = original_args[:]
- if len(args) > 0:
- # First check if we want to run a subcommand.
- cmd_name = args[0]
- remaining_args = args[1:]
- # "help" is a special case: Since printing of the help may be
- # delegated to a subcommand, we edit cmd_name before executing
- # the rest of the logic here.
- if cmd_name == 'help':
- remaining_args += ['--help']
- args = remaining_args
- cmd_name = args[0]
- if cmd_name == 'test':
- from . import mtest
- return mtest.run(remaining_args)
- elif cmd_name == 'setup':
- args = remaining_args
- # FALLTHROUGH like it's 1972.
- elif cmd_name == 'install':
- from . import minstall
- return minstall.run(remaining_args)
- elif cmd_name == 'introspect':
- from . import mintro
- return mintro.run(remaining_args)
- elif cmd_name == 'rewrite':
- from . import rewriter
- return rewriter.run(remaining_args)
- elif cmd_name == 'configure':
- try:
- from . import mconf
- return mconf.run(remaining_args)
- except MesonException as e:
- mlog.exception(e)
- sys.exit(1)
- elif cmd_name == 'wrap':
- from .wrap import wraptool
- return wraptool.run(remaining_args)
- elif cmd_name == 'init':
- from . import minit
- return minit.run(remaining_args)
- elif cmd_name == 'runpython':
- import runpy
- script_file = remaining_args[0]
- sys.argv[1:] = remaining_args[1:]
- runpy.run_path(script_file, run_name='__main__')
- sys.exit(0)
- # No special command? Do the basic setup/reconf.
+ # 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:
- script = args[1]
- try:
- sys.exit(run_script_command(args[1:]))
- except MesonException as e:
- mlog.error('\nError in {} helper script:'.format(script))
- mlog.exception(e)
- sys.exit(1)
-
- parser = create_parser()
-
- args = mesonlib.expand_arguments(args)
- options = parser.parse_args(args)
- coredata.parse_cmd_line_options(options)
- try:
- app = MesonApp(options)
- except Exception as e:
- # Log directory does not exist, so just print
- # to stdout.
- print('Error during basic setup:\n')
- print(e)
- return 1
- try:
- app.generate()
- except Exception as e:
- if isinstance(e, MesonException):
- mlog.exception(e)
- # Path to log file
- mlog.shutdown()
- logfile = os.path.join(app.build_dir, environment.Environment.log_dir, mlog.log_fname)
- mlog.log("\nA full log can be found at", mlog.bold(logfile))
- if os.environ.get('MESON_FORCE_BACKTRACE'):
- raise
- return 1
- else:
- if os.environ.get('MESON_FORCE_BACKTRACE'):
- raise
- traceback.print_exc()
- return 2
- finally:
- mlog.shutdown()
+ return run_script_command(args[1], args[2:])
- return 0
+ return CommandLineParser().run(args)
def main():
# Always resolve the command path so Ninja can find it for regen, tests, etc.
diff --git a/mesonbuild/minit.py b/mesonbuild/minit.py
index a66361f..394fe40 100644
--- a/mesonbuild/minit.py
+++ b/mesonbuild/minit.py
@@ -14,7 +14,7 @@
"""Code that creates simple startup projects."""
-import os, sys, argparse, re, shutil, subprocess
+import os, sys, re, shutil, subprocess
from glob import glob
from mesonbuild import mesonlib
from mesonbuild.environment import detect_ninja
@@ -425,8 +425,7 @@ def create_meson_build(options):
open('meson.build', 'w').write(content)
print('Generated meson.build file:\n\n' + content)
-def run(args):
- parser = argparse.ArgumentParser(prog='meson')
+def add_arguments(parser):
parser.add_argument("srcfiles", metavar="sourcefile", nargs="*",
help="source files. default: all recognized files in current directory")
parser.add_argument("-n", "--name", help="project name. default: name of current directory")
@@ -441,7 +440,8 @@ def run(args):
parser.add_argument('--type', default='executable',
choices=['executable', 'library'])
parser.add_argument('--version', default='0.1')
- options = parser.parse_args(args)
+
+def run(options):
if len(glob('*')) == 0:
autodetect_options(options, sample=True)
if not options.language:
diff --git a/mesonbuild/minstall.py b/mesonbuild/minstall.py
index 1d72179..b65abe0 100644
--- a/mesonbuild/minstall.py
+++ b/mesonbuild/minstall.py
@@ -14,7 +14,6 @@
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
@@ -33,15 +32,13 @@ build definitions so that it will not break when the change happens.'''
selinux_updates = []
-def buildparser():
- parser = argparse.ArgumentParser(prog='meson install')
+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.')
- return parser
class DirMaker:
def __init__(self, lf):
@@ -501,9 +498,7 @@ class Installer:
else:
raise
-def run(args):
- parser = buildparser()
- opts = parser.parse_args(args)
+def run(opts):
datafilename = 'meson-private/install.dat'
private_dir = os.path.dirname(datafilename)
log_dir = os.path.join(private_dir, '../meson-logs')
@@ -520,6 +515,3 @@ def run(args):
append_to_log(lf, '# Does not contain files installed by custom scripts.')
installer.do_install(datafilename)
return 0
-
-if __name__ == '__main__':
- sys.exit(run(sys.argv[1:]))
diff --git a/mesonbuild/mintro.py b/mesonbuild/mintro.py
index 188459a..b15a608 100644
--- a/mesonbuild/mintro.py
+++ b/mesonbuild/mintro.py
@@ -23,12 +23,10 @@ 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')
+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,
@@ -48,7 +46,6 @@ def buildparser():
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
@@ -206,9 +203,8 @@ def list_projinfo(builddata):
result['subprojects'] = subprojects
print(json.dumps(result))
-def run(args):
+def run(options):
datadir = 'meson-private'
- options = buildparser().parse_args(args)
if options.builddir is not None:
datadir = os.path.join(options.builddir, datadir)
if not os.path.isdir(datadir):
diff --git a/mesonbuild/modules/windows.py b/mesonbuild/modules/windows.py
index 59e845c..f0d5113 100644
--- a/mesonbuild/modules/windows.py
+++ b/mesonbuild/modules/windows.py
@@ -12,7 +12,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+import enum
import os
+import re
from .. import mlog
from .. import mesonlib, build
@@ -24,6 +26,10 @@ from ..interpreter import CustomTargetHolder
from ..interpreterbase import permittedKwargs, FeatureNewKwargs
from ..dependencies import ExternalProgram
+class ResourceCompilerType(enum.Enum):
+ windres = 1
+ rc = 2
+
class WindowsModule(ExtensionModule):
def detect_compiler(self, compilers):
@@ -32,26 +38,14 @@ class WindowsModule(ExtensionModule):
return compilers[l]
raise MesonException('Resource compilation requires a C or C++ compiler.')
- @FeatureNewKwargs('windows.compile_resources', '0.47.0', ['depend_files', 'depends'])
- @permittedKwargs({'args', 'include_directories', 'depend_files', 'depends'})
- def compile_resources(self, state, args, kwargs):
- comp = self.detect_compiler(state.compilers)
+ def _find_resource_compiler(self, state):
+ # FIXME: Does not handle `native: true` executables, see
+ # See https://github.com/mesonbuild/meson/issues/1531
- extra_args = mesonlib.stringlistify(kwargs.get('args', []))
- wrc_depend_files = extract_as_list(kwargs, 'depend_files', pop = True)
- wrc_depends = extract_as_list(kwargs, 'depends', pop = True)
- for d in wrc_depends:
- if isinstance(d, CustomTargetHolder):
- extra_args += get_include_args([d.outdir_include()])
- inc_dirs = extract_as_list(kwargs, 'include_directories', pop = True)
- for incd in inc_dirs:
- if not isinstance(incd.held_object, (str, build.IncludeDirs)):
- raise MesonException('Resource include dirs should be include_directories().')
- extra_args += get_include_args(inc_dirs)
+ if hasattr(self, '_rescomp'):
+ return self._rescomp
rescomp = None
- # FIXME: Does not handle `native: true` executables, see
- # https://github.com/mesonbuild/meson/issues/1531
if state.environment.is_cross_build():
# If cross compiling see if windres has been specified in the
# cross file before trying to find it another way.
@@ -65,6 +59,7 @@ class WindowsModule(ExtensionModule):
rescomp = ExternalProgram('windres', command=os.environ.get('WINDRES'), silent=True)
if not rescomp or not rescomp.found():
+ comp = self.detect_compiler(state.compilers)
if comp.id == 'msvc':
rescomp = ExternalProgram('rc', silent=True)
else:
@@ -73,7 +68,38 @@ class WindowsModule(ExtensionModule):
if not rescomp.found():
raise MesonException('Could not find Windows resource compiler')
- if 'rc' in rescomp.get_path():
+ for (arg, match, type) in [
+ ('/?', '^.*Microsoft.*Resource Compiler.*$', ResourceCompilerType.rc),
+ ('--version', '^.*GNU windres.*$', ResourceCompilerType.windres),
+ ]:
+ p, o, e = mesonlib.Popen_safe(rescomp.get_command() + [arg])
+ m = re.search(match, o, re.MULTILINE)
+ if m:
+ mlog.log('Windows resource compiler: %s' % m.group())
+ self._rescomp = (rescomp, type)
+ break
+ else:
+ raise MesonException('Could not determine type of Windows resource compiler')
+
+ return self._rescomp
+
+ @FeatureNewKwargs('windows.compile_resources', '0.47.0', ['depend_files', 'depends'])
+ @permittedKwargs({'args', 'include_directories', 'depend_files', 'depends'})
+ def compile_resources(self, state, args, kwargs):
+ extra_args = mesonlib.stringlistify(kwargs.get('args', []))
+ wrc_depend_files = extract_as_list(kwargs, 'depend_files', pop = True)
+ wrc_depends = extract_as_list(kwargs, 'depends', pop = True)
+ for d in wrc_depends:
+ if isinstance(d, CustomTargetHolder):
+ extra_args += get_include_args([d.outdir_include()])
+ inc_dirs = extract_as_list(kwargs, 'include_directories', pop = True)
+ for incd in inc_dirs:
+ if not isinstance(incd.held_object, (str, build.IncludeDirs)):
+ raise MesonException('Resource include dirs should be include_directories().')
+ extra_args += get_include_args(inc_dirs)
+
+ rescomp, rescomp_type = self._find_resource_compiler(state)
+ if rescomp_type == ResourceCompilerType.rc:
# RC is used to generate .res files, a special binary resource
# format, which can be passed directly to LINK (apparently LINK uses
# CVTRES internally to convert this to a COFF object)
@@ -129,7 +155,7 @@ class WindowsModule(ExtensionModule):
}
# instruct binutils windres to generate a preprocessor depfile
- if 'windres' in rescomp.get_path():
+ if rescomp_type == ResourceCompilerType.windres:
res_kwargs['depfile'] = res_kwargs['output'] + '.d'
res_kwargs['command'] += ['--preprocessor-arg=-MD', '--preprocessor-arg=-MQ@OUTPUT@', '--preprocessor-arg=-MF@DEPFILE@']
diff --git a/mesonbuild/msetup.py b/mesonbuild/msetup.py
new file mode 100644
index 0000000..1576556
--- /dev/null
+++ b/mesonbuild/msetup.py
@@ -0,0 +1,197 @@
+# 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.realpath(dir1))
+ ndir2 = os.path.abspath(os.path.realpath(dir2))
+ if not os.path.exists(ndir1):
+ os.makedirs(ndir1)
+ if not os.path.exists(ndir2):
+ os.makedirs(ndir2)
+ if not stat.S_ISDIR(os.stat(ndir1).st_mode):
+ raise MesonException('%s is not a directory' % dir1)
+ if not stat.S_ISDIR(os.stat(ndir2).st_mode):
+ raise MesonException('%s is not a directory' % dir2)
+ if os.path.samefile(dir1, dir2):
+ raise MesonException('Source and build directories must not be the same. Create a pristine build directory.')
+ if self.has_build_file(ndir1):
+ if self.has_build_file(ndir2):
+ raise MesonException('Both directories contain a build file %s.' % environment.build_filename)
+ return ndir1, ndir2
+ if self.has_build_file(ndir2):
+ return ndir2, ndir1
+ raise MesonException('Neither directory contains a build file %s.' % environment.build_filename)
+
+ def validate_dirs(self, dir1, dir2, reconfigure):
+ (src_dir, build_dir) = self.validate_core_dirs(dir1, dir2)
+ priv_dir = os.path.join(build_dir, 'meson-private/coredata.dat')
+ if os.path.exists(priv_dir):
+ if not reconfigure:
+ print('Directory already configured.\n'
+ '\nJust run your build command (e.g. ninja) and Meson will regenerate as necessary.\n'
+ 'If ninja fails, run "ninja reconfigure" or "meson --reconfigure"\n'
+ 'to force Meson to regenerate.\n'
+ '\nIf build failures persist, manually wipe your build directory to clear any\n'
+ 'stored system data.\n'
+ '\nTo change option values, run "meson configure" instead.')
+ sys.exit(0)
+ else:
+ if reconfigure:
+ print('Directory does not contain a valid build tree:\n{}'.format(build_dir))
+ sys.exit(1)
+ return src_dir, build_dir
+
+ def check_pkgconfig_envvar(self, env):
+ curvar = os.environ.get('PKG_CONFIG_PATH', '')
+ if curvar != env.coredata.pkgconf_envvar:
+ mlog.warning('PKG_CONFIG_PATH has changed between invocations from "%s" to "%s".' %
+ (env.coredata.pkgconf_envvar, curvar))
+ env.coredata.pkgconf_envvar = curvar
+
+ def generate(self):
+ env = environment.Environment(self.source_dir, self.build_dir, self.options)
+ mlog.initialize(env.get_log_dir(), self.options.fatal_warnings)
+ if self.options.profile:
+ mlog.set_timestamp_start(time.monotonic())
+ with mesonlib.BuildDirLock(self.build_dir):
+ self._generate(env)
+
+ def _generate(self, env):
+ mlog.debug('Build started at', datetime.datetime.now().isoformat())
+ mlog.debug('Main binary:', sys.executable)
+ mlog.debug('Python system:', platform.system())
+ mlog.log(mlog.bold('The Meson build system'))
+ self.check_pkgconfig_envvar(env)
+ mlog.log('Version:', coredata.version)
+ mlog.log('Source dir:', mlog.bold(self.source_dir))
+ mlog.log('Build dir:', mlog.bold(self.build_dir))
+ if env.is_cross_build():
+ mlog.log('Build type:', mlog.bold('cross build'))
+ else:
+ mlog.log('Build type:', mlog.bold('native build'))
+ b = build.Build(env)
+
+ intr = interpreter.Interpreter(b)
+ if env.is_cross_build():
+ mlog.log('Host machine cpu family:', mlog.bold(intr.builtin['host_machine'].cpu_family_method([], {})))
+ mlog.log('Host machine cpu:', mlog.bold(intr.builtin['host_machine'].cpu_method([], {})))
+ mlog.log('Target machine cpu family:', mlog.bold(intr.builtin['target_machine'].cpu_family_method([], {})))
+ mlog.log('Target machine cpu:', mlog.bold(intr.builtin['target_machine'].cpu_method([], {})))
+ mlog.log('Build machine cpu family:', mlog.bold(intr.builtin['build_machine'].cpu_family_method([], {})))
+ mlog.log('Build machine cpu:', mlog.bold(intr.builtin['build_machine'].cpu_method([], {})))
+ if self.options.profile:
+ fname = os.path.join(self.build_dir, 'meson-private', 'profile-interpreter.log')
+ profile.runctx('intr.run()', globals(), locals(), filename=fname)
+ else:
+ intr.run()
+ # Print all default option values that don't match the current value
+ for def_opt_name, def_opt_value, cur_opt_value in intr.get_non_matching_default_options():
+ mlog.log('Option', mlog.bold(def_opt_name), 'is:',
+ mlog.bold(str(cur_opt_value)),
+ '[default: {}]'.format(str(def_opt_value)))
+ try:
+ dumpfile = os.path.join(env.get_scratch_dir(), 'build.dat')
+ # We would like to write coredata as late as possible since we use the existence of
+ # this file to check if we generated the build file successfully. Since coredata
+ # includes settings, the build files must depend on it and appear newer. However, due
+ # to various kernel caches, we cannot guarantee that any time in Python is exactly in
+ # sync with the time that gets applied to any files. Thus, we dump this file as late as
+ # possible, but before build files, and if any error occurs, delete it.
+ cdf = env.dump_coredata()
+ if self.options.profile:
+ fname = 'profile-{}-backend.log'.format(intr.backend.name)
+ fname = os.path.join(self.build_dir, 'meson-private', fname)
+ profile.runctx('intr.backend.generate(intr)', globals(), locals(), filename=fname)
+ else:
+ intr.backend.generate(intr)
+ build.save(b, dumpfile)
+ # Post-conf scripts must be run after writing coredata or else introspection fails.
+ intr.backend.run_postconf_scripts()
+ except:
+ if 'cdf' in locals():
+ old_cdf = cdf + '.prev'
+ if os.path.exists(old_cdf):
+ os.replace(old_cdf, cdf)
+ else:
+ os.unlink(cdf)
+ raise
+
+def run(options):
+ coredata.parse_cmd_line_options(options)
+ app = MesonApp(options)
+ app.generate()
+ return 0
diff --git a/mesonbuild/mtest.py b/mesonbuild/mtest.py
index 8d9a585..78f2252 100644
--- a/mesonbuild/mtest.py
+++ b/mesonbuild/mtest.py
@@ -60,8 +60,7 @@ def determine_worker_count():
num_workers = 1
return num_workers
-def buildparser():
- parser = argparse.ArgumentParser(prog='meson test')
+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',
@@ -102,7 +101,6 @@ def buildparser():
help='Arguments to pass to the specified test(s) or all tests')
parser.add_argument('args', nargs='*',
help='Optional list of tests to run')
- return parser
def returncode_to_status(retcode):
@@ -737,9 +735,7 @@ def rebuild_all(wd):
return True
-def run(args):
- options = buildparser().parse_args(args)
-
+def run(options):
if options.benchmark:
options.num_processes = 1
@@ -784,3 +780,9 @@ def run(args):
else:
print(e)
return 1
+
+def run_with_args(args):
+ parser = argparse.ArgumentParser(prog='meson test')
+ add_arguments(parser)
+ options = parser.parse_args(args)
+ return run(options)
diff --git a/mesonbuild/rewriter.py b/mesonbuild/rewriter.py
index 1127288..5da8c89 100644
--- a/mesonbuild/rewriter.py
+++ b/mesonbuild/rewriter.py
@@ -27,11 +27,8 @@ 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')
+def add_arguments(parser):
parser.add_argument('--sourcedir', default='.',
help='Path to source directory.')
parser.add_argument('--target', default=None,
@@ -39,10 +36,8 @@ def buildparser():
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)
+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.')
diff --git a/mesonbuild/scripts/dist.py b/mesonbuild/scripts/dist.py
index 68cfcd0..56ac585 100644
--- a/mesonbuild/scripts/dist.py
+++ b/mesonbuild/scripts/dist.py
@@ -81,16 +81,17 @@ def run_dist_scripts(dist_root, dist_scripts):
env = os.environ.copy()
env['MESON_DIST_ROOT'] = dist_root
for d in dist_scripts:
- print('Processing dist script %s' % d)
- ddir, dname = os.path.split(d)
- ep = ExternalProgram(dname,
- search_dir=os.path.join(dist_root, ddir),
- silent=True)
- if not ep.found():
- sys.exit('Script %s could not be found in dist directory' % d)
- pc = subprocess.run(ep.command, env=env)
- if pc.returncode != 0:
- sys.exit('Dist script errored out')
+ script = d['exe']
+ args = d['args']
+ name = ' '.join(script + args)
+ print('Running custom dist script {!r}'.format(name))
+ try:
+ rc = subprocess.call(script + args, env=env)
+ if rc != 0:
+ sys.exit('Dist script errored out')
+ except OSError:
+ print('Failed to run dist script {!r}'.format(name))
+ sys.exit(1)
def git_have_dirty_index(src_root):
diff --git a/mesonbuild/scripts/meson_exe.py b/mesonbuild/scripts/meson_exe.py
index 84abfc3..23c7334 100644
--- a/mesonbuild/scripts/meson_exe.py
+++ b/mesonbuild/scripts/meson_exe.py
@@ -81,6 +81,8 @@ def run_exe(exe):
if exe.capture and p.returncode == 0:
with open(exe.capture, 'wb') as output:
output.write(stdout)
+ else:
+ sys.stdout.buffer.write(stdout)
if stderr:
sys.stderr.buffer.write(stderr)
return p.returncode
diff --git a/mesonbuild/wrap/wraptool.py b/mesonbuild/wrap/wraptool.py
index 364452d..bb64b5b 100644
--- a/mesonbuild/wrap/wraptool.py
+++ b/mesonbuild/wrap/wraptool.py
@@ -16,7 +16,6 @@ import json
import sys, os
import configparser
import shutil
-import argparse
from glob import glob
@@ -208,9 +207,6 @@ def status(options):
else:
print('', name, 'not up to date. Have %s %d, but %s %d is available.' % (current_branch, current_revision, latest_branch, latest_revision))
-def run(args):
- parser = argparse.ArgumentParser(prog='wraptool')
- add_arguments(parser)
- options = parser.parse_args(args)
+def run(options):
options.wrap_func(options)
return 0
diff --git a/run_project_tests.py b/run_project_tests.py
index ba7b5e0..876d135 100755
--- a/run_project_tests.py
+++ b/run_project_tests.py
@@ -247,12 +247,12 @@ def run_test_inprocess(testdir):
os.chdir(testdir)
test_log_fname = Path('meson-logs', 'testlog.txt')
try:
- returncode_test = mtest.run(['--no-rebuild'])
+ returncode_test = mtest.run_with_args(['--no-rebuild'])
if test_log_fname.exists():
test_log = test_log_fname.open(errors='ignore').read()
else:
test_log = ''
- returncode_benchmark = mtest.run(['--no-rebuild', '--benchmark', '--logbase', 'benchmarklog'])
+ returncode_benchmark = mtest.run_with_args(['--no-rebuild', '--benchmark', '--logbase', 'benchmarklog'])
finally:
sys.stdout = old_stdout
sys.stderr = old_stderr
diff --git a/run_tests.py b/run_tests.py
index 2a078ef..af926ea 100755
--- a/run_tests.py
+++ b/run_tests.py
@@ -181,7 +181,7 @@ def run_mtest_inprocess(commandlist):
old_stderr = sys.stderr
sys.stderr = mystderr = StringIO()
try:
- returncode = mtest.run(commandlist)
+ returncode = mtest.run_with_args(commandlist)
finally:
sys.stdout = old_stdout
sys.stderr = old_stderr
diff --git a/test cases/common/14 configure file/meson.build b/test cases/common/14 configure file/meson.build
index d7beeb1..a3601aa 100644
--- a/test cases/common/14 configure file/meson.build
+++ b/test cases/common/14 configure file/meson.build
@@ -12,20 +12,20 @@ assert(conf.get('var', 'default') == 'mystring', 'Get function is not working.')
assert(conf.get('notthere', 'default') == 'default', 'Default value getting is not working.')
cfile = configure_file(input : 'config.h.in',
-output : 'config.h',
-configuration : conf)
+ output : 'config.h',
+ configuration : conf)
e = executable('inctest', 'prog.c',
# Note that you should NOT do this. Don't add generated headers here
# This tests that we do the right thing even if people add in conf files
# to their sources.
-cfile)
+ cfile)
test('inctest', e)
# Test if we can also pass files() as input
configure_file(input : files('config.h.in'),
- output : 'config2.h',
- configuration : conf)
+ output : 'config2.h',
+ configuration : conf)
# Now generate a header file with an external script.
genprog = import('python3').find_python()
@@ -93,8 +93,7 @@ dump = configuration_data()
dump.set('ZERO', 0)
config_templates = files(['config4a.h.in', 'config4b.h.in'])
foreach config_template : config_templates
- configure_file(input : config_template, output : '@BASENAME@',
- configuration : dump)
+ configure_file(input : config_template, output : '@BASENAME@', configuration : dump)
endforeach
test('Substituted', executable('prog4', 'prog4.c'))
@@ -123,8 +122,7 @@ conf5.set('var2', 'error')
configure_file(
input : 'config5.h.in',
output : '@BASENAME@',
- configuration : conf5
-)
+ configuration : conf5)
test('test5', executable('prog5', 'prog5.c'))
# Test escaping
@@ -134,8 +132,7 @@ conf6.set('var2', 'bar')
configure_file(
input : 'config6.h.in',
output : '@BASENAME@',
- configuration : conf6
-)
+ configuration : conf6)
test('test6', executable('prog6', 'prog6.c'))
# test empty install dir string
@@ -152,8 +149,7 @@ configure_file(
input : 'config7.h.in',
output : '@BASENAME@',
format : 'cmake',
- configuration : conf7
-)
+ configuration : conf7)
test('test7', executable('prog7', 'prog7.c'))
# Test copying of an empty configuration data object
@@ -182,24 +178,21 @@ configure_file(
input : 'config8.h.in',
output : '@BASENAME@',
encoding : 'koi8-r',
- configuration : conf8
-)
+ configuration : conf8)
# Test that passing an empty configuration_data() object to a file with
# #mesondefine substitutions does not print the warning.
configure_file(
input: 'nosubst-nocopy1.txt.in',
output: 'nosubst-nocopy1.txt',
- configuration : configuration_data()
-)
+ configuration : configuration_data())
# test that passing an empty configuration_data() object to a file with
# @foo@ substitutions does not print the warning.
configure_file(
input: 'nosubst-nocopy2.txt.in',
output: 'nosubst-nocopy2.txt',
- configuration : configuration_data()
-)
+ configuration : configuration_data())
# test that passing a configured file object to test() works, and that passing
# an empty configuration_data() object to a file that leads to no substitutions
@@ -207,27 +200,23 @@ configure_file(
test_file = configure_file(
input: 'test.py.in',
output: 'test.py',
- configuration: configuration_data()
-)
+ configuration: configuration_data())
# Test that overwriting an existing file creates a warning.
configure_file(
input: 'test.py.in',
output: 'double_output.txt',
- configuration: conf
-)
+ configuration: conf)
configure_file(
input: 'test.py.in',
output: 'double_output.txt',
- configuration: conf
-)
+ configuration: conf)
# Test that the same file name in a different subdir will not create a warning
configure_file(
input: 'test.py.in',
output: 'no_write_conflict.txt',
- configuration: conf
-)
+ configuration: conf)
test('configure-file', test_file)
diff --git a/test cases/d/9 features/app.d b/test cases/d/9 features/app.d
index 6b43bf0..05c56ca 100644
--- a/test cases/d/9 features/app.d
+++ b/test cases/d/9 features/app.d
@@ -41,6 +41,30 @@ void main (string[] args)
exit (1);
}
}
+
+ version (With_VersionInteger)
+ version(3) exit(0);
+
+ version (With_Debug)
+ debug exit(0);
+
+ version (With_DebugInteger)
+ debug(3) exit(0);
+
+ version (With_DebugIdentifier)
+ debug(DebugIdentifier) exit(0);
+
+ version (With_DebugAll) {
+ int dbg = 0;
+ debug dbg++;
+ debug(2) dbg++;
+ debug(3) dbg++;
+ debug(4) dbg++;
+ debug(DebugIdentifier) dbg++;
+
+ if (dbg == 5)
+ exit(0);
+ }
// we fail here
exit (1);
diff --git a/test cases/d/9 features/meson.build b/test cases/d/9 features/meson.build
index 694e488..06f0341 100644
--- a/test cases/d/9 features/meson.build
+++ b/test cases/d/9 features/meson.build
@@ -1,4 +1,4 @@
-project('D Features', 'd')
+project('D Features', 'd', default_options : ['debug=false'])
# ONLY FOR BACKWARDS COMPATIBILITY.
# DO NOT DO THIS IN NEW CODE!
@@ -44,3 +44,63 @@ e_test = executable('dapp_test',
d_unittest: true
)
test('dapp_test', e_test)
+
+# test version level
+e_version_int = executable('dapp_version_int',
+ test_src,
+ d_import_dirs: [data_dir],
+ d_module_versions: ['With_VersionInteger', 3],
+)
+test('dapp_version_int_t', e_version_int, args: ['debug'])
+
+# test version level failure
+e_version_int_fail = executable('dapp_version_int_fail',
+ test_src,
+ d_import_dirs: [data_dir],
+ d_module_versions: ['With_VersionInteger', 2],
+)
+test('dapp_version_int_t_fail', e_version_int_fail, args: ['debug'], should_fail: true)
+
+# test debug conditions: disabled
+e_no_debug = executable('dapp_no_debug',
+ test_src,
+ d_import_dirs: [data_dir],
+ d_module_versions: ['With_Debug'],
+)
+test('dapp_no_debug_t_fail', e_no_debug, args: ['debug'], should_fail: true)
+
+# test debug conditions: enabled
+e_debug = executable('dapp_debug',
+ test_src,
+ d_import_dirs: [data_dir],
+ d_module_versions: ['With_Debug'],
+ d_debug: 1,
+)
+test('dapp_debug_t', e_debug, args: ['debug'])
+
+# test debug conditions: integer
+e_debug_int = executable('dapp_debug_int',
+ test_src,
+ d_import_dirs: [data_dir],
+ d_module_versions: ['With_DebugInteger'],
+ d_debug: 3,
+)
+test('dapp_debug_int_t', e_debug_int, args: ['debug'])
+
+# test debug conditions: identifier
+e_debug_ident = executable('dapp_debug_ident',
+ test_src,
+ d_import_dirs: [data_dir],
+ d_module_versions: ['With_DebugIdentifier'],
+ d_debug: 'DebugIdentifier',
+)
+test('dapp_debug_ident_t', e_debug_ident, args: ['debug'])
+
+# test with all debug conditions at once, and with redundant values
+e_debug_all = executable('dapp_debug_all',
+ test_src,
+ d_import_dirs: [data_dir],
+ d_module_versions: ['With_DebugAll'],
+ d_debug: ['4', 'DebugIdentifier', 2, 'DebugIdentifierUnused'],
+)
+test('dapp_debug_all_t', e_debug_all, args: ['debug'])
diff --git a/test cases/frameworks/24 libgcrypt/libgcrypt_prog.c b/test cases/frameworks/24 libgcrypt/libgcrypt_prog.c
new file mode 100644
index 0000000..f131359
--- /dev/null
+++ b/test cases/frameworks/24 libgcrypt/libgcrypt_prog.c
@@ -0,0 +1,8 @@
+#include <gcrypt.h>
+
+int
+main()
+{
+ gcry_check_version(NULL);
+ return 0;
+}
diff --git a/test cases/frameworks/24 libgcrypt/meson.build b/test cases/frameworks/24 libgcrypt/meson.build
new file mode 100644
index 0000000..5aadb13
--- /dev/null
+++ b/test cases/frameworks/24 libgcrypt/meson.build
@@ -0,0 +1,23 @@
+project('libgcrypt test', 'c')
+
+wm = find_program('libgcrypt-config', required : false)
+if not wm.found()
+ error('MESON_SKIP_TEST: libgcrypt-config not installed')
+endif
+
+libgcrypt_dep = dependency('libgcrypt', version : '>= 1.0')
+libgcrypt_ver = libgcrypt_dep.version()
+assert(libgcrypt_ver.split('.').length() > 1, 'libgcrypt version is "@0@"'.format(libgcrypt_ver))
+message('libgcrypt version is "@0@"'.format(libgcrypt_ver))
+e = executable('libgcrypt_prog', 'libgcrypt_prog.c', dependencies : libgcrypt_dep)
+
+test('libgcrypttest', e)
+
+# Test using the method keyword:
+
+dependency('libgcrypt', method : 'config-tool')
+dependency('libgcrypt', method : 'pkg-config', required: false)
+
+# Check we can apply a version constraint
+dependency('libgcrypt', version: '>=@0@'.format(libgcrypt_dep.version()), method: 'pkg-config', required: false)
+dependency('libgcrypt', version: '>=@0@'.format(libgcrypt_dep.version()), method: 'config-tool')
diff --git a/test cases/unit/35 dist script/meson.build b/test cases/unit/35 dist script/meson.build
index 3415ec4..fd672a9 100644
--- a/test cases/unit/35 dist script/meson.build
+++ b/test cases/unit/35 dist script/meson.build
@@ -4,4 +4,4 @@ project('dist script', 'c',
exe = executable('comparer', 'prog.c')
test('compare', exe)
-meson.add_dist_script('replacer.py')
+meson.add_dist_script('replacer.py', '"incorrect"', '"correct"')
diff --git a/test cases/unit/35 dist script/replacer.py b/test cases/unit/35 dist script/replacer.py
index adda365..96ccdcc 100755
--- a/test cases/unit/35 dist script/replacer.py
+++ b/test cases/unit/35 dist script/replacer.py
@@ -2,11 +2,15 @@
import os
import pathlib
+import sys
+
+if len(sys.argv) < 3:
+ sys.exit('usage: replacer.py <pattern> <replacement>')
source_root = pathlib.Path(os.environ['MESON_DIST_ROOT'])
modfile = source_root / 'prog.c'
contents = modfile.read_text()
-contents = contents.replace('"incorrect"', '"correct"')
+contents = contents.replace(sys.argv[1], sys.argv[2])
modfile.write_text(contents)