1
0
mirror of synced 2024-11-22 09:14:23 +01:00
mat2/libmat2/parser_factory.py
jvoisin 38fae60b8b Rename some files to simplify packaging
- the `src` folder is now `libmat2`
- the `main.py` script is now `mat2.py`
2018-05-18 23:52:40 +02:00

43 lines
1.1 KiB
Python

import os
import mimetypes
import importlib
import pkgutil
from typing import TypeVar
from . import abstract, unsupported_extensions
T = TypeVar('T', bound='abstract.AbstractParser')
# This loads every parser in a dynamic way
for module_loader, name, ispkg in pkgutil.walk_packages('.libmat2'):
if not name.startswith('libmat2.'):
continue
elif name == 'libmat2.abstract':
continue
importlib.import_module(name)
def _get_parsers() -> list:
""" 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