| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
from typing import TYPE_CHECKING, Any |
| 7 |
|
| 8 |
from griffe._internal.mixins import DelMembersMixin, GetMembersMixin, SetMembersMixin |
| 9 |
|
| 10 |
if TYPE_CHECKING: |
| 11 |
from collections.abc import ItemsView, KeysView, ValuesView |
| 12 |
from pathlib import Path |
| 13 |
|
| 14 |
from griffe._internal.models import Module |
| 15 |
|
| 16 |
|
| 17 |
class LinesCollection: |
| 18 |
"""A simple dictionary containing the modules source code lines.""" |
| 19 |
|
| 20 |
def __init__(self) -> None: |
| 21 |
"""Initialize the collection.""" |
| 22 |
self._data: dict[Path, list[str]] = {} |
| 23 |
|
| 24 |
def __getitem__(self, key: Path) -> list[str]: |
| 25 |
"""Get the lines of a file path.""" |
| 26 |
return self._data[key] |
| 27 |
|
| 28 |
def __setitem__(self, key: Path, value: list[str]) -> None: |
| 29 |
"""Set the lines of a file path.""" |
| 30 |
self._data[key] = value |
| 31 |
|
| 32 |
def __contains__(self, item: Path) -> bool: |
| 33 |
"""Check if a file path is in the collection.""" |
| 34 |
return item in self._data |
| 35 |
|
| 36 |
def __bool__(self) -> bool: |
| 37 |
"""A lines collection is always true-ish.""" |
| 38 |
return True |
| 39 |
|
| 40 |
def keys(self) -> KeysView: |
| 41 |
"""Return the collection keys. |
| 42 |
|
| 43 |
Returns: |
| 44 |
The collection keys. |
| 45 |
""" |
| 46 |
return self._data.keys() |
| 47 |
|
| 48 |
def values(self) -> ValuesView: |
| 49 |
"""Return the collection values. |
| 50 |
|
| 51 |
Returns: |
| 52 |
The collection values. |
| 53 |
""" |
| 54 |
return self._data.values() |
| 55 |
|
| 56 |
def items(self) -> ItemsView: |
| 57 |
"""Return the collection items. |
| 58 |
|
| 59 |
Returns: |
| 60 |
The collection items. |
| 61 |
""" |
| 62 |
return self._data.items() |
| 63 |
|
| 64 |
|
| 65 |
class ModulesCollection(GetMembersMixin, SetMembersMixin, DelMembersMixin): |
| 66 |
"""A collection of modules, allowing easy access to members.""" |
| 67 |
|
| 68 |
is_collection = True |
| 69 |
"""Marked as collection to distinguish from objects.""" |
| 70 |
|
| 71 |
def __init__(self) -> None: |
| 72 |
"""Initialize the collection.""" |
| 73 |
self.members: dict[str, Module] = {} |
| 74 |
"""Members (modules) of the collection.""" |
| 75 |
|
| 76 |
def __bool__(self) -> bool: |
| 77 |
"""A modules collection is always true-ish.""" |
| 78 |
return True |
| 79 |
|
| 80 |
def __contains__(self, item: Any) -> bool: |
| 81 |
"""Check if a module is in the collection.""" |
| 82 |
return item in self.members |
| 83 |
|
| 84 |
@property |
| 85 |
def all_members(self) -> dict[str, Module]: |
| 86 |
"""Members of the collection. |
| 87 |
|
| 88 |
This property is overwritten to simply return `self.members`, |
| 89 |
as `all_members` does not make sense for a modules collection. |
| 90 |
""" |
| 91 |
return self.members |