| 1 |
"""Analyze python import statements.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import ast |
| 6 |
import os |
| 7 |
import re |
| 8 |
import typing as t |
| 9 |
|
| 10 |
from ..io import ( |
| 11 |
read_binary_file, |
| 12 |
) |
| 13 |
|
| 14 |
from ..util import ( |
| 15 |
display, |
| 16 |
ApplicationError, |
| 17 |
is_subdir, |
| 18 |
) |
| 19 |
|
| 20 |
from ..data import ( |
| 21 |
data_context, |
| 22 |
) |
| 23 |
|
| 24 |
from ..target import ( |
| 25 |
TestTarget, |
| 26 |
) |
| 27 |
|
| 28 |
VIRTUAL_PACKAGES = { |
| 29 |
'ansible.module_utils.six', |
| 30 |
} |
| 31 |
|
| 32 |
|
| 33 |
def get_python_module_utils_imports(compile_targets: list[TestTarget]) -> dict[str, set[str]]: |
| 34 |
"""Return a dictionary of module_utils names mapped to sets of python file paths.""" |
| 35 |
module_utils = enumerate_module_utils() |
| 36 |
|
| 37 |
virtual_utils = set(m for m in module_utils if any(m.startswith('%s.' % v) for v in VIRTUAL_PACKAGES)) |
| 38 |
module_utils -= virtual_utils |
| 39 |
|
| 40 |
imports_by_target_path = {} |
| 41 |
|
| 42 |
for target in compile_targets: |
| 43 |
imports_by_target_path[target.path] = extract_python_module_utils_imports(target.path, module_utils) |
| 44 |
|
| 45 |
def recurse_import(import_name: str, depth: int = 0, seen: t.Optional[set[str]] = None) -> set[str]: |
| 46 |
"""Recursively expand module_utils imports from module_utils files.""" |
| 47 |
display.info('module_utils import: %s%s' % (' ' * depth, import_name), verbosity=4) |
| 48 |
|
| 49 |
if seen is None: |
| 50 |
seen = {import_name} |
| 51 |
|
| 52 |
results = {import_name} |
| 53 |
|
| 54 |
# virtual packages depend on the modules they contain instead of the reverse |
| 55 |
if import_name in VIRTUAL_PACKAGES: |
| 56 |
for sub_import in sorted(virtual_utils): |
| 57 |
if sub_import.startswith('%s.' % import_name): |
| 58 |
if sub_import in seen: |
| 59 |
continue |
| 60 |
|
| 61 |
seen.add(sub_import) |
| 62 |
|
| 63 |
matches = sorted(recurse_import(sub_import, depth + 1, seen)) |
| 64 |
|
| 65 |
for result in matches: |
| 66 |
results.add(result) |
| 67 |
|
| 68 |
import_path = get_import_path(import_name) |
| 69 |
|
| 70 |
if import_path not in imports_by_target_path: |
| 71 |
import_path = get_import_path(import_name, package=True) |
| 72 |
|
| 73 |
if import_path not in imports_by_target_path: |
| 74 |
raise ApplicationError('Cannot determine path for module_utils import: %s' % import_name) |
| 75 |
|
| 76 |
# process imports in reverse so the deepest imports come first |
| 77 |
for name in sorted(imports_by_target_path[import_path], reverse=True): |
| 78 |
if name in virtual_utils: |
| 79 |
continue |
| 80 |
|
| 81 |
if name in seen: |
| 82 |
continue |
| 83 |
|
| 84 |
seen.add(name) |
| 85 |
|
| 86 |
matches = sorted(recurse_import(name, depth + 1, seen)) |
| 87 |
|
| 88 |
for result in matches: |
| 89 |
results.add(result) |
| 90 |
|
| 91 |
return results |
| 92 |
|
| 93 |
for module_util in module_utils: |
| 94 |
# recurse over module_utils imports while excluding self |
| 95 |
module_util_imports = recurse_import(module_util) |
| 96 |
module_util_imports.remove(module_util) |
| 97 |
|
| 98 |
# add recursive imports to all path entries which import this module_util |
| 99 |
for target_path, modules in imports_by_target_path.items(): |
| 100 |
if module_util in modules: |
| 101 |
for module_util_import in sorted(module_util_imports): |
| 102 |
if module_util_import not in modules: |
| 103 |
display.info('%s inherits import %s via %s' % (target_path, module_util_import, module_util), verbosity=6) |
| 104 |
modules.add(module_util_import) |
| 105 |
|
| 106 |
imports: dict[str, set[str]] = {module_util: set() for module_util in module_utils | virtual_utils} |
| 107 |
|
| 108 |
for target_path, modules in imports_by_target_path.items(): |
| 109 |
for module_util in modules: |
| 110 |
imports[module_util].add(target_path) |
| 111 |
|
| 112 |
# for purposes of mapping module_utils to paths, treat imports of virtual utils the same as the parent package |
| 113 |
for virtual_util in virtual_utils: |
| 114 |
parent_package = '.'.join(virtual_util.split('.')[:-1]) |
| 115 |
imports[virtual_util] = imports[parent_package] |
| 116 |
display.info('%s reports imports from parent package %s' % (virtual_util, parent_package), verbosity=6) |
| 117 |
|
| 118 |
for module_util in sorted(imports): |
| 119 |
if not imports[module_util]: |
| 120 |
package_path = get_import_path(module_util, package=True) |
| 121 |
|
| 122 |
if os.path.exists(package_path) and not os.path.getsize(package_path): |
| 123 |
continue # ignore empty __init__.py files |
| 124 |
|
| 125 |
display.warning('No imports found which use the "%s" module_util.' % module_util) |
| 126 |
|
| 127 |
return imports |
| 128 |
|
| 129 |
|
| 130 |
def get_python_module_utils_name(path: str) -> str: |
| 131 |
"""Return a namespace and name from the given module_utils path.""" |
| 132 |
base_path = data_context().content.module_utils_path |
| 133 |
|
| 134 |
if data_context().content.collection: |
| 135 |
prefix = 'ansible_collections.' + data_context().content.collection.prefix + 'plugins.module_utils' |
| 136 |
else: |
| 137 |
prefix = 'ansible.module_utils' |
| 138 |
|
| 139 |
if path.endswith('/__init__.py'): |
| 140 |
path = os.path.dirname(path) |
| 141 |
|
| 142 |
if path == base_path: |
| 143 |
name = prefix |
| 144 |
else: |
| 145 |
name = prefix + '.' + os.path.splitext(os.path.relpath(path, base_path))[0].replace(os.path.sep, '.') |
| 146 |
|
| 147 |
return name |
| 148 |
|
| 149 |
|
| 150 |
def enumerate_module_utils() -> set[str]: |
| 151 |
"""Return a list of available module_utils imports.""" |
| 152 |
module_utils = [] |
| 153 |
|
| 154 |
for path in data_context().content.walk_files(data_context().content.module_utils_path): |
| 155 |
ext = os.path.splitext(path)[1] |
| 156 |
|
| 157 |
if ext != '.py': |
| 158 |
continue |
| 159 |
|
| 160 |
module_utils.append(get_python_module_utils_name(path)) |
| 161 |
|
| 162 |
return set(module_utils) |
| 163 |
|
| 164 |
|
| 165 |
def extract_python_module_utils_imports(path: str, module_utils: set[str]) -> set[str]: |
| 166 |
"""Return a list of module_utils imports found in the specified source file.""" |
| 167 |
# Python code must be read as bytes to avoid a SyntaxError when the source uses comments to declare the file encoding. |
| 168 |
# See: https://www.python.org/dev/peps/pep-0263 |
| 169 |
# Specifically: If a Unicode string with a coding declaration is passed to compile(), a SyntaxError will be raised. |
| 170 |
code = read_binary_file(path) |
| 171 |
|
| 172 |
try: |
| 173 |
tree = ast.parse(code) |
| 174 |
except SyntaxError as ex: |
| 175 |
# Treat this error as a warning so tests can be executed as best as possible. |
| 176 |
# The compile test will detect and report this syntax error. |
| 177 |
display.warning('%s:%s Syntax error extracting module_utils imports: %s' % (path, ex.lineno, ex.msg)) |
| 178 |
return set() |
| 179 |
|
| 180 |
finder = ModuleUtilFinder(path, module_utils) |
| 181 |
finder.visit(tree) |
| 182 |
return finder.imports |
| 183 |
|
| 184 |
|
| 185 |
def get_import_path(name: str, package: bool = False) -> str: |
| 186 |
"""Return a path from an import name.""" |
| 187 |
if package: |
| 188 |
filename = os.path.join(name.replace('.', '/'), '__init__.py') |
| 189 |
else: |
| 190 |
filename = '%s.py' % name.replace('.', '/') |
| 191 |
|
| 192 |
if name.startswith('ansible.module_utils.') or name == 'ansible.module_utils': |
| 193 |
path = os.path.join('lib', filename) |
| 194 |
elif data_context().content.collection and ( |
| 195 |
name.startswith('ansible_collections.%s.plugins.module_utils.' % data_context().content.collection.full_name) or |
| 196 |
name == 'ansible_collections.%s.plugins.module_utils' % data_context().content.collection.full_name): |
| 197 |
path = '/'.join(filename.split('/')[3:]) |
| 198 |
else: |
| 199 |
raise Exception('Unexpected import name: %s' % name) |
| 200 |
|
| 201 |
return path |
| 202 |
|
| 203 |
|
| 204 |
def path_to_module(path: str) -> str: |
| 205 |
"""Convert the given path to a module name.""" |
| 206 |
module = os.path.splitext(path)[0].replace(os.path.sep, '.') |
| 207 |
|
| 208 |
if module.endswith('.__init__'): |
| 209 |
module = module[:-9] |
| 210 |
|
| 211 |
return module |
| 212 |
|
| 213 |
|
| 214 |
def relative_to_absolute(name: str, level: int, module: str, path: str, lineno: int) -> str: |
| 215 |
"""Convert a relative import to an absolute import.""" |
| 216 |
if level <= 0: |
| 217 |
absolute_name = name |
| 218 |
elif not module: |
| 219 |
display.warning('Cannot resolve relative import "%s%s" in unknown module at %s:%d' % ('.' * level, name, path, lineno)) |
| 220 |
absolute_name = 'relative.nomodule' |
| 221 |
else: |
| 222 |
parts = module.split('.') |
| 223 |
|
| 224 |
if path.endswith('/__init__.py'): |
| 225 |
# Ensure the correct relative module is calculated for both not_init.py and __init__.py: |
| 226 |
# a/b/not_init.py -> a.b.not_init # used as-is |
| 227 |
# a/b/__init__.py -> a.b # needs "__init__" part appended to ensure relative imports work |
| 228 |
parts.append('__init__') |
| 229 |
|
| 230 |
if level >= len(parts): |
| 231 |
display.warning('Cannot resolve relative import "%s%s" above module "%s" at %s:%d' % ('.' * level, name, module, path, lineno)) |
| 232 |
absolute_name = 'relative.abovelevel' |
| 233 |
else: |
| 234 |
absolute_name = '.'.join(parts[:-level] + [name]) |
| 235 |
|
| 236 |
return absolute_name |
| 237 |
|
| 238 |
|
| 239 |
class ModuleUtilFinder(ast.NodeVisitor): |
| 240 |
"""AST visitor to find valid module_utils imports.""" |
| 241 |
|
| 242 |
def __init__(self, path: str, module_utils: set[str]) -> None: |
| 243 |
self.path = path |
| 244 |
self.module_utils = module_utils |
| 245 |
self.imports: set[str] = set() |
| 246 |
|
| 247 |
# implicitly import parent package |
| 248 |
|
| 249 |
if path.endswith('/__init__.py'): |
| 250 |
path = os.path.split(path)[0] |
| 251 |
|
| 252 |
if path.startswith('lib/ansible/module_utils/'): |
| 253 |
package = os.path.split(path)[0].replace('/', '.')[4:] |
| 254 |
|
| 255 |
if package != 'ansible.module_utils' and package not in VIRTUAL_PACKAGES: |
| 256 |
self.add_import(package, 0) |
| 257 |
|
| 258 |
self.module = None |
| 259 |
|
| 260 |
if data_context().content.is_ansible: |
| 261 |
# Various parts of the Ansible source tree execute within different modules. |
| 262 |
# To support import analysis, each file which uses relative imports must reside under a path defined here. |
| 263 |
# The mapping is a tuple consisting of a path pattern to match and a replacement path. |
| 264 |
# During analysis, any relative imports not covered here will result in warnings, which can be fixed by adding the appropriate entry. |
| 265 |
path_map = ( |
| 266 |
('^lib/ansible/', 'ansible/'), |
| 267 |
('^test/lib/ansible_test/_util/controller/sanity/validate-modules/', 'validate_modules/'), |
| 268 |
('^test/units/', 'test/units/'), |
| 269 |
('^test/lib/ansible_test/_internal/', 'ansible_test/_internal/'), |
| 270 |
('^test/integration/targets/.*/ansible_collections/(?P<ns>[^/]*)/(?P<col>[^/]*)/', r'ansible_collections/\g<ns>/\g<col>/'), |
| 271 |
('^test/integration/targets/.*/library/', 'ansible/modules/'), |
| 272 |
) |
| 273 |
|
| 274 |
for pattern, replacement in path_map: |
| 275 |
if re.search(pattern, self.path): |
| 276 |
revised_path = re.sub(pattern, replacement, self.path) |
| 277 |
self.module = path_to_module(revised_path) |
| 278 |
break |
| 279 |
else: |
| 280 |
# This assumes that all files within the collection are executed by Ansible as part of the collection. |
| 281 |
# While that will usually be true, there are exceptions which will result in this resolution being incorrect. |
| 282 |
self.module = path_to_module(os.path.join(data_context().content.collection.directory, self.path)) |
| 283 |
|
| 284 |
# pylint: disable=locally-disabled, invalid-name |
| 285 |
def visit_Import(self, node: ast.Import) -> None: |
| 286 |
"""Visit an import node.""" |
| 287 |
self.generic_visit(node) |
| 288 |
|
| 289 |
# import ansible.module_utils.MODULE[.MODULE] |
| 290 |
# import ansible_collections.{ns}.{col}.plugins.module_utils.module_utils.MODULE[.MODULE] |
| 291 |
self.add_imports([alias.name for alias in node.names], node.lineno) |
| 292 |
|
| 293 |
# pylint: disable=locally-disabled, invalid-name |
| 294 |
def visit_ImportFrom(self, node: ast.ImportFrom) -> None: |
| 295 |
"""Visit an import from node.""" |
| 296 |
self.generic_visit(node) |
| 297 |
|
| 298 |
if not node.module: |
| 299 |
return |
| 300 |
|
| 301 |
module = relative_to_absolute(node.module, node.level, self.module, self.path, node.lineno) |
| 302 |
|
| 303 |
if not module.startswith('ansible'): |
| 304 |
return |
| 305 |
|
| 306 |
# from ansible.module_utils import MODULE[, MODULE] |
| 307 |
# from ansible.module_utils.MODULE[.MODULE] import MODULE[, MODULE] |
| 308 |
# from ansible_collections.{ns}.{col}.plugins.module_utils import MODULE[, MODULE] |
| 309 |
# from ansible_collections.{ns}.{col}.plugins.module_utils.MODULE[.MODULE] import MODULE[, MODULE] |
| 310 |
self.add_imports(['%s.%s' % (module, alias.name) for alias in node.names], node.lineno) |
| 311 |
|
| 312 |
def add_import(self, name: str, line_number: int) -> None: |
| 313 |
"""Record the specified import.""" |
| 314 |
import_name = name |
| 315 |
|
| 316 |
while self.is_module_util_name(name): |
| 317 |
if name in self.module_utils: |
| 318 |
if name not in self.imports: |
| 319 |
display.info('%s:%d imports module_utils: %s' % (self.path, line_number, name), verbosity=5) |
| 320 |
self.imports.add(name) |
| 321 |
|
| 322 |
return # duplicate imports are ignored |
| 323 |
|
| 324 |
name = '.'.join(name.split('.')[:-1]) |
| 325 |
|
| 326 |
if is_subdir(self.path, data_context().content.test_path): |
| 327 |
return # invalid imports in tests are ignored |
| 328 |
|
| 329 |
# Treat this error as a warning so tests can be executed as best as possible. |
| 330 |
# This error should be detected by unit or integration tests. |
| 331 |
display.warning('%s:%d Invalid module_utils import: %s' % (self.path, line_number, import_name)) |
| 332 |
|
| 333 |
def add_imports(self, names: list[str], line_no: int) -> None: |
| 334 |
"""Add the given import names if they are module_utils imports.""" |
| 335 |
for name in names: |
| 336 |
if self.is_module_util_name(name): |
| 337 |
self.add_import(name, line_no) |
| 338 |
|
| 339 |
@staticmethod |
| 340 |
def is_module_util_name(name: str) -> bool: |
| 341 |
"""Return True if the given name is a module_util name for the content under test. External module_utils are ignored.""" |
| 342 |
if data_context().content.is_ansible and name.startswith('ansible.module_utils.'): |
| 343 |
return True |
| 344 |
|
| 345 |
if data_context().content.collection and name.startswith('ansible_collections.%s.plugins.module_utils.' % data_context().content.collection.full_name): |
| 346 |
return True |
| 347 |
|
| 348 |
return False |