File: parser_factory.py

package info (click to toggle)
mat2 0.14.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 12,376 kB
  • sloc: python: 3,772; makefile: 7
file content (64 lines) | stat: -rw-r--r-- 2,112 bytes parent folder | download | duplicates (2)
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import glob
import os
import mimetypes
import importlib
from typing import TypeVar, Optional, List, Tuple

from . import abstract, UNSUPPORTED_EXTENSIONS

T = TypeVar('T', bound='abstract.AbstractParser')

mimetypes.add_type('application/epub+zip', '.epub')
mimetypes.add_type('application/x-dtbncx+xml', '.ncx')  # EPUB Navigation Control XML File

# This should be removed after we move to python3.10
# https://github.com/python/cpython/commit/20a5b7e986377bdfd929d7e8c4e3db5847dfdb2d
mimetypes.add_type('image/heic', '.heic')


def __load_all_parsers():
    """ Loads every parser in a dynamic way """
    current_dir = os.path.dirname(__file__)
    for fname in glob.glob(os.path.join(current_dir, '*.py')):
        if fname.endswith('abstract.py'):
            continue
        elif fname.endswith('__init__.py'):
            continue
        elif fname.endswith('exiftool.py'):
            continue
        basename = os.path.basename(fname)
        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) -> Tuple[Optional[T], Optional[str]]:
    """ Return the appropriate parser for a given filename.

        :raises ValueError: Raised if the instantiation of the parser went wrong.
    """
    mtype, _ = mimetypes.guess_type(filename)

    _, extension = os.path.splitext(filename)
    if extension.lower() in UNSUPPORTED_EXTENSIONS:
        return None, mtype

    if mtype == 'application/x-tar':
        if extension[1:] in ('bz2', 'gz', 'xz'):
            mtype = mtype + '+' + extension[1:]

    for parser_class in _get_parsers():  # type: ignore
        if mtype in parser_class.mimetypes:
            # This instantiation might raise a ValueError on malformed files
            return parser_class(filename), mtype
    return None, mtype