1
0
mirror of synced 2024-06-18 09:49:38 +02:00
mat2/libmat2/parser_factory.py
jvoisin 4ebf9754f8 Import the dynamic import system
The dynamic import should now work when MAT2 is
installed system-wide, either via the distribution's
packaging system, or via pip.
2018-06-04 20:53:21 +02:00

45 lines
1.3 KiB
Python

import glob
import os
import mimetypes
import importlib
from typing import TypeVar, List
from . import abstract, unsupported_extensions
T = TypeVar('T', bound='abstract.AbstractParser')
def __load_all_parsers():
""" Loads every parser in a dynamic way """
current_dir = os.path.dirname(__file__)
for name in glob.glob(os.path.join(current_dir, '*.py')):
if name in ('abstract.py', '__init__.py'):
continue
basename = os.path.basename(name)
name, _ = os.path.splitext(basename)
importlib.import_module('.' + name, package='libmat2')
__load_all_parsers()
def _get_parsers() -> List[T]:
""" Get all our parsers!"""
def __get_parsers(cls):
return cls.__subclasses__() + \
[g for s in cls.__subclasses__() for g in __get_parsers(s)]
return __get_parsers(abstract.AbstractParser)
def get_parser(filename: str) -> (T, str):
mtype, _ = mimetypes.guess_type(filename)
_, extension = os.path.splitext(filename)
if extension in unsupported_extensions:
return None, mtype
for c in _get_parsers():
if mtype in c.mimetypes:
try:
return c(filename), mtype
except ValueError:
return None, mtype
return None, mtype