Debian Codegraph @

utils/dependencies.py

raw
1 # -*- coding: utf-8 -*-
2 """Helper to check for availability and version of dependencies."""
3
4 import configparser
5 import os
6 import re
7
8
9 class DependencyDefinition(object):
10 """Dependency definition.
11
12 Attributes:
13 dpkg_name (str): name of the dpkg package that provides the dependency.
14 is_optional (bool): True if the dependency is optional.
15 l2tbinaries_name (str): name of the l2tbinaries package that provides
16 the dependency.
17 maximum_version (str): maximum supported version, a greater or equal
18 version is not supported.
19 minimum_version (str): minimum supported version, a lesser version is
20 not supported.
21 name (str): name of (the Python module that provides) the dependency.
22 pypi_name (str): name of the PyPI package that provides the dependency.
23 python2_only (bool): True if the dependency is only supported by Python 2.
24 python3_only (bool): True if the dependency is only supported by Python 3.
25 rpm_name (str): name of the rpm package that provides the dependency.
26 skip_check (bool): True if the dependency should be skipped by the
27 CheckDependencies or CheckTestDependencies methods of DependencyHelper.
28 skip_requires (bool): True if the dependency should be excluded from
29 pyproject.toml dependencies.
30 version_property (str): name of the version attribute or function.
31 """
32
33 def __init__(self, name):
34 """Initializes a dependency configuration.
35
36 Args:
37 name (str): name of the dependency.
38 """
39 super(DependencyDefinition, self).__init__()
40 self.dpkg_name = None
41 self.is_optional = False
42 self.l2tbinaries_name = None
43 self.maximum_version = None
44 self.minimum_version = None
45 self.name = name
46 self.pypi_name = None
47 self.python2_only = False
48 self.python3_only = False
49 self.rpm_name = None
50 self.skip_check = None
51 self.skip_requires = None
52 self.version_property = None
53
54
55 class DependencyDefinitionReader(object):
56 """Dependency definition reader."""
57
58 _VALUE_NAMES = frozenset([
59 'dpkg_name',
60 'is_optional',
61 'l2tbinaries_name',
62 'maximum_version',
63 'minimum_version',
64 'pypi_name',
65 'python2_only',
66 'python3_only',
67 'rpm_name',
68 'skip_check',
69 'skip_requires',
70 'version_property'])
71
72 def _GetConfigValue(self, config_parser, section_name, value_name):
73 """Retrieves a value from the config parser.
74
75 Args:
76 config_parser (ConfigParser): configuration parser.
77 section_name (str): name of the section that contains the value.
78 value_name (str): name of the value.
79
80 Returns:
81 object: configuration value or None if the value does not exists.
82 """
83 try:
84 return config_parser.get(section_name, value_name)
85 except configparser.NoOptionError:
86 return None
87
88 def Read(self, file_object):
89 """Reads dependency definitions.
90
91 Args:
92 file_object (file): file-like object to read from.
93
94 Yields:
95 DependencyDefinition: dependency definition.
96 """
97 config_parser = configparser.ConfigParser(interpolation=None)
98 config_parser.read_file(file_object)
99
100 for section_name in config_parser.sections():
101 dependency_definition = DependencyDefinition(section_name)
102 for value_name in self._VALUE_NAMES:
103 value = self._GetConfigValue(config_parser, section_name, value_name)
104 setattr(dependency_definition, value_name, value)
105
106 yield dependency_definition
107
108
109 class DependencyHelper(object):
110 """Dependency helper.
111
112 Attributes:
113 dependencies (dict[str, DependencyDefinition]): dependencies.
114 """
115
116 _VERSION_NUMBERS_REGEX = re.compile(r'[0-9.]+')
117 _VERSION_SPLIT_REGEX = re.compile(r'\.|\-')
118
119 def __init__(
120 self, dependencies_file='dependencies.ini',
121 test_dependencies_file='test_dependencies.ini'):
122 """Initializes a dependency helper.
123
124 Args:
125 dependencies_file (Optional[str]): path to the dependencies configuration
126 file.
127 test_dependencies_file (Optional[str]): path to the test dependencies
128 configuration file.
129 """
130 super(DependencyHelper, self).__init__()
131 self._test_dependencies = {}
132 self.dependencies = {}
133
134 dependency_reader = DependencyDefinitionReader()
135
136 with open(dependencies_file, 'r', encoding='utf-8') as file_object:
137 for dependency in dependency_reader.Read(file_object):
138 self.dependencies[dependency.name] = dependency
139
140 if os.path.exists(test_dependencies_file):
141 with open(test_dependencies_file, 'r', encoding='utf-8') as file_object:
142 for dependency in dependency_reader.Read(file_object):
143 self._test_dependencies[dependency.name] = dependency
144
145 def _CheckPythonModule(self, dependency):
146 """Checks the availability of a Python module.
147
148 Args:
149 dependency (DependencyDefinition): dependency definition.
150
151 Returns:
152 tuple: containing:
153
154 bool: True if the Python module is available and conforms to
155 the minimum required version, False otherwise.
156 str: status message.
157 """
158 module_object = self._ImportPythonModule(dependency.name)
159 if not module_object:
160 return False, f'missing: {dependency.name:s}'
161
162 if not dependency.version_property:
163 return True, dependency.name
164
165 return self._CheckPythonModuleVersion(
166 dependency.name, module_object, dependency.version_property,
167 dependency.minimum_version, dependency.maximum_version)
168
169 def _CheckPythonModuleVersion(
170 self, module_name, module_object, version_property, minimum_version,
171 maximum_version):
172 """Checks the version of a Python module.
173
174 Args:
175 module_object (module): Python module.
176 module_name (str): name of the Python module.
177 version_property (str): version attribute or function.
178 minimum_version (str): minimum version.
179 maximum_version (str): maximum version.
180
181 Returns:
182 tuple: containing:
183
184 bool: True if the Python module is available and conforms to
185 the minimum required version, False otherwise.
186 str: status message.
187 """
188 module_version = None
189 if not version_property.endswith('()'):
190 module_version = getattr(module_object, version_property, None)
191 else:
192 version_method = getattr(
193 module_object, version_property[:-2], None)
194 if version_method:
195 module_version = version_method()
196
197 if not module_version:
198 return False, (
199 f'unable to determine version information for: {module_name:s}')
200
201 # Make sure the module version is a string.
202 module_version = f'{module_version!s}'
203
204 # Split the version string and convert every digit into an integer.
205 # A string compare of both version strings will yield an incorrect result.
206
207 # Strip any semantic suffixes such as a1, b1, pre, post, rc, dev.
208 module_version = self._VERSION_NUMBERS_REGEX.findall(module_version)[0]
209
210 if module_version[-1] == '.':
211 module_version = module_version[:-1]
212
213 try:
214 module_version_map = list(
215 map(int, self._VERSION_SPLIT_REGEX.split(module_version)))
216 except ValueError:
217 return False, (
218 f'unable to parse module version: {module_name:s} {module_version:s}')
219
220 if minimum_version:
221 try:
222 minimum_version_map = list(
223 map(int, self._VERSION_SPLIT_REGEX.split(minimum_version)))
224 except ValueError:
225 return False, (
226 f'unable to parse minimum version: {module_name:s} '
227 f'{minimum_version:s}')
228
229 if module_version_map < minimum_version_map:
230 return False, (
231 f'{module_name:s} version: {module_version!s} is too old, '
232 f'{minimum_version!s} or later required')
233
234 if maximum_version:
235 try:
236 maximum_version_map = list(
237 map(int, self._VERSION_SPLIT_REGEX.split(maximum_version)))
238 except ValueError:
239 return False, (
240 f'unable to parse maximum version: {module_name:s} '
241 f'{maximum_version:s}')
242
243 if module_version_map > maximum_version_map:
244 return False, (
245 f'{module_name:s} version: {module_version!s} is too recent, '
246 f'{maximum_version!s} or earlier required')
247
248 return True, f'{module_name:s} version: {module_version!s}'
249
250 def _ImportPythonModule(self, module_name):
251 """Imports a Python module.
252
253 Args:
254 module_name (str): name of the module.
255
256 Returns:
257 module: Python module or None if the module cannot be imported.
258 """
259 try:
260 module_object = list(map(__import__, [module_name]))[0]
261 except ImportError:
262 return None
263
264 # If the module name contains dots get the upper most module object.
265 if '.' in module_name:
266 for submodule_name in module_name.split('.')[1:]:
267 module_object = getattr(module_object, submodule_name, None)
268
269 return module_object
270
271 def _PrintCheckDependencyStatus(
272 self, dependency, result, status_message, verbose_output=True):
273 """Prints the check dependency status.
274
275 Args:
276 dependency (DependencyDefinition): dependency definition.
277 result (bool): True if the Python module is available and conforms to
278 the minimum required version, False otherwise.
279 status_message (str): status message.
280 verbose_output (Optional[bool]): True if output should be verbose.
281 """
282 if not result or dependency.is_optional:
283 if dependency.is_optional:
284 status_indicator = '[OPTIONAL]'
285 else:
286 status_indicator = '[FAILURE]'
287
288 print(f'{status_indicator:s}\t{status_message:s}')
289
290 elif verbose_output:
291 print(f'[OK]\t\t{status_message:s}')
292
293 def CheckDependencies(self, verbose_output=True):
294 """Checks the availability of the dependencies.
295
296 Args:
297 verbose_output (Optional[bool]): True if output should be verbose.
298
299 Returns:
300 bool: True if the dependencies are available, False otherwise.
301 """
302 print('Checking availability and versions of dependencies.')
303 check_result = True
304
305 for _, dependency in sorted(self.dependencies.items()):
306 if dependency.skip_check:
307 continue
308
309 result, status_message = self._CheckPythonModule(dependency)
310
311 if not result and not dependency.is_optional:
312 check_result = False
313
314 self._PrintCheckDependencyStatus(
315 dependency, result, status_message, verbose_output=verbose_output)
316
317 if check_result and not verbose_output:
318 print('[OK]')
319
320 print('')
321 return check_result
322
323 def CheckTestDependencies(self, verbose_output=True):
324 """Checks the availability of the dependencies when running tests.
325
326 Args:
327 verbose_output (Optional[bool]): True if output should be verbose.
328
329 Returns:
330 bool: True if the dependencies are available, False otherwise.
331 """
332 if not self.CheckDependencies(verbose_output=verbose_output):
333 return False
334
335 print('Checking availability and versions of test dependencies.')
336 check_result = True
337
338 for dependency in sorted(
339 self._test_dependencies.values(),
340 key=lambda dependency: dependency.name):
341 if dependency.skip_check:
342 continue
343
344 result, status_message = self._CheckPythonModule(dependency)
345
346 if not result and not dependency.is_optional:
347 check_result = False
348
349 self._PrintCheckDependencyStatus(
350 dependency, result, status_message, verbose_output=verbose_output)
351
352 if check_result and not verbose_output:
353 print('[OK]')
354
355 print('')
356 return check_result