aboutsummaryrefslogtreecommitdiffstats
path: root/bsie/reader/chain.py
blob: 8e900e155db190b47deab438c65e47e590ea9704 (plain)
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
"""

Part of the bsie module.
A copy of the license is provided with the project.
Author: Matthias Baumgartner, 2022
"""
# standard imports
import logging
import typing

# bsie imports
from bsie.utils import bsfs, errors

# inner-module imports
from . import base
from . import builder

# exports
__all__: typing.Sequence[str] = (
    'ReaderChain',
    )


## code ##

logger = logging.getLogger(__name__)

# Content type.
T_CONTENT = typing.TypeVar('T_CONTENT') # pylint: disable=invalid-name

class ReaderChain(base.Reader, typing.Generic[T_CONTENT]):
    """Read an image."""

    # sub-readers for specific file formats.
    _children: typing.Tuple[base.Reader, ...]

    def __init__(
            self,
            subreader_names: typing.Iterable[str],
            cfg: typing.Any,
            ):
        rbuild = builder.ReaderBuilder(cfg)
        children = []
        for name in subreader_names:
            try:
                # build sub-reader
                children.append(rbuild.build(name))
            except (ValueError,
                    TypeError,
                    errors.LoaderError,
                    errors.BuilderError) as err:
                # failed to build a child; skip and notify
                logger.warning('failed to load reader: %s', err)

        if len(children) == 0:
            logger.warning('%s failed to load any sub-readers.', bsfs.typename(self))

        # copy children to member
        self._children = tuple(children)

    def __str__(self) -> str:
        substr = ', '.join(str(child) for child in self._children)
        return f'{bsfs.typename(self)}({substr})'

    def __repr__(self) -> str:
        return f'{bsfs.typename(self)}({self._children})'

    def __eq__(self, other: typing.Any) -> bool:
        return super().__eq__(other) \
           and self._children == other._children

    def __hash__(self) -> int:
        return hash((super().__hash__(), self._children))

    def __call__(self, path: str) -> T_CONTENT:
        for child in self._children:
            try:
                return child(path)
            except errors.ReaderError:
                # child cannot read the file, skip.
                pass

        raise errors.ReaderError(path)

## EOF ##