-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathcmake.py
281 lines (236 loc) · 8.56 KB
/
cmake.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# Copyright 2016-2018 Dirk Thomas
# Licensed under the Apache License, Version 2.0
import os
from pathlib import Path
import re
import sys
from colcon_core.logging import colcon_logger
from colcon_core.package_identification \
import PackageIdentificationExtensionPoint
from colcon_core.plugin_system import satisfies_version
logger = colcon_logger.getChild(__name__)
class CmakePackageIdentification(PackageIdentificationExtensionPoint):
"""Identify CMake packages with `CMakeLists.txt` files."""
def __init__(self): # noqa: D107
super().__init__()
satisfies_version(
PackageIdentificationExtensionPoint.EXTENSION_POINT_VERSION,
'^1.0')
def identify(self, metadata): # noqa: D102
if metadata.type is not None and metadata.type != 'cmake':
return
cmakelists_txt = metadata.path / 'CMakeLists.txt'
if not cmakelists_txt.is_file():
return
data = extract_data(cmakelists_txt)
if not data['name'] and not metadata.name:
raise RuntimeError(
"Failed to extract project name from '%s'" % cmakelists_txt)
if data['name'] == 'Project':
lines = cmakelists_txt.read_text(errors='replace').splitlines()
if 'catkin_workspace()' in lines:
logger.warning(
"Ignoring '{cmakelists_txt}' since it seems to be a "
"toplevel CMake file generated by 'catkin_make'"
.format_map(locals()))
return
metadata.type = 'cmake'
if metadata.name is None:
metadata.name = data['name']
metadata.dependencies['build'] |= data['depends']
metadata.dependencies['run'] |= data['depends']
def extract_data(cmakelists_txt):
"""
Extract the project name and dependencies from a CMakeLists.txt file.
:param Path cmakelists_txt: The path of the CMakeLists.txt file
:rtype: dict
"""
content = extract_content(cmakelists_txt)
data = {}
data['name'] = extract_project_name(content)
# fall back to use the directory name
if data['name'] is None:
data['name'] = cmakelists_txt.parent.name
# extract dependencies from all CMake files in the project directory
depends_content = content + extract_content(
cmakelists_txt.parent, exclude=[cmakelists_txt])
depends = extract_dependencies(depends_content)
# exclude self references
data['depends'] = depends - {data['name']}
return data
def extract_content(basepath, exclude=None):
"""
Get all non-comment lines from CMake files under the given basepath.
All `CMakeLists.txt` files as well as files ending with `.cmake` are used.
Directories starting with a dot (`.`) are being skipped.
:param Path basepath: The path to recursively crawl
:param list exclude: The paths to exclude
:rtype: str
"""
if basepath.is_file():
content = basepath.read_text(errors='replace')
elif basepath.is_dir():
content = ''
for dirpath, dirnames, filenames in os.walk(str(basepath)):
# skip subdirectories starting with a dot
dirnames[:] = filter(lambda d: not d.startswith('.'), dirnames)
dirnames.sort()
for name in sorted(filenames):
if name != 'CMakeLists.txt' and not name.endswith('.cmake'):
continue
path = Path(dirpath) / name
if path in (exclude or []):
continue
content += path.read_text(errors='replace') + '\n'
else:
return ''
return _remove_cmake_comments(content)
def _remove_cmake_comments(content):
lines = content.splitlines()
for index, line in enumerate(lines):
lines[index] = _remove_cmake_comments_from_line(line)
return '\n'.join(lines)
def _remove_cmake_comments_from_line(line):
# match comments starting with #
# which are not within a string enclosed in double quotes
pattern = (
# strings
'("[^"]*")'
'|'
# comments
'(#.*)'
'|'
# other
'([^#"]*)'
)
modline = ''
for matches in re.findall(pattern, line):
modline += matches[0] + matches[2]
return modline
def extract_project_name(content):
"""
Extract the CMake project name from the CMake code.
The `project()` call must be on a single line and the first argument must
be a literal string for this function to be able to extract the name.
:param str content: The CMake source code
:returns: The project name, otherwise None
:rtype: str
"""
# extract project name
match = re.search(
# case insensitive function name
_get_case_insensitive_pattern('project') +
# optional white space
r'\s*'
# open parenthesis
r'\('
# optional white space
r'\s*'
# optional "opening" quote
'("?)'
# project name
'([a-zA-Z0-9_-]+)'
# optional "closing" quote (only if an "opening" quote was used)
r'\1'
# optional language
r'(\s+[^\)]*)?'
# close parenthesis
r'\)',
content)
if not match:
return None
return match.group(2)
def extract_dependencies(content):
"""
Extract the dependencies from the CMake code.
The `find_package()` and `pkg_check_modules` calls must be on a single line
and the first argument must be a literal string for this function to be
able to extract the dependency name.
:param str content: The CMake source code
:returns: The dependencies name
:rtype: list
"""
return \
extract_find_package_calls(content) | \
_extract_pkg_config_calls(content)
def extract_find_package_calls(content, *, function_name='find_package'):
"""
Extract `find_package()`-like calls from the CMake code.
The function call must be on a single line and the first argument must be
a literal string for this function to be able to extract it.
:param str content: The CMake source code
:returns: The first arguments of the functions (in the case of
`find_package()` these are the package names)
:rtype: set
"""
matches = re.findall(
# case insensitive function name
_get_case_insensitive_pattern(function_name) +
# optional white space
r'\s*'
# open parenthesis
r'\('
# optional white space
r'\s*'
# optional "opening" quote
'("?)'
# package name
'([a-zA-Z0-9_-]+)'
# optional "closing" quote (only if an "opening" quote was used)
r'\1'
# white space
r'(\s+'
# optional arguments
r'[^\)]*)?'
# close parenthesis
r'\)',
content)
return {m[1] for m in matches}
def _extract_pkg_config_calls(content):
pattern1 = _get_case_insensitive_pattern('pkg_check_modules')
pattern2 = _get_case_insensitive_pattern('pkg_search_module')
function_names_pattern = '(?:{pattern1}|{pattern2})'.format_map(locals())
matches = re.findall(
# case insensitive function names
function_names_pattern +
# optional white space
r'\s*'
# open parenthesis
r'\('
# optional white space
r'\s*'
# optional "opening" quote
'("?)'
# prefix
'[a-zA-Z0-9_]+'
# optional "closing" quote (only if an "opening" quote was used)
r'\1'
# optional options prefixed by white space
r'(?:\s+(?:REQUIRED|QUIET|NO_CMAKE_PATH|NO_CMAKE_ENVIRONMENT_PATH))*'
# package names prefixed by white space with opt. trailing white space
'([^)]+)'
# close parenthesis
r'\)',
content)
names = set()
for modules in [m[1].strip() for m in matches]:
# split multiple modules
for module in modules.split():
# remove optional version suffix
for char in ('>', '=', '<'):
if char in module:
module = module[:module.index(char)]
names.add(module)
return names
def _get_case_insensitive_pattern(value):
# non-capturing case insensitive pattern for a string literal
if sys.version_info[:2] < (3, 6):
# match each character separately with arbitrary case
pattern = ''
for char in value:
if char.lower() != char.upper():
pattern += '[' + char.lower() + char.upper() + ']'
else:
pattern += char
return pattern
return '(?i:{value})'.format_map(locals())