1
0
mirror of synced 2024-11-11 20:08:52 +01:00
mat2/libmat2/parser_factory.py

47 lines
1.4 KiB
Python
Raw Normal View History

import glob
import os
2018-03-19 23:43:49 +01:00
import mimetypes
2018-03-20 01:20:11 +01:00
import importlib
2018-06-04 22:54:01 +02:00
from typing import TypeVar, List, Tuple, Optional
2018-03-19 23:43:49 +01:00
from . import abstract, unsupported_extensions
2018-03-20 01:20:11 +01:00
2018-06-04 22:54:01 +02:00
assert Tuple # make pyflakes happy
2018-04-02 19:11:59 +02:00
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')):
2018-06-10 00:28:26 +02:00
if name.endswith('abstract.py') or name.endswith('__init__.py'):
continue
basename = os.path.basename(name)
name, _ = os.path.splitext(basename)
importlib.import_module('.' + name, package='libmat2')
__load_all_parsers()
2018-06-04 20:29:41 +02:00
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)
2018-06-04 22:54:01 +02:00
def get_parser(filename: str) -> Tuple[Optional[T], Optional[str]]:
2018-05-16 00:08:45 +02:00
mtype, _ = mimetypes.guess_type(filename)
_, extension = os.path.splitext(filename)
if extension in unsupported_extensions:
return None, mtype
for parser_class in _get_parsers(): # type: ignore
if mtype in parser_class.mimetypes:
try:
return parser_class(filename), mtype
except ValueError:
return None, mtype
return None, mtype