aboutsummaryrefslogtreecommitdiffstats
path: root/bsfs/namespace/namespace.py
blob: 8080f5de808f4fb3420e9f9aa134f5d611f85a0d (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
"""

Part of the BlackStar filesystem (bsfs) module.
A copy of the license is provided with the project.
Author: Matthias Baumgartner, 2022
"""
# imports
import typing

# bsfs imports
from bsfs.utils import URI, typename

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


## code ##

class Namespace():
    """A namespace consists of a common prefix that is used in a set of URIs.

    Note that the prefix must include the separator between
    path and fragment (typically a '#' or a '/').
    """

    # namespace prefix.
    prefix: URI

    def __init__(self, prefix: URI):
        self.prefix = URI(prefix)

    def __eq__(self, other: typing.Any) -> bool:
        return isinstance(other, type(self)) and self.prefix == other.prefix

    def __hash__(self) -> int:
        return hash((type(self), self.prefix))

    def __str__(self) -> str:
        return f'{typename(self)}({self.prefix})'

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

    def __getattr__(self, fragment: str) -> URI:
        """Return prefix + fragment."""
        return URI(self.prefix + fragment)

    def __getitem__(self, fragment: str) -> URI:
        """Alias for getattr(self, fragment)."""
        return self.__getattr__(fragment)


class ClosedNamespace(Namespace):
    """Namespace that covers a restricted set of URIs."""

    # set of permissible fragments.
    fragments: typing.Set[str]

    def __init__(self, prefix: URI, *args: str):
        super().__init__(prefix)
        self.fragments = set(args)

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

    def __hash__(self) -> int:
        return hash((type(self), self.prefix, tuple(sorted(self.fragments))))

    def __getattr__(self, fragment: str) -> URI:
        """Return prefix + fragment.
        Raises a KeyError if the fragment is not allowed in this namespace.
        """
        if fragment not in self.fragments:
            raise KeyError('fragment')
        return super().__getattr__(fragment)

## EOF ##