aboutsummaryrefslogtreecommitdiffstats
path: root/bsie/extractor/generic/path.py
blob: 7fe157bdb5031c8bdcb256d94f467f6ef52106d2 (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
86
87
88
89
90

# standard imports
import os
import typing

# bsie imports
from bsie.extractor import base
from bsie.matcher import nodes
from bsie.utils import bsfs, ns

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


## code ##

class Path(base.Extractor):
    """Extract information from file's path."""

    CONTENT_READER = 'bsie.reader.path.Path'

    # mapping from predicate to handler function.
    _callmap: typing.Dict[bsfs.schema.Predicate, typing.Callable[[str], typing.Any]]

    def __init__(self):
        super().__init__(bsfs.schema.from_string(base.SCHEMA_PREAMBLE + '''
            bse:dirname rdfs:subClassOf bsfs:Predicate ;
                rdfs:domain bsn:Entity ;
                rdfs:range xsd:string ;
                rdfs:label "File path"^^xsd:string ;
                schema:description "File path in some filesystem."^^xsd:string ;
                bsfs:unique "true"^^xsd:boolean .

            bse:filename rdfs:subClassOf bsfs:Predicate ;
                rdfs:domain bsn:Entity ;
                rdfs:range xsd:string ;
                rdfs:label "File name"^^xsd:string ;
                schema:description "Filename of entity in some filesystem."^^xsd:string ;
                bsfs:unique "true"^^xsd:boolean .
            '''))
        self._callmap = {
            self.schema.predicate(ns.bse.filename): self.__filename,
            self.schema.predicate(ns.bse.dirname): self.__dirname,
            }

    def extract(
            self,
            subject: nodes.Entity,
            content: str,
            principals: typing.Iterable[bsfs.schema.Predicate],
            ) -> typing.Iterator[typing.Tuple[nodes.Node, bsfs.schema.Predicate, typing.Any]]:
        for pred in principals:
            # find callback
            clbk = self._callmap.get(pred)
            if clbk is None:
                continue
            # get value
            value = clbk(content)
            if value is None:
                continue
            # produce triple
            yield subject, pred, value

    def __filename(self, path: str) -> typing.Optional[str]:
        try:
            return os.path.basename(path)
        except Exception: # pylint: disable=broad-except # we explicitly want to catch everything
            # some error, skip
            # FIXME: some kind of error reporting (e.g. logging)?
            # Options: (a) Fail silently (current); (b) Skip and report to log;
            # (c) Raise ExtractorError (aborts extraction); (d) separate content type
            # checks from basename errors (report content type errors, skip basename
            # errors)
            return None

    def __dirname(self, path: str) -> typing.Optional[str]:
        try:
            return os.path.dirname(os.path.abspath(os.path.normpath(path)))
        except Exception: # pylint: disable=broad-except # we explicitly want to catch everything
            # some error, skip
            # FIXME: some kind of error reporting (e.g. logging)?
            # Options: (a) Fail silently (current); (b) Skip and report to log;
            # (c) Raise ExtractorError (aborts extraction); (d) separate content type
            # checks from basename errors (report content type errors, skip basename
            # errors)
            return None

## EOF ##