Debian Codegraph @

utils/dependencies.py

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