Skip to content

Commit

Permalink
feat: detect conditional imports
Browse files Browse the repository at this point in the history
  • Loading branch information
gforcada committed Feb 3, 2024
1 parent 9673df6 commit 61c7e0a
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions z3c/dependencychecker/modules.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@

FOLDERS_TO_IGNORE = ("node_modules", "__pycache__", "venv")

HAS_REPORTED_CONDITIONAL_IMPORTS = False

class BaseModule:
def __init__(self, package_path, full_path):
Expand Down Expand Up @@ -117,11 +118,31 @@ def _process_ast_node(self, node):
file_path=self.path,
is_test=self.testing,
)
elif isinstance(node, ast.Try):
if not HAS_REPORTED_CONDITIONAL_IMPORTS:
self._is_a_conditional_import(node)

@staticmethod
def _is_relative_import(import_node):
return import_node.level > 0

def _is_a_conditional_import(self, node):
global HAS_REPORTED_CONDITIONAL_IMPORTS
for handler in node.handlers:
type_info = getattr(handler, 'type', False)
if type_info:
exception_id = getattr(type_info, 'id', False)
if exception_id == 'ImportError':
print('This distribution has conditional imports')
HAS_REPORTED_CONDITIONAL_IMPORTS = True
break

value = getattr(type_info, 'value', False)
if value and value.id == 'pkg_resources' and type_info.attr == 'DistributionNotFound':
print('This distribution has conditional imports')
HAS_REPORTED_CONDITIONAL_IMPORTS = True
break


class ZCMLFile(BaseModule):
"""Extract imports from .zcml files
Expand Down

0 comments on commit 61c7e0a

Please sign in to comment.