| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import dataclasses |
| 4 |
import sys |
| 5 |
import typing as t |
| 6 |
|
| 7 |
# pass slots=True on 3.10+ |
| 8 |
# it's not strictly necessary, but it improves performance |
| 9 |
if sys.version_info >= (3, 10): |
| 10 |
_add_dataclass_kwargs: dict[str, bool] = {"slots": True} |
| 11 |
else: |
| 12 |
_add_dataclass_kwargs: dict[str, bool] = {} |
| 13 |
|
| 14 |
|
| 15 |
@dataclasses.dataclass(frozen=True, repr=False, **_add_dataclass_kwargs) |
| 16 |
class Scope: |
| 17 |
""" |
| 18 |
A scope object is a representation of a scope and its dynamic dependencies |
| 19 |
(other scopes). |
| 20 |
|
| 21 |
A scope may be optional (also referred to as "atomically revocable"). |
| 22 |
An optional scope can be revoked without revoking consent for other scopes |
| 23 |
which were granted at the same time. |
| 24 |
|
| 25 |
Scopes are immutable, and provide several evolver methods which produce new |
| 26 |
Scopes. In particular, ``with_dependency`` and ``with_dependencies`` create |
| 27 |
new scopes with added dependencies. |
| 28 |
|
| 29 |
``str(Scope(...))`` produces a valid scope string for use in various methods. |
| 30 |
|
| 31 |
:param scope_string: The string which will be used as the basis for this Scope |
| 32 |
:param optional: The scope may be marked as optional. This means that the scope can |
| 33 |
be declined by the user without declining consent for other scopes. |
| 34 |
""" |
| 35 |
|
| 36 |
scope_string: str |
| 37 |
optional: bool = dataclasses.field(default=False) |
| 38 |
dependencies: tuple[Scope, ...] = dataclasses.field(default=()) |
| 39 |
|
| 40 |
def __post_init__( |
| 41 |
self, |
| 42 |
) -> None: |
| 43 |
if any(c in self.scope_string for c in "[]* "): |
| 44 |
raise ValueError( |
| 45 |
"Scope instances may not contain the special characters '[]* '. " |
| 46 |
"Use Scope.parse instead." |
| 47 |
) |
| 48 |
|
| 49 |
@classmethod |
| 50 |
def parse(cls, scope_string: str) -> Scope: |
| 51 |
""" |
| 52 |
Deserialize a scope string to a scope object. |
| 53 |
|
| 54 |
This is the special case of parsing in which exactly one scope must be returned |
| 55 |
by the parse. If more than one scope is returned by the parse, a ``ValueError`` |
| 56 |
will be raised. |
| 57 |
|
| 58 |
:param scope_string: The string to parse |
| 59 |
""" |
| 60 |
# deferred import because ScopeParser depends on Scope, but Scope.parse |
| 61 |
# is a wrapper over ScopeParser.parse() |
| 62 |
from .parser import ScopeParser |
| 63 |
|
| 64 |
data = ScopeParser.parse(scope_string) |
| 65 |
if len(data) != 1: |
| 66 |
raise ValueError( |
| 67 |
"`Scope.parse()` did not get exactly one scope. " |
| 68 |
f"Instead got data={data}" |
| 69 |
) |
| 70 |
return data[0] |
| 71 |
|
| 72 |
def with_dependency(self, other_scope: Scope) -> Scope: |
| 73 |
""" |
| 74 |
Create a new scope with a dependency. |
| 75 |
The dependent scope relationship will be stored in the Scope and will |
| 76 |
be evident in its string representation. |
| 77 |
|
| 78 |
:param other_scope: The scope upon which the current scope depends. |
| 79 |
""" |
| 80 |
if not isinstance(other_scope, Scope): |
| 81 |
raise TypeError( |
| 82 |
"Scope.with_dependency() takes a Scope as its input. " |
| 83 |
f"Got: '{type(other_scope).__qualname__}'" |
| 84 |
) |
| 85 |
return dataclasses.replace( |
| 86 |
self, dependencies=self.dependencies + (other_scope,) |
| 87 |
) |
| 88 |
|
| 89 |
def with_dependencies(self, other_scopes: t.Iterable[Scope]) -> Scope: |
| 90 |
""" |
| 91 |
Create a new scope with added dependencies. |
| 92 |
The dependent scope relationships will be stored in the Scope and will |
| 93 |
be evident in its string representation. |
| 94 |
|
| 95 |
:param other_scopes: The scopes upon which the current scope depends. |
| 96 |
""" |
| 97 |
other_scopes_tuple = tuple(other_scopes) |
| 98 |
for i, item in enumerate(other_scopes_tuple): |
| 99 |
if not isinstance(item, Scope): |
| 100 |
raise TypeError( |
| 101 |
"Scope.with_dependencies() takes " |
| 102 |
"an iterable of Scopes as its input. " |
| 103 |
f"At position {i}, got: '{type(item).__qualname__}'" |
| 104 |
) |
| 105 |
return dataclasses.replace( |
| 106 |
self, dependencies=self.dependencies + other_scopes_tuple |
| 107 |
) |
| 108 |
|
| 109 |
def with_optional(self, optional: bool) -> Scope: |
| 110 |
""" |
| 111 |
Create a new scope with a different 'optional' value. |
| 112 |
|
| 113 |
:param optional: Whether or not the scope is optional. |
| 114 |
""" |
| 115 |
return dataclasses.replace(self, optional=optional) |
| 116 |
|
| 117 |
def __repr__(self) -> str: |
| 118 |
parts: list[str] = [f"'{self.scope_string}'"] |
| 119 |
if self.optional: |
| 120 |
parts.append("optional=True") |
| 121 |
if self.dependencies: |
| 122 |
parts.append(f"dependencies={self.dependencies!r}") |
| 123 |
return "Scope(" + ", ".join(parts) + ")" |
| 124 |
|
| 125 |
def __str__(self) -> str: |
| 126 |
base_scope = ("*" if self.optional else "") + self.scope_string |
| 127 |
if not self.dependencies: |
| 128 |
return base_scope |
| 129 |
return base_scope + "[" + " ".join(str(c) for c in self.dependencies) + "]" |