Commit 51db8475 authored by Dave Reisner's avatar Dave Reisner
Browse files

Add meson.build files to build with meson

Provide both build systems in parallel for now, to ensure that we work
out all the differences between the two. Some time from now, we'll give
up on autotools.

Meson tends to be faster and probably easier to read/maintain. On my
machine, the full meson configure+build+install takes a little under
half as long as a similar autotools-based invocation.

Building with meson is a two step process. First, configure the build:

  meson build

Then, compile the project:

  ninja -C build

There's some mild differences in functionality between meson and
autotools.  specifically:

1) No singular update-po target. meson only generates individual
update-po targets for each textdomain (of which we have 3).  To make
this easier, there's a build-aux/update-po script which finds all
update-po targets and runs them.

2) No 'make dist' equivalent. Just run 'git archive' to generate a
suitable tarball for distribution.
parent dab45f08
#!/usr/bin/env python
# SPDX-License-Identifier: Unlicense
#
# Based on the template file provided by the 'YCM-Generator' project authored by
# Reuben D'Netto.
# Jiahui Xie has re-reformatted and expanded the original script in accordance
# to the requirements of the PEP 8 style guide and 'systemd' project,
# respectively.
#
# The original license is preserved as it is.
#
#
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a compiled
# binary, for any purpose, commercial or non-commercial, and by any
# means.
#
# In jurisdictions that recognize copyright laws, the author or authors
# of this software dedicate any and all copyright interest in the
# software to the public domain. We make this dedication for the benefit
# of the public at large and to the detriment of our heirs and
# successors. We intend this dedication to be an overt act of
# relinquishment in perpetuity of all present and future rights to this
# software under copyright law.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# For more information, please refer to <http://unlicense.org/>
"""
YouCompleteMe configuration file tailored to support the 'meson' build system
used by the 'systemd' project.
"""
import glob
import os
import ycm_core
SOURCE_EXTENSIONS = (".C", ".cpp", ".cxx", ".cc", ".c", ".m", ".mm")
HEADER_EXTENSIONS = (".H", ".h", ".hxx", ".hpp", ".hh")
def DirectoryOfThisScript():
"""
Return the absolute path of the parent directory containing this
script.
"""
return os.path.dirname(os.path.abspath(__file__))
def GuessBuildDirectory():
"""
Guess the build directory using the following heuristics:
1. Returns the current directory of this script plus 'build'
subdirectory in absolute path if this subdirectory exists.
2. Otherwise, probes whether there exists any directory
containing '.ninja_log' file two levels above the current directory;
returns this single directory only if there is one candidate.
"""
result = os.path.join(DirectoryOfThisScript(), "build")
if os.path.exists(result):
return result
result = glob.glob(os.path.join(DirectoryOfThisScript(),
"..", "..", "*", ".ninja_log"))
if not result:
return ""
if 1 != len(result):
return ""
return os.path.split(result[0])[0]
def TraverseByDepth(root, include_extensions):
"""
Return a set of child directories of the 'root' containing file
extensions specified in 'include_extensions'.
NOTE:
1. The 'root' directory itself is excluded from the result set.
2. No subdirectories would be excluded if 'include_extensions' is left
to 'None'.
3. Each entry in 'include_extensions' must begin with string '.'.
"""
is_root = True
result = set()
# Perform a depth first top down traverse of the given directory tree.
for root_dir, subdirs, file_list in os.walk(root):
if not is_root:
# print("Relative Root: ", root_dir)
# print(subdirs)
if include_extensions:
get_ext = os.path.splitext
subdir_extensions = {
get_ext(f)[-1] for f in file_list if get_ext(f)[-1]
}
if subdir_extensions & include_extensions:
result.add(root_dir)
else:
result.add(root_dir)
else:
is_root = False
return result
_project_src_dir = os.path.join(DirectoryOfThisScript(), "src")
_include_dirs_set = TraverseByDepth(_project_src_dir, frozenset({".h"}))
flags = [
"-x",
"c"
# The following flags are partially redundant due to the existence of
# 'compile_commands.json'.
# '-Wall',
# '-Wextra',
# '-Wfloat-equal',
# '-Wpointer-arith',
# '-Wshadow',
# '-std=gnu99',
]
for include_dir in _include_dirs_set:
flags.append("-I" + include_dir)
# Set this to the absolute path to the folder (NOT the file!) containing the
# compile_commands.json file to use that instead of 'flags'. See here for
# more details: http://clang.llvm.org/docs/JSONCompilationDatabase.html
#
# You can get CMake to generate this file for you by adding:
# set( CMAKE_EXPORT_COMPILE_COMMANDS 1 )
# to your CMakeLists.txt file.
#
# Most projects will NOT need to set this to anything; you can just change the
# 'flags' list of compilation flags. Notice that YCM itself uses that approach.
compilation_database_folder = GuessBuildDirectory()
if os.path.exists(compilation_database_folder):
database = ycm_core.CompilationDatabase(compilation_database_folder)
else:
database = None
def MakeRelativePathsInFlagsAbsolute(flags, working_directory):
"""
Iterate through 'flags' and replace the relative paths prefixed by
'-isystem', '-I', '-iquote', '--sysroot=' with absolute paths
start with 'working_directory'.
"""
if not working_directory:
return list(flags)
new_flags = []
make_next_absolute = False
path_flags = ["-isystem", "-I", "-iquote", "--sysroot="]
for flag in flags:
new_flag = flag
if make_next_absolute:
make_next_absolute = False
if not flag.startswith("/"):
new_flag = os.path.join(working_directory, flag)
for path_flag in path_flags:
if flag == path_flag:
make_next_absolute = True
break
if flag.startswith(path_flag):
path = flag[len(path_flag):]
new_flag = path_flag + os.path.join(working_directory, path)
break
if new_flag:
new_flags.append(new_flag)
return new_flags
def IsHeaderFile(filename):
"""
Check whether 'filename' is considered as a header file.
"""
extension = os.path.splitext(filename)[1]
return extension in HEADER_EXTENSIONS
def GetCompilationInfoForFile(filename):
"""
Helper function to look up compilation info of 'filename' in the 'database'.
"""
# The compilation_commands.json file generated by CMake does not have
# entries for header files. So we do our best by asking the db for flags for
# a corresponding source file, if any. If one exists, the flags for that
# file should be good enough.
if not database:
return None
if IsHeaderFile(filename):
basename = os.path.splitext(filename)[0]
for extension in SOURCE_EXTENSIONS:
replacement_file = basename + extension
if os.path.exists(replacement_file):
compilation_info = \
database.GetCompilationInfoForFile(replacement_file)
if compilation_info.compiler_flags_:
return compilation_info
return None
return database.GetCompilationInfoForFile(filename)
def FlagsForFile(filename, **kwargs):
"""
Callback function to be invoked by YouCompleteMe in order to get the
information necessary to compile 'filename'.
It returns a dictionary with a single element 'flags'. This element is a
list of compiler flags to pass to libclang for the file 'filename'.
"""
if database:
# Bear in mind that compilation_info.compiler_flags_ does NOT return a
# python list, but a "list-like" StringVec object
compilation_info = GetCompilationInfoForFile(filename)
if not compilation_info:
return None
final_flags = MakeRelativePathsInFlagsAbsolute(
compilation_info.compiler_flags_,
compilation_info.compiler_working_dir_)
else:
relative_to = DirectoryOfThisScript()
final_flags = MakeRelativePathsInFlagsAbsolute(flags, relative_to)
return {
"flags": final_flags,
"do_cache": True
}
#!@BASH@
input=$1
output=$2
mode=$3
"@SED@" \
-e "s|@rootdir[@]|@ROOTDIR@|g" \
-e "s|@localedir[@]|@LOCALEDIR@|g" \
-e "s|@sysconfdir[@]|@sysconfdir@|g" \
-e "s|@localstatedir[@]|@localstatedir@|g" \
-e "s|@libmakepkgdir[@]|@LIBMAKEPKGDIR@|g" \
-e "s|@pkgdatadir[@]|@PKGDATADIR@|g" \
-e "s|@prefix[@]|@PREFIX@|g" \
-e "1s|#!/bin/bash|#!@BASH@|g" \
-e "s|@PACKAGE_VERSION[@]|@PACKAGE_VERSION@|g" \
-e "s|@PACKAGE_NAME[@]|@PACKAGE_NAME@|g" \
-e "s|@BUILDSCRIPT[@]|@BUILDSCRIPT@|g" \
-e "s|@TEMPLATE_DIR[@]|@TEMPLATE_DIR@|g" \
-e "s|@DEBUGSUFFIX[@]|@DEBUGSUFFIX@|g" \
-e "s|@INODECMD[@]|@INODECMD@|g" \
-e "s|@OWNERCMD[@]|@OWNERCMD@|g" \
-e "s|@MODECMD[@]|@MODECMD@|g" \
-e "s|@SEDINPLACEFLAGS[@]|@SEDINPLACEFLAGS@|g" \
-e "s|@SEDPATH[@]|@SEDPATH@|g" \
-e "s|@DUFLAGS[@]|@DUFLAGS@|g" \
-e "s|@DUPATH[@]|@DUPATH@|g" \
-e "s|@configure_input[@]|Generated from ${output##*/}.sh.in; do not edit by hand.|g" \
"$input" >"$output"
if [[ $mode ]]; then
chmod "$mode" "$output"
fi
#!/bin/sh
set -eu
# this is needed mostly because $DESTDIR is provided as a variable,
# and we need to create the target directory...
mkdir -vp "$(dirname "${DESTDIR:-}$2")"
if [ "$(dirname $1)" = . ]; then
ln -vfs -T "$1" "${DESTDIR:-}$2"
else
ln -vfs -T --relative "${DESTDIR:-}$1" "${DESTDIR:-}$2"
fi
#!/usr/bin/env python3
# Adapted from tappy copyright (c) 2016, Matt Layman
# MIT license
# https://github.com/python-tap/tappy
import io
import re
import subprocess
import sys
class Directive(object):
"""A representation of a result line directive."""
skip_pattern = re.compile(
r"""^SKIP\S*
(?P<whitespace>\s*) # Optional whitespace.
(?P<reason>.*) # Slurp up the rest.""",
re.IGNORECASE | re.VERBOSE)
todo_pattern = re.compile(
r"""^TODO\b # The directive name
(?P<whitespace>\s*) # Immediately following must be whitespace.
(?P<reason>.*) # Slurp up the rest.""",
re.IGNORECASE | re.VERBOSE)
def __init__(self, text):
"""Initialize the directive by parsing the text.
The text is assumed to be everything after a '#\s*' on a result line.
"""
self._text = text
self._skip = False
self._todo = False
self._reason = None
match = self.skip_pattern.match(text)
if match:
self._skip = True
self._reason = match.group('reason')
match = self.todo_pattern.match(text)
if match:
if match.group('whitespace'):
self._todo = True
else:
# Catch the case where the directive has no descriptive text.
if match.group('reason') == '':
self._todo = True
self._reason = match.group('reason')
@property
def text(self):
"""Get the entire text."""
return self._text
@property
def skip(self):
"""Check if the directive is a SKIP type."""
return self._skip
@property
def todo(self):
"""Check if the directive is a TODO type."""
return self._todo
@property
def reason(self):
"""Get the reason for the directive."""
return self._reason
class Parser(object):
"""A parser for TAP files and lines."""
# ok and not ok share most of the same characteristics.
result_base = r"""
\s* # Optional whitespace.
(?P<number>\d*) # Optional test number.
\s* # Optional whitespace.
(?P<description>[^#]*) # Optional description before #.
\#? # Optional directive marker.
\s* # Optional whitespace.
(?P<directive>.*) # Optional directive text.
"""
ok = re.compile(r'^ok' + result_base, re.VERBOSE)
not_ok = re.compile(r'^not\ ok' + result_base, re.VERBOSE)
plan = re.compile(r"""
^1..(?P<expected>\d+) # Match the plan details.
[^#]* # Consume any non-hash character to confirm only
# directives appear with the plan details.
\#? # Optional directive marker.
\s* # Optional whitespace.
(?P<directive>.*) # Optional directive text.
""", re.VERBOSE)
diagnostic = re.compile(r'^#')
bail = re.compile(r"""
^Bail\ out!
\s* # Optional whitespace.
(?P<reason>.*) # Optional reason.
""", re.VERBOSE)
version = re.compile(r'^TAP version (?P<version>\d+)$')
TAP_MINIMUM_DECLARED_VERSION = 13
def parse(self, fh):
"""Generate tap.line.Line objects, given a file-like object `fh`.
`fh` may be any object that implements both the iterator and
context management protocol (i.e. it can be used in both a
"with" statement and a "for...in" statement.)
Trailing whitespace and newline characters will be automatically
stripped from the input lines.
"""
with fh:
for line in fh:
yield self.parse_line(line.rstrip())
def parse_line(self, text):
"""Parse a line into whatever TAP category it belongs."""
match = self.ok.match(text)
if match:
return self._parse_result(True, match)
match = self.not_ok.match(text)
if match:
return self._parse_result(False, match)
if self.diagnostic.match(text):
return ('diagnostic', text)
match = self.plan.match(text)
if match:
return self._parse_plan(match)
match = self.bail.match(text)
if match:
return ('bail', match.group('reason'))
match = self.version.match(text)
if match:
return self._parse_version(match)
return ('unknown',)
def _parse_plan(self, match):
"""Parse a matching plan line."""
expected_tests = int(match.group('expected'))
directive = Directive(match.group('directive'))
# Only SKIP directives are allowed in the plan.
if directive.text and not directive.skip:
return ('unknown',)
return ('plan', expected_tests, directive)
def _parse_result(self, ok, match):
"""Parse a matching result line into a result instance."""
return ('result', ok, match.group('number'),
match.group('description').strip(),
Directive(match.group('directive')))
def _parse_version(self, match):
version = int(match.group('version'))
if version < self.TAP_MINIMUM_DECLARED_VERSION:
raise ValueError('It is an error to explicitly specify '
'any version lower than 13.')
return ('version', version)
class Rules(object):
def __init__(self):
self._lines_seen = {'plan': [], 'test': 0, 'failed': 0, 'version': []}
self._errors = []
def check(self, final_line_count):
"""Check the status of all provided data and update the suite."""
if self._lines_seen['version']:
self._process_version_lines()
self._process_plan_lines(final_line_count)
def check_errors(self):
if self._lines_seen['failed'] > 0:
self._add_error('Tests failed.')
if self._errors:
for error in self._errors:
print(error)
return 1
return 0
def _process_version_lines(self):
"""Process version line rules."""
if len(self._lines_seen['version']) > 1:
self._add_error('Multiple version lines appeared.')
elif self._lines_seen['version'][0] != 1:
self._add_error('The version must be on the first line.')
def _process_plan_lines(self, final_line_count):
"""Process plan line rules."""
if not self._lines_seen['plan']:
self._add_error('Missing a plan.')
return
if len(self._lines_seen['plan']) > 1:
self._add_error('Only one plan line is permitted per file.')
return
expected_tests, at_line = self._lines_seen['plan'][0]
if not self._plan_on_valid_line(at_line, final_line_count):
self._add_error(
'A plan must appear at the beginning or end of the file.')
return
if expected_tests != self._lines_seen['test']:
self._add_error(
'Expected {expected_count} tests '
'but only {seen_count} ran.'.format(
expected_count=expected_tests,
seen_count=self._lines_seen['test']))
def _plan_on_valid_line(self, at_line, final_line_count):
"""Check if a plan is on a valid line."""
# Put the common cases first.
if at_line == 1 or at_line == final_line_count:
return True
# The plan may only appear on line 2 if the version is at line 1.
after_version = (
self._lines_seen['version'] and
self._lines_seen['version'][0] == 1 and
at_line == 2)
if after_version:
return True
return False
def handle_bail(self, reason):
"""Handle a bail line."""
self._add_error('Bailed: {reason}').format(reason=reason)
def handle_skipping_plan(self):
"""Handle a plan that contains a SKIP directive."""
sys.exit(77)
def saw_plan(self, expected_tests, at_line):
"""Record when a plan line was seen."""
self._lines_seen['plan'].append((expected_tests, at_line))
def saw_test(self, ok):
"""Record when a test line was seen."""
self._lines_seen['test'] += 1
if not ok:
self._lines_seen['failed'] += 1
def saw_version_at(self, line_counter):
"""Record when a version line was seen."""
self._lines_seen['version'].append(line_counter)
def _add_error(self, message):
self._errors += [message]
if __name__ == '__main__':
parser = Parser()
rules = Rules()
try:
out = subprocess.check_output(sys.argv[1:], universal_newlines=True)
except subprocess.CalledProcessError as e:
sys.stdout.write(e.output)
raise e
line_generator = parser.parse(io.StringIO(out))
line_counter = 0
for line in line_generator:
line_counter += 1
if line[0] == 'unknown':
continue
if line[0] == 'result':
rules.saw_test(line[1])
print('{okay} {num} {description} {directive}'.format(
okay=('' if line[1] else 'not ') + 'ok', num=line[2],
description=line[3], directive=line[4].text))
elif line[0] == 'plan':
if line[2].skip:
rules.handle_skipping_plan()
rules.saw_plan(line[1], line_counter)
elif line[0] == 'bail':
rules.handle_bail(line[1])
elif line[0] == 'version':
rules.saw_version_at(line_counter)
elif line[0] == 'diagnostic':
print(line[1])
rules.check(line_counter)
sys.exit(rules.check_errors())
#!/bin/bash
find_build_directory() {
local build_dirs=(*/.ninja_log)
if [[ ! -e ${build_dirs[0]} ]]; then
echo "error: No build directory found. Have you run 'meson build' yet?" >&2
return 1
elif (( ${#build_dirs[*]} > 1 )); then
echo "error: Multiple build directories found. Unable to proceed." >&2
return 1
fi
printf '%s\n' "${build_dirs[0]%/*}"
}
filter_targets_by_name() {
if command -v jq &>/dev/null; then
jq --arg re "$1" -r 'map(.name)[] | select(match($re))'
else
json_pp | awk -v filter="$1" -F'[:"]' \
'$2 == "name" && $(NF - 1) ~ filter { print $(NF - 1) }'
fi
}
# Make things simple and require that we're in the build root rather than
# trying to chase down the location of this script and the relative build dir.
if [[ ! -d .git ]]; then