~kf5jwc/sms-printer

ref: 1f13487e66a7511ddcc612d0fbe9a6d12abb9576 sms-printer/sms_printer/load.py -rw-r--r-- 991 bytes View raw
1f13487e — Kyle Jones Merge branch 'namespaces' 1 year, 5 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import importlib
import pkgutil

from loguru import logger
import sms_printer.parsers as sms_parsers


@logger.catch
def load_parsers(namespace=sms_parsers):

    packages = tuple(pkgutil.iter_modules(namespace.__path__, namespace.__name__ + "."))
    logger.info("Parsers found: {}", len(packages))

    parsers = [importlib.import_module(name) for _, name, _ in packages]
    parsers = tuple(filter(__contains_parser_interface, parsers))

    if len(parsers):
        logger.info("Parsers loaded: {}", len(parsers))
    else:
        logger.warning("No parsers were loaded!")

    return parsers


def __contains_parser_interface(package):
    interface = [callable(getattr(package, func)) for func in ("validate", "parse")]

    if all(interface):
        logger.info("Loaded parser: {}", package.__name__)
    else:
        logger.warning("Could not load parser: {}", package.__name__)
        logger.warning("Parser did not implement the correct interface!")

    return all(interface)