use cached property instead of custom __getattr__ implementation

This commit is contained in:
Evgenii Alekseev 2023-05-31 18:47:48 +03:00
parent 3ad6cd27c6
commit e3347aec2d
8 changed files with 36 additions and 53 deletions

View File

@ -103,6 +103,9 @@ Again, the most checks can be performed by `make check` command, though some add
@property @property
def property(self) -> Any: ... def property(self) -> Any: ...
@cached_property
def property_cached(self) -> Any: ... # cached property has to be treated as normal one
@classmethod @classmethod
def class_method(cls) -> Self: ... def class_method(cls) -> Self: ...

View File

@ -25,7 +25,7 @@ ignore_packages =
makechrootpkg_flags = makechrootpkg_flags =
makepkg_flags = --nocolor --ignorearch makepkg_flags = --nocolor --ignorearch
triggers = ahriman.core.gitremote.RemotePullTrigger ahriman.core.report.ReportTrigger ahriman.core.upload.UploadTrigger ahriman.core.gitremote.RemotePushTrigger triggers = ahriman.core.gitremote.RemotePullTrigger ahriman.core.report.ReportTrigger ahriman.core.upload.UploadTrigger ahriman.core.gitremote.RemotePushTrigger
triggers_known = ahriman.core.support.KeyringTrigger ahriman.core.support.MirrorlistTrigger triggers_known = ahriman.core.gitremote.RemotePullTrigger ahriman.core.gitremote.RemotePushTrigger ahriman.core.report.ReportTrigger ahriman.core.upload.UploadTrigger ahriman.core.support.KeyringTrigger ahriman.core.support.MirrorlistTrigger
vcs_allowed_age = 604800 vcs_allowed_age = 604800
[repository] [repository]

View File

@ -80,7 +80,7 @@ class Validate(Handler):
loader = TriggerLoader() loader = TriggerLoader()
triggers = loader.selected_triggers(configuration) + loader.known_triggers(configuration) triggers = loader.selected_triggers(configuration) + loader.known_triggers(configuration)
for trigger in triggers: for trigger in set(triggers):
try: try:
trigger_class = loader.load_trigger_class(trigger) trigger_class = loader.load_trigger_class(trigger)
except ExtensionError: except ExtensionError:

View File

@ -20,9 +20,9 @@
import shutil import shutil
from collections.abc import Callable, Generator from collections.abc import Callable, Generator
from functools import cached_property
from pathlib import Path from pathlib import Path
from pyalpm import DB, Handle, Package, SIG_PACKAGE, error as PyalpmError # type: ignore[import] from pyalpm import DB, Handle, Package, SIG_PACKAGE, error as PyalpmError # type: ignore[import]
from typing import Any
from ahriman.core.configuration import Configuration from ahriman.core.configuration import Configuration
from ahriman.core.log import LazyLogging from ahriman.core.log import LazyLogging
@ -34,13 +34,8 @@ from ahriman.models.repository_paths import RepositoryPaths
class Pacman(LazyLogging): class Pacman(LazyLogging):
""" """
alpm wrapper alpm wrapper
Attributes:
handle(Handle): pyalpm root ``Handle``
""" """
handle: Handle
def __init__(self, architecture: str, configuration: Configuration, *, def __init__(self, architecture: str, configuration: Configuration, *,
refresh_database: PacmanSynchronization) -> None: refresh_database: PacmanSynchronization) -> None:
""" """
@ -84,6 +79,16 @@ class Pacman(LazyLogging):
return handle return handle
@cached_property
def handle(self) -> Handle:
"""
pyalpm handle
Returns:
Handle: generated pyalpm handle instance
"""
return self.__create_handle_fn()
def database_copy(self, handle: Handle, database: DB, pacman_root: Path, paths: RepositoryPaths, *, def database_copy(self, handle: Handle, database: DB, pacman_root: Path, paths: RepositoryPaths, *,
use_ahriman_cache: bool) -> None: use_ahriman_cache: bool) -> None:
""" """
@ -184,22 +189,3 @@ class Pacman(LazyLogging):
result.update(trim_package(provides) for provides in package.provides) result.update(trim_package(provides) for provides in package.provides)
return result return result
def __getattr__(self, item: str) -> Any:
"""
pacman handle extractor
Args:
item(str): property name
Returns:
Any: attribute by its name
Raises:
AttributeError: in case if no such attribute found
"""
if item == "handle":
handle = self.__create_handle_fn()
setattr(self, item, handle)
return handle
return super().__getattr__(item) # required for logging attribute

View File

@ -21,18 +21,24 @@ import contextlib
import logging import logging
from collections.abc import Generator from collections.abc import Generator
from functools import cached_property
from typing import Any from typing import Any
class LazyLogging: class LazyLogging:
""" """
wrapper for the logger library inspired by scala lazy logging module wrapper for the logger library inspired by scala lazy logging module
Attributes:
logger(logging.Logger): class logger instance
""" """
logger: logging.Logger @cached_property
def logger(self) -> logging.Logger:
"""
get class logger instance
Returns:
logging.Logger: class logger instance
"""
return logging.getLogger(self.logger_name)
@property @property
def logger_name(self) -> str: def logger_name(self) -> str:
@ -89,22 +95,3 @@ class LazyLogging:
yield yield
finally: finally:
self._package_logger_reset() self._package_logger_reset()
def __getattr__(self, item: str) -> Any:
"""
logger extractor
Args:
item(str): property name
Returns:
Any: attribute by its name
Raises:
AttributeError: in case if no such attribute found
"""
if item == "logger":
logger = logging.getLogger(self.logger_name)
setattr(self, item, logger)
return logger
raise AttributeError(f"'{self.__class__.__qualname__}' object has no attribute '{item}'")

View File

@ -17,6 +17,8 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
from collections.abc import Callable
from ahriman.core.configuration import Configuration from ahriman.core.configuration import Configuration
from ahriman.core.configuration.schema import ConfigurationSchema from ahriman.core.configuration.schema import ConfigurationSchema
from ahriman.core.log import LazyLogging from ahriman.core.log import LazyLogging
@ -128,8 +130,10 @@ class Trigger(LazyLogging):
result(Result): build result result(Result): build result
packages(list[Package]): list of all available packages packages(list[Package]): list of all available packages
""" """
if (run := getattr(self, "run", None)) is not None: # compatibility with old triggers
run(result, packages) # compatibility with old triggers run: Callable[[Result, list[Package]], None] | None = getattr(self, "run", None)
if run is not None:
run(result, packages)
def on_start(self) -> None: def on_start(self) -> None:
""" """

View File

@ -61,11 +61,14 @@ def test_schema(configuration: Configuration) -> None:
assert schema.pop("console") assert schema.pop("console")
assert schema.pop("email") assert schema.pop("email")
assert schema.pop("github") assert schema.pop("github")
assert schema.pop("gitremote")
assert schema.pop("html") assert schema.pop("html")
assert schema.pop("keyring") assert schema.pop("keyring")
assert schema.pop("keyring_generator") assert schema.pop("keyring_generator")
assert schema.pop("mirrorlist") assert schema.pop("mirrorlist")
assert schema.pop("mirrorlist_generator") assert schema.pop("mirrorlist_generator")
assert schema.pop("remote-pull")
assert schema.pop("remote-push")
assert schema.pop("report") assert schema.pop("report")
assert schema.pop("rsync") assert schema.pop("rsync")
assert schema.pop("s3") assert schema.pop("s3")

View File

@ -25,7 +25,7 @@ ignore_packages =
makechrootpkg_flags = makechrootpkg_flags =
makepkg_flags = --skippgpcheck makepkg_flags = --skippgpcheck
triggers = ahriman.core.report.ReportTrigger ahriman.core.upload.UploadTrigger triggers = ahriman.core.report.ReportTrigger ahriman.core.upload.UploadTrigger
triggers_known = ahriman.core.support.KeyringTrigger ahriman.core.support.MirrorlistTrigger triggers_known = ahriman.core.gitremote.RemotePullTrigger ahriman.core.gitremote.RemotePushTrigger ahriman.core.report.ReportTrigger ahriman.core.upload.UploadTrigger ahriman.core.support.KeyringTrigger ahriman.core.support.MirrorlistTrigger
[repository] [repository]
name = aur-clone name = aur-clone