| 1 |
# SPDX-License-Identifier: Apache-2.0 |
| 2 |
# Copyright 2019 The Meson development team |
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
from .common import CMakeException, CMakeBuildFile, CMakeConfiguration |
| 7 |
import typing as T |
| 8 |
from .. import mlog |
| 9 |
from pathlib import Path |
| 10 |
import json |
| 11 |
import re |
| 12 |
|
| 13 |
STRIP_KEYS = ['cmake', 'reply', 'backtrace', 'backtraceGraph', 'version'] |
| 14 |
|
| 15 |
class CMakeFileAPI: |
| 16 |
def __init__(self, build_dir: Path): |
| 17 |
self.build_dir = build_dir |
| 18 |
self.api_base_dir = self.build_dir / '.cmake' / 'api' / 'v1' |
| 19 |
self.request_dir = self.api_base_dir / 'query' / 'client-meson' |
| 20 |
self.reply_dir = self.api_base_dir / 'reply' |
| 21 |
self.cmake_sources: T.List[CMakeBuildFile] = [] |
| 22 |
self.cmake_configurations: T.List[CMakeConfiguration] = [] |
| 23 |
self.project_version = '' |
| 24 |
self.kind_resolver_map = { |
| 25 |
'codemodel': self._parse_codemodel, |
| 26 |
'cache': self._parse_cache, |
| 27 |
'cmakeFiles': self._parse_cmakeFiles, |
| 28 |
} |
| 29 |
|
| 30 |
def get_cmake_sources(self) -> T.List[CMakeBuildFile]: |
| 31 |
return self.cmake_sources |
| 32 |
|
| 33 |
def get_cmake_configurations(self) -> T.List[CMakeConfiguration]: |
| 34 |
return self.cmake_configurations |
| 35 |
|
| 36 |
def get_project_version(self) -> str: |
| 37 |
return self.project_version |
| 38 |
|
| 39 |
def setup_request(self) -> None: |
| 40 |
self.request_dir.mkdir(parents=True, exist_ok=True) |
| 41 |
|
| 42 |
query = { |
| 43 |
'requests': [ |
| 44 |
{'kind': 'codemodel', 'version': {'major': 2, 'minor': 0}}, |
| 45 |
{'kind': 'cache', 'version': {'major': 2, 'minor': 0}}, |
| 46 |
{'kind': 'cmakeFiles', 'version': {'major': 1, 'minor': 0}}, |
| 47 |
] |
| 48 |
} |
| 49 |
|
| 50 |
query_file = self.request_dir / 'query.json' |
| 51 |
query_file.write_text(json.dumps(query, indent=2), encoding='utf-8') |
| 52 |
|
| 53 |
def load_reply(self) -> None: |
| 54 |
if not self.reply_dir.is_dir(): |
| 55 |
raise CMakeException('No response from the CMake file API') |
| 56 |
|
| 57 |
root = None |
| 58 |
reg_index = re.compile(r'^index-.*\.json$') |
| 59 |
for i in self.reply_dir.iterdir(): |
| 60 |
if reg_index.match(i.name): |
| 61 |
root = i |
| 62 |
break |
| 63 |
|
| 64 |
if not root: |
| 65 |
raise CMakeException('Failed to find the CMake file API index') |
| 66 |
|
| 67 |
index = self._reply_file_content(root) # Load the root index |
| 68 |
index = self._strip_data(index) # Avoid loading duplicate files |
| 69 |
index = self._resolve_references(index) # Load everything |
| 70 |
index = self._strip_data(index) # Strip unused data (again for loaded files) |
| 71 |
|
| 72 |
# Debug output |
| 73 |
debug_json = self.build_dir / '..' / 'fileAPI.json' |
| 74 |
debug_json = debug_json.resolve() |
| 75 |
debug_json.write_text(json.dumps(index, indent=2), encoding='utf-8') |
| 76 |
mlog.cmd_ci_include(debug_json.as_posix()) |
| 77 |
|
| 78 |
# parse the JSON |
| 79 |
for i in index['objects']: |
| 80 |
assert isinstance(i, dict) |
| 81 |
assert 'kind' in i |
| 82 |
assert i['kind'] in self.kind_resolver_map |
| 83 |
|
| 84 |
self.kind_resolver_map[i['kind']](i) |
| 85 |
|
| 86 |
def _parse_codemodel(self, data: T.Dict[str, T.Any]) -> None: |
| 87 |
assert 'configurations' in data |
| 88 |
assert 'paths' in data |
| 89 |
|
| 90 |
source_dir = data['paths']['source'] |
| 91 |
build_dir = data['paths']['build'] |
| 92 |
|
| 93 |
# The file API output differs quite a bit from the server |
| 94 |
# output. It is more flat than the server output and makes |
| 95 |
# heavy use of references. Here these references are |
| 96 |
# resolved and the resulting data structure is identical |
| 97 |
# to the CMake serve output. |
| 98 |
|
| 99 |
def helper_parse_dir(dir_entry: T.Dict[str, T.Any]) -> T.Tuple[Path, Path]: |
| 100 |
src_dir = Path(dir_entry.get('source', '.')) |
| 101 |
bld_dir = Path(dir_entry.get('build', '.')) |
| 102 |
src_dir = src_dir if src_dir.is_absolute() else source_dir / src_dir |
| 103 |
bld_dir = bld_dir if bld_dir.is_absolute() else build_dir / bld_dir |
| 104 |
src_dir = src_dir.resolve() |
| 105 |
bld_dir = bld_dir.resolve() |
| 106 |
|
| 107 |
return src_dir, bld_dir |
| 108 |
|
| 109 |
def parse_sources(comp_group: T.Dict[str, T.Any], tgt: T.Dict[str, T.Any]) -> T.Tuple[T.List[Path], T.List[Path], T.List[int]]: |
| 110 |
gen = [] |
| 111 |
src = [] |
| 112 |
idx = [] |
| 113 |
|
| 114 |
src_list_raw = tgt.get('sources', []) |
| 115 |
for i in comp_group.get('sourceIndexes', []): |
| 116 |
if i >= len(src_list_raw) or 'path' not in src_list_raw[i]: |
| 117 |
continue |
| 118 |
if src_list_raw[i].get('isGenerated', False): |
| 119 |
gen += [Path(src_list_raw[i]['path'])] |
| 120 |
else: |
| 121 |
src += [Path(src_list_raw[i]['path'])] |
| 122 |
idx += [i] |
| 123 |
|
| 124 |
return src, gen, idx |
| 125 |
|
| 126 |
def parse_target(tgt: T.Dict[str, T.Any]) -> T.Dict[str, T.Any]: |
| 127 |
src_dir, bld_dir = helper_parse_dir(cnf.get('paths', {})) |
| 128 |
|
| 129 |
# Parse install paths (if present) |
| 130 |
install_paths = [] |
| 131 |
if 'install' in tgt: |
| 132 |
prefix = Path(tgt['install']['prefix']['path']) |
| 133 |
install_paths = [prefix / x['path'] for x in tgt['install']['destinations']] |
| 134 |
install_paths = list(set(install_paths)) |
| 135 |
|
| 136 |
# On the first look, it looks really nice that the CMake devs have |
| 137 |
# decided to use arrays for the linker flags. However, this feeling |
| 138 |
# soon turns into despair when you realize that there only one entry |
| 139 |
# per type in most cases, and we still have to do manual string splitting. |
| 140 |
link_flags = [] |
| 141 |
link_libs = [] |
| 142 |
for i in tgt.get('link', {}).get('commandFragments', []): |
| 143 |
if i['role'] == 'flags': |
| 144 |
link_flags += [i['fragment']] |
| 145 |
elif i['role'] == 'libraries': |
| 146 |
link_libs += [i['fragment']] |
| 147 |
elif i['role'] == 'libraryPath': |
| 148 |
link_flags += ['-L{}'.format(i['fragment'])] |
| 149 |
elif i['role'] == 'frameworkPath': |
| 150 |
link_flags += ['-F{}'.format(i['fragment'])] |
| 151 |
for i in tgt.get('archive', {}).get('commandFragments', []): |
| 152 |
if i['role'] == 'flags': |
| 153 |
link_flags += [i['fragment']] |
| 154 |
|
| 155 |
# TODO The `dependencies` entry is new in the file API. |
| 156 |
# maybe we can make use of that in addition to the |
| 157 |
# implicit dependency detection |
| 158 |
tgt_data = { |
| 159 |
'artifacts': [Path(x.get('path', '')) for x in tgt.get('artifacts', [])], |
| 160 |
'sourceDirectory': src_dir, |
| 161 |
'buildDirectory': bld_dir, |
| 162 |
'name': tgt.get('name', ''), |
| 163 |
'fullName': tgt.get('nameOnDisk', ''), |
| 164 |
'hasInstallRule': 'install' in tgt, |
| 165 |
'installPaths': install_paths, |
| 166 |
'linkerLanguage': tgt.get('link', {}).get('language', 'CXX'), |
| 167 |
'linkLibraries': ' '.join(link_libs), # See previous comment block why we join the array |
| 168 |
'linkFlags': ' '.join(link_flags), # See previous comment block why we join the array |
| 169 |
'type': tgt.get('type', 'EXECUTABLE'), |
| 170 |
'fileGroups': [], |
| 171 |
} |
| 172 |
|
| 173 |
processed_src_idx = [] |
| 174 |
for cg in tgt.get('compileGroups', []): |
| 175 |
# Again, why an array, when there is usually only one element |
| 176 |
# and arguments are separated with spaces... |
| 177 |
flags = [] |
| 178 |
for i in cg.get('compileCommandFragments', []): |
| 179 |
flags += [i['fragment']] |
| 180 |
|
| 181 |
cg_data = { |
| 182 |
'defines': [x.get('define', '') for x in cg.get('defines', [])], |
| 183 |
'compileFlags': ' '.join(flags), |
| 184 |
'language': cg.get('language', 'C'), |
| 185 |
'isGenerated': None, # Set later, flag is stored per source file |
| 186 |
'sources': [], |
| 187 |
'includePath': cg.get('includes', []), |
| 188 |
} |
| 189 |
|
| 190 |
normal_src, generated_src, src_idx = parse_sources(cg, tgt) |
| 191 |
if normal_src: |
| 192 |
cg_data = dict(cg_data) |
| 193 |
cg_data['isGenerated'] = False |
| 194 |
cg_data['sources'] = normal_src |
| 195 |
tgt_data['fileGroups'] += [cg_data] |
| 196 |
if generated_src: |
| 197 |
cg_data = dict(cg_data) |
| 198 |
cg_data['isGenerated'] = True |
| 199 |
cg_data['sources'] = generated_src |
| 200 |
tgt_data['fileGroups'] += [cg_data] |
| 201 |
processed_src_idx += src_idx |
| 202 |
|
| 203 |
# Object libraries have no compile groups, only source groups. |
| 204 |
# So we add all the source files to a dummy source group that were |
| 205 |
# not found in the previous loop |
| 206 |
normal_src = [] |
| 207 |
generated_src = [] |
| 208 |
for idx, src in enumerate(tgt.get('sources', [])): |
| 209 |
if idx in processed_src_idx: |
| 210 |
continue |
| 211 |
|
| 212 |
if src.get('isGenerated', False): |
| 213 |
generated_src += [src['path']] |
| 214 |
else: |
| 215 |
normal_src += [src['path']] |
| 216 |
|
| 217 |
if normal_src: |
| 218 |
tgt_data['fileGroups'] += [{ |
| 219 |
'isGenerated': False, |
| 220 |
'sources': normal_src, |
| 221 |
}] |
| 222 |
if generated_src: |
| 223 |
tgt_data['fileGroups'] += [{ |
| 224 |
'isGenerated': True, |
| 225 |
'sources': generated_src, |
| 226 |
}] |
| 227 |
return tgt_data |
| 228 |
|
| 229 |
def parse_project(pro: T.Dict[str, T.Any]) -> T.Dict[str, T.Any]: |
| 230 |
# Only look at the first directory specified in directoryIndexes |
| 231 |
# TODO Figure out what the other indexes are there for |
| 232 |
p_src_dir = source_dir |
| 233 |
p_bld_dir = build_dir |
| 234 |
try: |
| 235 |
p_src_dir, p_bld_dir = helper_parse_dir(cnf['directories'][pro['directoryIndexes'][0]]) |
| 236 |
except (IndexError, KeyError): |
| 237 |
pass |
| 238 |
|
| 239 |
pro_data = { |
| 240 |
'name': pro.get('name', ''), |
| 241 |
'sourceDirectory': p_src_dir, |
| 242 |
'buildDirectory': p_bld_dir, |
| 243 |
'targets': [], |
| 244 |
} |
| 245 |
|
| 246 |
for ref in pro.get('targetIndexes', []): |
| 247 |
tgt = {} |
| 248 |
try: |
| 249 |
tgt = cnf['targets'][ref] |
| 250 |
except (IndexError, KeyError): |
| 251 |
pass |
| 252 |
pro_data['targets'] += [parse_target(tgt)] |
| 253 |
|
| 254 |
return pro_data |
| 255 |
|
| 256 |
for cnf in data.get('configurations', []): |
| 257 |
cnf_data = { |
| 258 |
'name': cnf.get('name', ''), |
| 259 |
'projects': [], |
| 260 |
} |
| 261 |
|
| 262 |
for pro in cnf.get('projects', []): |
| 263 |
cnf_data['projects'] += [parse_project(pro)] |
| 264 |
|
| 265 |
self.cmake_configurations += [CMakeConfiguration(cnf_data)] |
| 266 |
|
| 267 |
def _parse_cmakeFiles(self, data: T.Dict[str, T.Any]) -> None: |
| 268 |
assert 'inputs' in data |
| 269 |
assert 'paths' in data |
| 270 |
|
| 271 |
src_dir = Path(data['paths']['source']) |
| 272 |
|
| 273 |
for i in data['inputs']: |
| 274 |
path = Path(i['path']) |
| 275 |
path = path if path.is_absolute() else src_dir / path |
| 276 |
self.cmake_sources += [CMakeBuildFile(path, i.get('isCMake', False), i.get('isGenerated', False))] |
| 277 |
|
| 278 |
def _parse_cache(self, data: T.Dict[str, T.Any]) -> None: |
| 279 |
assert 'entries' in data |
| 280 |
|
| 281 |
for e in data['entries']: |
| 282 |
if e['name'] == 'CMAKE_PROJECT_VERSION': |
| 283 |
self.project_version = e['value'] |
| 284 |
|
| 285 |
def _strip_data(self, data: T.Any) -> T.Any: |
| 286 |
if isinstance(data, list): |
| 287 |
for idx, i in enumerate(data): |
| 288 |
data[idx] = self._strip_data(i) |
| 289 |
|
| 290 |
elif isinstance(data, dict): |
| 291 |
new = {} |
| 292 |
for key, val in data.items(): |
| 293 |
if key not in STRIP_KEYS: |
| 294 |
new[key] = self._strip_data(val) |
| 295 |
data = new |
| 296 |
|
| 297 |
return data |
| 298 |
|
| 299 |
def _resolve_references(self, data: T.Any) -> T.Any: |
| 300 |
if isinstance(data, list): |
| 301 |
for idx, i in enumerate(data): |
| 302 |
data[idx] = self._resolve_references(i) |
| 303 |
|
| 304 |
elif isinstance(data, dict): |
| 305 |
# Check for the "magic" reference entry and insert |
| 306 |
# it into the root data dict |
| 307 |
if 'jsonFile' in data: |
| 308 |
data.update(self._reply_file_content(data['jsonFile'])) |
| 309 |
|
| 310 |
for key, val in data.items(): |
| 311 |
data[key] = self._resolve_references(val) |
| 312 |
|
| 313 |
return data |
| 314 |
|
| 315 |
def _reply_file_content(self, filename: Path) -> T.Dict[str, T.Any]: |
| 316 |
real_path = self.reply_dir / filename |
| 317 |
if not real_path.exists(): |
| 318 |
raise CMakeException(f'File "{real_path}" does not exist') |
| 319 |
|
| 320 |
data = json.loads(real_path.read_text(encoding='utf-8')) |
| 321 |
assert isinstance(data, dict) |
| 322 |
for i in data.keys(): |
| 323 |
assert isinstance(i, str) |
| 324 |
return data |