Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
benyissa committed Nov 21, 2023
1 parent ee7ebfb commit 93ad35d
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 62 deletions.
65 changes: 3 additions & 62 deletions agent/exploits/__init__.py
Original file line number Diff line number Diff line change
@@ -1,63 +1,4 @@
"""Exploits importer"""
import logging
import sys
import traceback
import os
import pkgutil
from typing import Callable
"""Importer module."""
from agent import importer

logger = logging.getLogger(__name__)


def _importer_for(path: str, prefix: str) -> Callable[[], None]:
"""
Creates a function for importing all Python files in a specified folder and adding them as attributes
to a given module.
Args:
path (str): the path to the folder containing the Python files to import
prefix (str): the prefix to use when adding the imported files as attributes to the module
Returns:
A function that can be called to perform the import and attribute assignment.
The function takes two optional arguments:
- file_path (str): the path to the folder containing the Python files to import (default is `path`)
- stop_on_error (bool): whether to stop execution if an error occurs during import (default is `True`)
"""

def _import_all_files(file_path: str = path, stop_on_error: bool = True) -> None:
"""
Imports all Python files in a specified folder and adds them as attributes to a given module.
Args:
file_path (str): the path to the folder containing the Python files to import
(default is the value passed to `_importer_for`)
stop_on_error (bool): whether to stop execution if an error occurs during import (default is `True`)
"""
folder = os.path.dirname(file_path)
module = sys.modules[prefix]

for importer, name, _ in pkgutil.iter_modules([folder]):
abs_name = prefix + "." + name

if abs_name in sys.modules:
continue

loader = importer.find_module(abs_name) # type: ignore[call-arg]
sub_mod = None
try:
if loader is not None:
sub_mod = loader.load_module(abs_name)
except ImportError as e:
if stop_on_error:
raise
# Print the full traceback for debugging purposes.
traceback.print_exc()
logger.warning("Cannot load REbus plugin [%s]. Root cause: %s", name, e)
else:
setattr(module, name, sub_mod)

return _import_all_files


import_all = _importer_for(__file__, __name__)
import_all = importer.importer_for(__file__, __name__)
53 changes: 53 additions & 0 deletions agent/importer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
"""Dynamic importer to enable registry pattern."""
import logging
import sys
import traceback
import os
import pkgutil
from typing import Callable

logger = logging.getLogger(__name__)


def importer_for(path: str, prefix: str) -> Callable[[], None]:
"""
Creates a function for importing all Python files in a specified folder and adding them as attributes
to a given module.
Args:
path (str): the path to the folder containing the Python files to import
prefix (str): the prefix to use when adding the imported files as attributes to the module
Returns:
A function that can be called to perform the import and attribute assignment. The function takes two
optional arguments:
- file_path (str): the path to the folder containing the Python files to import (default is `path`)
- stop_on_error (bool): whether to stop execution if an error occurs during import (default is `True`)
"""

def import_all(path: str = path, stop_on_error: bool = True) -> None:
"""
Imports all Python files in a specified folder and adds them as attributes to a given module.
Args:
file_path (str): the path to the folder containing the Python files to import
(default is the value passed to `importer_for`)
stop_on_error (bool): whether to stop execution if an error occurs during import (default is `True`)
"""
folder = os.path.dirname(path)
module = sys.modules[prefix]
for importer, name, _ in pkgutil.iter_modules([folder]):
absname = prefix + "." + name
if absname in sys.modules:
continue
loader = importer.find_module(absname) # type: ignore[call-arg]
try:
if loader is not None:
submod = loader.load_module(absname)
except ImportError as e:
if stop_on_error:
raise
# This is for debugging to print the full trace and pinpoint to source of the exception.
traceback.print_exc()
logger.warning("Cannot load REbus plugin [%s]. Root cause: %s", name, e)
else:
setattr(module, name, submod)

return import_all

0 comments on commit 93ad35d

Please sign in to comment.