1# Copyright 2018 The Meson development team
2
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6
7#     http://www.apache.org/licenses/LICENSE-2.0
8
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14import re
15import os, os.path, pathlib
16import shutil
17import typing as T
18
19from . import ExtensionModule, ModuleReturnValue
20
21from .. import build, dependencies, mesonlib, mlog
22from ..cmake import SingleTargetOptions, TargetOptions, cmake_defines_to_args
23from ..interpreter import ConfigurationDataHolder, InterpreterException, SubprojectHolder
24from ..interpreterbase import (
25    InterpreterObject,
26    ObjectHolder,
27
28    FeatureNew,
29    FeatureNewKwargs,
30    FeatureDeprecatedKwargs,
31
32    stringArgs,
33    permittedKwargs,
34    noPosargs,
35    noKwargs,
36
37    InvalidArguments,
38)
39
40
41COMPATIBILITIES = ['AnyNewerVersion', 'SameMajorVersion', 'SameMinorVersion', 'ExactVersion']
42
43# Taken from https://github.com/Kitware/CMake/blob/master/Modules/CMakePackageConfigHelpers.cmake
44PACKAGE_INIT_BASE = '''
45####### Expanded from \\@PACKAGE_INIT\\@ by configure_package_config_file() #######
46####### Any changes to this file will be overwritten by the next CMake run ####
47####### The input file was @inputFileName@ ########
48
49get_filename_component(PACKAGE_PREFIX_DIR "${CMAKE_CURRENT_LIST_DIR}/@PACKAGE_RELATIVE_PATH@" ABSOLUTE)
50'''
51PACKAGE_INIT_EXT = '''
52# Use original install prefix when loaded through a "/usr move"
53# cross-prefix symbolic link such as /lib -> /usr/lib.
54get_filename_component(_realCurr "${CMAKE_CURRENT_LIST_DIR}" REALPATH)
55get_filename_component(_realOrig "@absInstallDir@" REALPATH)
56if(_realCurr STREQUAL _realOrig)
57  set(PACKAGE_PREFIX_DIR "@installPrefix@")
58endif()
59unset(_realOrig)
60unset(_realCurr)
61'''
62PACKAGE_INIT_SET_AND_CHECK = '''
63macro(set_and_check _var _file)
64  set(${_var} "${_file}")
65  if(NOT EXISTS "${_file}")
66    message(FATAL_ERROR "File or directory ${_file} referenced by variable ${_var} does not exist !")
67  endif()
68endmacro()
69
70####################################################################################
71'''
72
73class CMakeSubprojectHolder(InterpreterObject, ObjectHolder):
74    def __init__(self, subp, pv):
75        assert(isinstance(subp, SubprojectHolder))
76        assert(hasattr(subp, 'cm_interpreter'))
77        InterpreterObject.__init__(self)
78        ObjectHolder.__init__(self, subp, pv)
79        self.methods.update({'get_variable': self.get_variable,
80                             'dependency': self.dependency,
81                             'include_directories': self.include_directories,
82                             'target': self.target,
83                             'target_type': self.target_type,
84                             'target_list': self.target_list,
85                             'found': self.found_method,
86                             })
87
88    def _args_to_info(self, args):
89        if len(args) != 1:
90            raise InterpreterException('Exactly one argument is required.')
91
92        tgt = args[0]
93        res = self.held_object.cm_interpreter.target_info(tgt)
94        if res is None:
95            raise InterpreterException('The CMake target {} does not exist\n'.format(tgt) +
96                                       '  Use the following command in your meson.build to list all available targets:\n\n' +
97                                       '    message(\'CMaket targets:\\n - \' + \'\\n - \'.join(<cmake_subproject>.target_list()))')
98
99        # Make sure that all keys are present (if not this is a bug)
100        assert(all([x in res for x in ['inc', 'src', 'dep', 'tgt', 'func']]))
101        return res
102
103    @noKwargs
104    @stringArgs
105    def get_variable(self, args, kwargs):
106        return self.held_object.get_variable_method(args, kwargs)
107
108    @noKwargs
109    @stringArgs
110    def dependency(self, args, kwargs):
111        info = self._args_to_info(args)
112        return self.get_variable([info['dep']], kwargs)
113
114    @noKwargs
115    @stringArgs
116    def include_directories(self, args, kwargs):
117        info = self._args_to_info(args)
118        return self.get_variable([info['inc']], kwargs)
119
120    @noKwargs
121    @stringArgs
122    def target(self, args, kwargs):
123        info = self._args_to_info(args)
124        return self.get_variable([info['tgt']], kwargs)
125
126    @noKwargs
127    @stringArgs
128    def target_type(self, args, kwargs):
129        info = self._args_to_info(args)
130        return info['func']
131
132    @noPosargs
133    @noKwargs
134    def target_list(self, args, kwargs):
135        return self.held_object.cm_interpreter.target_list()
136
137    @noPosargs
138    @noKwargs
139    @FeatureNew('CMakeSubproject.found()', '0.53.2')
140    def found_method(self, args, kwargs):
141        return self.held_object is not None
142
143
144class CMakeSubprojectOptions(InterpreterObject):
145    def __init__(self) -> None:
146        super().__init__()
147        self.cmake_options = []  # type: T.List[str]
148        self.target_options = TargetOptions()
149
150        self.methods.update(
151            {
152                'add_cmake_defines': self.add_cmake_defines,
153                'set_override_option': self.set_override_option,
154                'set_install': self.set_install,
155                'append_compile_args': self.append_compile_args,
156                'append_link_args': self.append_link_args,
157                'clear': self.clear,
158            }
159        )
160
161    def _get_opts(self, kwargs: dict) -> SingleTargetOptions:
162        if 'target' in kwargs:
163            return self.target_options[kwargs['target']]
164        return self.target_options.global_options
165
166    @noKwargs
167    def add_cmake_defines(self, args, kwargs) -> None:
168        self.cmake_options += cmake_defines_to_args(args)
169
170    @stringArgs
171    @permittedKwargs({'target'})
172    def set_override_option(self, args, kwargs) -> None:
173        if len(args) != 2:
174            raise InvalidArguments('set_override_option takes exactly 2 positional arguments')
175        self._get_opts(kwargs).set_opt(args[0], args[1])
176
177    @permittedKwargs({'target'})
178    def set_install(self, args, kwargs) -> None:
179        if len(args) != 1 or not isinstance(args[0], bool):
180            raise InvalidArguments('set_install takes exactly 1 boolean argument')
181        self._get_opts(kwargs).set_install(args[0])
182
183    @stringArgs
184    @permittedKwargs({'target'})
185    def append_compile_args(self, args, kwargs) -> None:
186        if len(args) < 2:
187            raise InvalidArguments('append_compile_args takes at least 2 positional arguments')
188        self._get_opts(kwargs).append_args(args[0], args[1:])
189
190    @stringArgs
191    @permittedKwargs({'target'})
192    def append_link_args(self, args, kwargs) -> None:
193        if not args:
194            raise InvalidArguments('append_link_args takes at least 1 positional argument')
195        self._get_opts(kwargs).append_link_args(args)
196
197    @noPosargs
198    @noKwargs
199    def clear(self, args, kwargs) -> None:
200        self.cmake_options.clear()
201        self.target_options = TargetOptions()
202
203
204class CmakeModule(ExtensionModule):
205    cmake_detected = False
206    cmake_root = None
207
208    def __init__(self, interpreter):
209        super().__init__(interpreter)
210        self.snippets.add('configure_package_config_file')
211        self.snippets.add('subproject')
212
213    def detect_voidp_size(self, env):
214        compilers = env.coredata.compilers.host
215        compiler = compilers.get('c', None)
216        if not compiler:
217            compiler = compilers.get('cpp', None)
218
219        if not compiler:
220            raise mesonlib.MesonException('Requires a C or C++ compiler to compute sizeof(void *).')
221
222        return compiler.sizeof('void *', '', env)
223
224    def detect_cmake(self):
225        if self.cmake_detected:
226            return True
227
228        cmakebin = dependencies.ExternalProgram('cmake', silent=False)
229        p, stdout, stderr = mesonlib.Popen_safe(cmakebin.get_command() + ['--system-information', '-G', 'Ninja'])[0:3]
230        if p.returncode != 0:
231            mlog.log('error retrieving cmake information: returnCode={0} stdout={1} stderr={2}'.format(p.returncode, stdout, stderr))
232            return False
233
234        match = re.search('\nCMAKE_ROOT \\"([^"]+)"\n', stdout.strip())
235        if not match:
236            mlog.log('unable to determine cmake root')
237            return False
238
239        cmakePath = pathlib.PurePath(match.group(1))
240        self.cmake_root = os.path.join(*cmakePath.parts)
241        self.cmake_detected = True
242        return True
243
244    @permittedKwargs({'version', 'name', 'compatibility', 'install_dir'})
245    def write_basic_package_version_file(self, state, _args, kwargs):
246        version = kwargs.get('version', None)
247        if not isinstance(version, str):
248            raise mesonlib.MesonException('Version must be specified.')
249
250        name = kwargs.get('name', None)
251        if not isinstance(name, str):
252            raise mesonlib.MesonException('Name not specified.')
253
254        compatibility = kwargs.get('compatibility', 'AnyNewerVersion')
255        if not isinstance(compatibility, str):
256            raise mesonlib.MesonException('compatibility is not string.')
257        if compatibility not in COMPATIBILITIES:
258            raise mesonlib.MesonException('compatibility must be either AnyNewerVersion, SameMajorVersion or ExactVersion.')
259
260        if not self.detect_cmake():
261            raise mesonlib.MesonException('Unable to find cmake')
262
263        pkgroot = kwargs.get('install_dir', None)
264        if pkgroot is None:
265            pkgroot = os.path.join(state.environment.coredata.get_builtin_option('libdir'), 'cmake', name)
266        if not isinstance(pkgroot, str):
267            raise mesonlib.MesonException('Install_dir must be a string.')
268
269        template_file = os.path.join(self.cmake_root, 'Modules', 'BasicConfigVersion-{}.cmake.in'.format(compatibility))
270        if not os.path.exists(template_file):
271            raise mesonlib.MesonException('your cmake installation doesn\'t support the {} compatibility'.format(compatibility))
272
273        version_file = os.path.join(state.environment.scratch_dir, '{}ConfigVersion.cmake'.format(name))
274
275        conf = {
276            'CVF_VERSION': (version, ''),
277            'CMAKE_SIZEOF_VOID_P': (str(self.detect_voidp_size(state.environment)), '')
278        }
279        mesonlib.do_conf_file(template_file, version_file, conf, 'meson')
280
281        res = build.Data(mesonlib.File(True, state.environment.get_scratch_dir(), version_file), pkgroot)
282        return ModuleReturnValue(res, [res])
283
284    def create_package_file(self, infile, outfile, PACKAGE_RELATIVE_PATH, extra, confdata):
285        package_init = PACKAGE_INIT_BASE.replace('@PACKAGE_RELATIVE_PATH@', PACKAGE_RELATIVE_PATH)
286        package_init = package_init.replace('@inputFileName@', infile)
287        package_init += extra
288        package_init += PACKAGE_INIT_SET_AND_CHECK
289
290        try:
291            with open(infile, "r") as fin:
292                data = fin.readlines()
293        except Exception as e:
294            raise mesonlib.MesonException('Could not read input file %s: %s' % (infile, str(e)))
295
296        result = []
297        regex = re.compile(r'(?:\\\\)+(?=\\?@)|\\@|@([-a-zA-Z0-9_]+)@')
298        for line in data:
299            line = line.replace('@PACKAGE_INIT@', package_init)
300            line, _missing = mesonlib.do_replacement(regex, line, 'meson', confdata)
301
302            result.append(line)
303
304        outfile_tmp = outfile + "~"
305        with open(outfile_tmp, "w", encoding='utf-8') as fout:
306            fout.writelines(result)
307
308        shutil.copymode(infile, outfile_tmp)
309        mesonlib.replace_if_different(outfile, outfile_tmp)
310
311    @permittedKwargs({'input', 'name', 'install_dir', 'configuration'})
312    def configure_package_config_file(self, interpreter, state, args, kwargs):
313        if args:
314            raise mesonlib.MesonException('configure_package_config_file takes only keyword arguments.')
315
316        if 'input' not in kwargs:
317            raise mesonlib.MesonException('configure_package_config_file requires "input" keyword.')
318        inputfile = kwargs['input']
319        if isinstance(inputfile, list):
320            if len(inputfile) != 1:
321                m = "Keyword argument 'input' requires exactly one file"
322                raise mesonlib.MesonException(m)
323            inputfile = inputfile[0]
324        if not isinstance(inputfile, (str, mesonlib.File)):
325            raise mesonlib.MesonException("input must be a string or a file")
326        if isinstance(inputfile, str):
327            inputfile = mesonlib.File.from_source_file(state.environment.source_dir, state.subdir, inputfile)
328
329        ifile_abs = inputfile.absolute_path(state.environment.source_dir, state.environment.build_dir)
330
331        if 'name' not in kwargs:
332            raise mesonlib.MesonException('"name" not specified.')
333        name = kwargs['name']
334
335        (ofile_path, ofile_fname) = os.path.split(os.path.join(state.subdir, '{}Config.cmake'.format(name)))
336        ofile_abs = os.path.join(state.environment.build_dir, ofile_path, ofile_fname)
337
338        install_dir = kwargs.get('install_dir', os.path.join(state.environment.coredata.get_builtin_option('libdir'), 'cmake', name))
339        if not isinstance(install_dir, str):
340            raise mesonlib.MesonException('"install_dir" must be a string.')
341
342        if 'configuration' not in kwargs:
343            raise mesonlib.MesonException('"configuration" not specified.')
344        conf = kwargs['configuration']
345        if not isinstance(conf, ConfigurationDataHolder):
346            raise mesonlib.MesonException('Argument "configuration" is not of type configuration_data')
347
348        prefix = state.environment.coredata.get_builtin_option('prefix')
349        abs_install_dir = install_dir
350        if not os.path.isabs(abs_install_dir):
351            abs_install_dir = os.path.join(prefix, install_dir)
352
353        PACKAGE_RELATIVE_PATH = os.path.relpath(prefix, abs_install_dir)
354        extra = ''
355        if re.match('^(/usr)?/lib(64)?/.+', abs_install_dir):
356            extra = PACKAGE_INIT_EXT.replace('@absInstallDir@', abs_install_dir)
357            extra = extra.replace('@installPrefix@', prefix)
358
359        self.create_package_file(ifile_abs, ofile_abs, PACKAGE_RELATIVE_PATH, extra, conf.held_object)
360        conf.mark_used()
361
362        conffile = os.path.normpath(inputfile.relative_name())
363        if conffile not in interpreter.build_def_files:
364            interpreter.build_def_files.append(conffile)
365
366        res = build.Data(mesonlib.File(True, ofile_path, ofile_fname), install_dir)
367        interpreter.build.data.append(res)
368
369        return res
370
371    @FeatureNew('subproject', '0.51.0')
372    @FeatureNewKwargs('subproject', '0.55.0', ['options'])
373    @FeatureDeprecatedKwargs('subproject', '0.55.0', ['cmake_options'])
374    @permittedKwargs({'cmake_options', 'required', 'options'})
375    @stringArgs
376    def subproject(self, interpreter, state, args, kwargs):
377        if len(args) != 1:
378            raise InterpreterException('Subproject takes exactly one argument')
379        if 'cmake_options' in kwargs and 'options' in kwargs:
380            raise InterpreterException('"options" cannot be used together with "cmake_options"')
381        dirname = args[0]
382        subp = interpreter.do_subproject(dirname, 'cmake', kwargs)
383        if not subp.held_object:
384            return subp
385        return CMakeSubprojectHolder(subp, dirname)
386
387    @FeatureNew('subproject_options', '0.55.0')
388    @noKwargs
389    @noPosargs
390    def subproject_options(self, state, args, kwargs) -> ModuleReturnValue:
391        opts = CMakeSubprojectOptions()
392        return ModuleReturnValue(opts, [])
393
394def initialize(*args, **kwargs):
395    return CmakeModule(*args, **kwargs)
396