Compare commits

...
8 Commits
77 changed files with 228 additions and 188 deletions

No files matched your search

-3
View File
@@ -147,9 +147,6 @@ Again, the most checks can be performed by `tox` command, though some additional
* Import order must be the following:
```python
# optional imports from future module
from __future__ import annotations
# Module import for those which are installed into environment (no matter standard library or not)...
import os
# ...one per line...
@@ -45,7 +45,7 @@ class Application(ApplicationPackages, ApplicationRepository):
>>> application.add(["ahriman"], PackageSource.AUR)
>>>
>>> # check for updates
>>> updates = application.updates([], aur=True, local=True, manual=True, vcs=True)
>>> updates = application.updates([], aur=True, local=True, manual=True, vcs=True, check_files=False)
>>> # updates for specified packages
>>> application.update(updates)
@@ -41,7 +41,7 @@ class UpdatesIterator(Iterator[list[str] | None]):
Typical usage of this class is something like:
>>> application = ...
>>> iterator = UpdatesIterator(application, None)
>>> iterator = UpdatesIterator(application, 3600)
>>>
>>> for updates in iterator:
>>> print(updates)
@@ -17,8 +17,6 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import annotations
from collections.abc import Iterable
from ahriman.core.configuration import Configuration
@@ -158,7 +158,7 @@ class Statistics(Handler):
Args:
event_type(str): event type
events(list[Event]): list of events
chart_path(Path): path to save plot if any
chart_path(Path | None): path to save plot if any
"""
# event statistics
Statistics.event_stats(event_type, events)
@@ -175,7 +175,7 @@ class Statistics(Handler):
Args:
event_type(str): event type
events(list[Event]): list of events
chart_path(Path): path to save plot if any
chart_path(Path | None): path to save plot if any
"""
key: Callable[[Event], str] = lambda event: event.object_id
by_object_id = {
@@ -18,6 +18,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import argparse
import itertools
from collections.abc import Callable
@@ -56,9 +57,9 @@ class Status(Handler):
service_status = client.status_get()
StatusPrinter(service_status.status)(verbose=args.info)
if args.package:
packages: list[tuple[Package, BuildStatus]] = sum(
(client.package_get(base) for base in args.package),
start=[])
packages: list[tuple[Package, BuildStatus]] = list(
itertools.chain.from_iterable(client.package_get(base) for base in args.package)
)
else:
packages = client.package_get(None)
@@ -77,7 +77,7 @@ class UnsafeCommands(Handler):
check if command is unsafe
Args:
command(str): command to check
command(list[str]): command and arguments to check
unsafe_commands(list[str]): list of unsafe commands
parser(argparse.ArgumentParser): generated argument parser
"""
@@ -19,6 +19,7 @@
#
import argparse
import copy
import itertools
from typing import Any
@@ -97,7 +98,7 @@ class Validate(Handler):
# create trigger loader instance
loader = TriggerLoader()
triggers = loader.selected_triggers(configuration) + loader.known_triggers(configuration)
triggers = itertools.chain(loader.selected_triggers(configuration), loader.known_triggers(configuration))
for trigger in set(triggers):
try:
@@ -18,6 +18,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import argparse
import itertools
import re
import sys
@@ -99,7 +100,7 @@ class Versions(Handler):
keys.extend(portion)
portion = {
key
for key in sum((list(dependencies_by_key(key)) for key in portion), start=[])
for key in itertools.chain.from_iterable(dependencies_by_key(key) for key in portion)
if key not in keys
}
+1 -1
View File
@@ -88,7 +88,7 @@ class _Context:
iterate over keys in local storage
Returns:
str: context key iterator
Iterator[str]: context key iterator
"""
return iter(self._content)
@@ -134,7 +134,7 @@ class Configuration(configparser.RawConfigParser):
repository identifier
Returns:
RepositoryId: repository unique identifier
RepositoryId | None: repository unique identifier
"""
return self._repository_id
@@ -58,7 +58,7 @@ class Migrations(LazyLogging):
configuration(Configuration): configuration instance
Returns:
MigrationResult: current schema version
MigrationResult: schema versions before and after migration
"""
return Migrations(connection, configuration).run()
@@ -144,8 +144,8 @@ class Migrations(LazyLogging):
"""
perform migrations
Return:
MigrationResult: current schema version
Returns:
MigrationResult: schema versions before and after migration
"""
migrations = self.migrations()
@@ -35,7 +35,7 @@ class BuildOperations(Operations):
Args:
package_base(str | None): optional filter by package base
repository_id(RepositoryId, optional): repository unique identifier override (Default value = None)
repository_id(RepositoryId | None, optional): repository unique identifier override (Default value = None)
"""
repository_id = repository_id or self._repository_id
@@ -57,9 +57,9 @@ class BuildOperations(Operations):
retrieve packages from build queue
Args:
repository_id(RepositoryId, optional): repository unique identifier override (Default value = None)
repository_id(RepositoryId | None, optional): repository unique identifier override (Default value = None)
Return:
Returns:
list[Package]: list of packages to be built
"""
repository_id = repository_id or self._repository_id
@@ -81,7 +81,7 @@ class BuildOperations(Operations):
Args:
package(Package): package to be inserted
repository_id(RepositoryId, optional): repository unique identifier override (Default value = None)
repository_id(RepositoryId | None, optional): repository unique identifier override (Default value = None)
"""
repository_id = repository_id or self._repository_id
@@ -35,7 +35,7 @@ class ChangesOperations(Operations):
Args:
package_base(str): package base to search
repository_id(RepositoryId, optional): repository unique identifier override (Default value = None)
repository_id(RepositoryId | None, optional): repository unique identifier override (Default value = None)
Returns:
Changes: changes for the package base if available
@@ -69,7 +69,7 @@ class ChangesOperations(Operations):
Args:
package_base(str): package base to insert
changes(Changes): package changes (as in patch format)
repository_id(RepositoryId, optional): repository unique identifier override (Default value = None)
repository_id(RepositoryId | None, optional): repository unique identifier override (Default value = None)
"""
repository_id = repository_id or self._repository_id
@@ -101,7 +101,7 @@ class ChangesOperations(Operations):
Args:
package_base(str | None): optional filter by package base
repository_id(RepositoryId, optional): repository unique identifier override (Default value = None)
repository_id(RepositoryId | None, optional): repository unique identifier override (Default value = None)
"""
repository_id = repository_id or self._repository_id
@@ -36,10 +36,10 @@ class DependenciesOperations(Operations):
Args:
package_base(str | None): package base to search
repository_id(RepositoryId, optional): repository unique identifier override (Default value = None)
repository_id(RepositoryId | None, optional): repository unique identifier override (Default value = None)
Returns:
Dependencies: dependencies for the package base if available
dict[str, Dependencies]: dependencies keyed by package base, optionally filtered by package base
"""
repository_id = repository_id or self._repository_id
@@ -69,7 +69,7 @@ class DependenciesOperations(Operations):
Args:
package_base(str): package base
dependencies(Dependencies): package dependencies
repository_id(RepositoryId, optional): repository unique identifier override (Default value = None)
repository_id(RepositoryId | None, optional): repository unique identifier override (Default value = None)
"""
repository_id = repository_id or self._repository_id
@@ -97,7 +97,7 @@ class DependenciesOperations(Operations):
Args:
package_base(str | None): optional filter by package base
repository_id(RepositoryId, optional): repository unique identifier override (Default value = None)
repository_id(RepositoryId | None, optional): repository unique identifier override (Default value = None)
"""
repository_id = repository_id or self._repository_id
@@ -42,7 +42,7 @@ class EventOperations(Operations):
to_date(int | float | None, optional): maximal creation date, exclusive (Default value = None)
limit(int, optional): limit records to the specified count, -1 means unlimited (Default value = -1)
offset(int, optional): records offset (Default value = 0)
repository_id(RepositoryId, optional): repository unique identifier override (Default value = None)
repository_id(RepositoryId | None, optional): repository unique identifier override (Default value = None)
Returns:
list[Event]: list of audit log events
@@ -84,7 +84,7 @@ class EventOperations(Operations):
Args:
event(Event): event to insert
repository_id(RepositoryId, optional): repository unique identifier override (Default value = None)
repository_id(RepositoryId | None, optional): repository unique identifier override (Default value = None)
"""
repository_id = repository_id or self._repository_id
@@ -40,9 +40,9 @@ class LogsOperations(Operations):
process_id(str | None, optional): process identifier to filter (Default value = None)
limit(int, optional): limit records to the specified count, -1 means unlimited (Default value = -1)
offset(int, optional): records offset (Default value = 0)
repository_id(RepositoryId, optional): repository unique identifier override (Default value = None)
repository_id(RepositoryId | None, optional): repository unique identifier override (Default value = None)
Return:
Returns:
list[LogRecord]: sorted package log records
"""
repository_id = repository_id or self._repository_id
@@ -79,7 +79,7 @@ class LogsOperations(Operations):
Args:
log_record(LogRecord): log record object
repository_id(RepositoryId, optional): repository unique identifier override (Default value = None)
repository_id(RepositoryId | None, optional): repository unique identifier override (Default value = None)
"""
repository_id = repository_id or self._repository_id
@@ -106,7 +106,7 @@ class LogsOperations(Operations):
Args:
package_base(str): package base to remove logs
version(str | None): package version. If set it will remove only logs belonging to another version
repository_id(RepositoryId, optional): repository unique identifier override (Default value = None)
repository_id(RepositoryId | None, optional): repository unique identifier override (Default value = None)
"""
repository_id = repository_id or self._repository_id
@@ -133,7 +133,7 @@ class LogsOperations(Operations):
Args:
keep_last_records(int): number of last records to keep
repository_id(RepositoryId, optional): repository unique identifier override (Default value = None)
repository_id(RepositoryId | None, optional): repository unique identifier override (Default value = None)
"""
repository_id = repository_id or self._repository_id
@@ -66,7 +66,7 @@ class Operations(LazyLogging):
dictionary factory based on official documentation
Args:
cursor(Cursor): cursor descriptor
cursor(sqlite3.Cursor): cursor descriptor
row(tuple[Any, ...]): fetched row
Returns:
@@ -82,7 +82,7 @@ class Operations(LazyLogging):
perform operation in connection
Args:
query(Callable[[Connection], T]): function to be called with connection
query(Callable[[sqlite3.Connection], T]): function to be called with connection
commit(bool, optional): if ``True`` commit() will be called on success (Default value = False)
Returns:
@@ -225,7 +225,7 @@ class PackageOperations(Operations):
Args:
package_base(str): package base name
repository_id(RepositoryId, optional): repository unique identifier override (Default value = None)
repository_id(RepositoryId | None, optional): repository unique identifier override (Default value = None)
enabled(bool): new hold status
"""
repository_id = repository_id or self._repository_id
@@ -248,7 +248,7 @@ class PackageOperations(Operations):
Args:
package_base(str): package base name
repository_id(RepositoryId, optional): repository unique identifier override (Default value = None)
repository_id(RepositoryId | None, optional): repository unique identifier override (Default value = None)
"""
repository_id = repository_id or self._repository_id
@@ -264,7 +264,7 @@ class PackageOperations(Operations):
Args:
package(Package): package properties
repository_id(RepositoryId, optional): repository unique identifier override (Default value = None)
repository_id(RepositoryId | None, optional): repository unique identifier override (Default value = None)
"""
repository_id = repository_id or self._repository_id
@@ -280,9 +280,9 @@ class PackageOperations(Operations):
get package list and their build statuses from database
Args:
repository_id(RepositoryId, optional): repository unique identifier override (Default value = None)
repository_id(RepositoryId | None, optional): repository unique identifier override (Default value = None)
Return:
Returns:
list[tuple[Package, BuildStatus]]: list of package properties and their statuses
"""
repository_id = repository_id or self._repository_id
@@ -303,7 +303,7 @@ class PackageOperations(Operations):
Args:
package_base(str): package base name
status(BuildStatus): new build status
repository_id(RepositoryId, optional): repository unique identifier override (Default value = None)
repository_id(RepositoryId | None, optional): repository unique identifier override (Default value = None)
"""
repository_id = repository_id or self._repository_id
@@ -116,7 +116,7 @@ class SQLite(
Args:
package_base(str): package base to remove
repository_id(RepositoryId, optional): repository unique identifier override (Default value = None)
repository_id(RepositoryId | None, optional): repository unique identifier override (Default value = None)
Examples:
This method completely removes the package from all tables and must be used, e.g. on package removal::
+1 -1
View File
@@ -254,7 +254,7 @@ class PasswordError(ValueError):
def __init__(self, details: Any) -> None:
"""
Args:
details(Any); error details
details(Any): error details
"""
ValueError.__init__(self, f"Password error: {details}")
@@ -35,6 +35,7 @@ class RepositoryStatsPrinter(StringPrinter):
def __init__(self, repository_id: RepositoryId, statistics: RepositoryStats) -> None:
"""
Args:
repository_id(RepositoryId): repository unique identifier
statistics(RepositoryStats): repository statistics
"""
StringPrinter.__init__(self, str(repository_id))
@@ -90,6 +90,9 @@ class UpdatePrinter(StringPrinter):
"""
generate version property
Args:
package(Package): package whose current and updated versions are shown
Returns:
tuple[str, str]: extract current and updated versions for the package
"""
@@ -81,7 +81,7 @@ class SyncHttpClient(LazyLogging):
get or create session
Returns:
request.Session: created session object
requests.Session: created session object
"""
session = requests.Session()
@@ -107,10 +107,10 @@ class JinjaTemplate:
sort content before rendering
Args:
content(list[dict[str, str]]): content of the template
content(list[dict[str, Any]]): content of the template
Returns:
list[dict[str, str]]: sorted content according to comparator defined
list[dict[str, Any]]: sorted content according to comparator defined
"""
comparator: Callable[[dict[str, str]], Comparable] = lambda item: item["filename"]
return sorted(content, key=comparator)
@@ -122,6 +122,9 @@ class JinjaTemplate:
Args:
result(Result): build result
template_name(Path | str): name of the template or path to it (legacy configuration)
Returns:
str: rendered report
"""
templates = self.templates[:]
if isinstance(template_name, Path):
@@ -17,8 +17,6 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import annotations
from ahriman.core.configuration import Configuration
from ahriman.core.exceptions import ReportError
from ahriman.core.log import LazyLogging
+2 -2
View File
@@ -82,10 +82,10 @@ class RSS(Report, JinjaTemplate):
sort content before rendering
Args:
content(list[dict[str, str]]): content of the template
content(list[dict[str, Any]]): content of the template
Returns:
list[dict[str, str]]: sorted content according to comparator defined
list[dict[str, Any]]: sorted content according to comparator defined
"""
comparator: Callable[[dict[str, str]], Comparable] = \
lambda item: parsedate_to_datetime(item["build_date"])
@@ -86,7 +86,7 @@ class RepositoryProperties(EventLogger, LazyLogging):
package_base(str): package base to lookup
Returns:
User | None: user found in database if any and empty object otherwise
User: user found in database if any and empty user object otherwise
"""
username = packagers.for_base(package_base)
if username is None: # none to search
@@ -17,6 +17,8 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import itertools
from collections.abc import Iterable
from ahriman.core.build_tools.package_version import PackageVersion
@@ -126,7 +128,7 @@ class UpdateHandler(PackageInfo, Cleaner):
if not dependencies.paths:
continue # skip check if no package dependencies found
required_packages = {dep for dep_packages in dependencies.paths.values() for dep in dep_packages}
required_packages = set(itertools.chain.from_iterable(dependencies.paths.values()))
filesystem = extract_files(required_packages)
for path, packages in dependencies.paths.items():
+1 -1
View File
@@ -103,7 +103,7 @@ class GPG(SyncHttpClient):
filepath(Path): path to the file which will be signed
Returns:
str: path to signature file
Path: path to signature file
"""
return filepath.parent / f"{filepath.name}.sig"
+6 -7
View File
@@ -17,13 +17,13 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import annotations
import argparse
import itertools
import uuid
from collections.abc import Callable, Iterable
from multiprocessing import Process, Queue
from multiprocessing import Process, get_context
from multiprocessing.queues import Queue
from threading import Lock, Thread
from ahriman.core.log import LazyLogging
@@ -57,8 +57,7 @@ class Spawn(Thread, LazyLogging):
self._lock = Lock()
self.active: dict[str, Process] = {}
# stupid pylint does not know that it is possible
self.queue: Queue[ProcessStatus | None] = Queue() # pylint: disable=unsubscriptable-object
self.queue: Queue[ProcessStatus | None] = get_context("spawn").Queue()
@staticmethod
def boolean_action_argument(name: str, value: bool) -> str:
@@ -76,7 +75,7 @@ class Spawn(Thread, LazyLogging):
@staticmethod
def process(callback: Callable[[argparse.Namespace, RepositoryId], bool], args: argparse.Namespace,
repository_id: RepositoryId, process_id: str, queue: Queue[ProcessStatus | None]) -> None: # pylint: disable=unsubscriptable-object
repository_id: RepositoryId, process_id: str, queue: Queue[ProcessStatus | None]) -> None:
"""
helper to run external process
@@ -119,7 +118,7 @@ class Spawn(Thread, LazyLogging):
continue # skip null values
flag = f"--{argument}"
if isinstance(value, list):
arguments.extend(list(sum(((flag, v) for v in value), ())))
arguments.extend(itertools.chain.from_iterable((flag, v) for v in value))
elif value:
arguments.extend([flag, value])
else:
@@ -18,8 +18,6 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# pylint: disable=too-many-public-methods
from __future__ import annotations
from ahriman.core.configuration import Configuration
from ahriman.core.database import SQLite
from ahriman.models.build_status import BuildStatus, BuildStatusEnum
@@ -164,7 +162,7 @@ class Client:
package_base(str): package base to retrieve
Returns:
list[Dependencies]: package implicit dependencies if available
Dependencies: package implicit dependencies if available
Raises:
NotImplementedError: not implemented method
@@ -114,7 +114,7 @@ class LocalClient(Client):
package_base(str): package base to retrieve
Returns:
list[Dependencies]: package implicit dependencies if available
Dependencies: package implicit dependencies if available
"""
return self.database.dependencies_get(package_base, self.repository_id).get(package_base, Dependencies())
@@ -151,7 +151,7 @@ class Watcher(LazyLogging):
package_base(str): package base to retrieve
Returns:
list[Dependencies]: package implicit dependencies if available
Dependencies: package implicit dependencies if available
"""
return self.client.package_dependencies_get(package_base)
@@ -269,7 +269,7 @@ class WebClient(Client, SyncAhrimanClient):
package_base(str): package base to retrieve
Returns:
list[Dependencies]: package implicit dependencies if available
Dependencies: package implicit dependencies if available
"""
with contextlib.suppress(Exception):
response = self.make_request("GET", self._dependencies_url(package_base),
-2
View File
@@ -17,8 +17,6 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import annotations
from collections.abc import Iterable
from functools import partial
@@ -57,7 +57,7 @@ class RemoteService(Upload, HttpUpload):
get or create session
Returns:
request.Session: created session object
requests.Session: created session object
"""
return self.client.session
@@ -17,8 +17,6 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import annotations
from pathlib import Path
from ahriman.core.configuration import Configuration
+2 -2
View File
@@ -101,8 +101,8 @@ def check_output(*args: str, exception: Exception | Callable[[int, list[str], st
Args:
*args(str): command line arguments
exception(Exception | Callable[[int, list[str], str, str]] | None, optional): exception which has to be raised
instead of default subprocess exception. If callable us is supplied, the
exception(Exception | Callable[[int, list[str], str, str], Exception] | None, optional): exception to raise
instead of the default subprocess exception. If a callable is supplied, the
:exc:`subprocess.CalledProcessError` arguments will be passed (Default value = None)
cwd(Path | None, optional): current working directory (Default value = None)
input_data(str | None, optional): data which will be written to command stdin (Default value = None)
@@ -69,11 +69,13 @@ class AURPackage:
>>>
>>> from ahriman.core.alpm.pacman import Pacman
>>> from ahriman.core.configuration import Configuration
>>> from ahriman.models.pacman_synchronization import PacmanSynchronization
>>> from ahriman.models.repository_id import RepositoryId
>>>
>>> configuration = Configuration()
>>> pacman = Pacman(RepositoryId("x86_64", "aur"), configuration)
>>> metadata = pacman.package_get("pacman")
>>> pacman = Pacman(RepositoryId("x86_64", "aur"), configuration,
>>> refresh_database=PacmanSynchronization.DISABLED)
>>> metadata = pacman.package("pacman")
>>> package = AURPackage.from_pacman(next(metadata)) # load package from pyalpm wrapper
"""
@@ -17,8 +17,6 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import annotations
from enum import StrEnum
@@ -182,7 +182,7 @@ class BuildPlan(Iterable[Package]):
iterate over selected packages in stable package-base order
Returns:
Package: selected package
Iterator[Package]: iterator over selected packages
"""
return iter(self.packages)
@@ -17,8 +17,6 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import annotations
from collections.abc import Iterable
from dataclasses import dataclass, field
from pathlib import Path
@@ -34,7 +32,7 @@ class FilesystemPackage:
Attributes:
package_name(str): package name
depends(set[str]): list of package dependencies
directories(set[Path]): list of directories this package contains
directories(list[Path]): list of directories this package contains
files(list[Path]): list of files this package contains
opt_depends(set[str]): list of package optional dependencies
"""
@@ -80,7 +78,8 @@ class FilesystemPackage:
include_optional(bool): include optional dependencies to check
Returns:
bool: whether this package depends on any other package in the list of packages
bool: ``True`` if this package has no dependencies among the supplied packages, ignoring packages
that have a required dependency on this package
"""
return not any(
package
@@ -38,9 +38,9 @@ class MetricsTimer:
>>> with MetricsTimer() as timer:
>>> do_something()
>>> print("Time elapsed for first function: %f", timer.elapsed)
>>> print(f"Time elapsed for first function: {timer.elapsed:f}")
>>> do_something_different()
>>> print("Time elapsed for all functions: %f", timer.elapsed)
>>> print(f"Time elapsed for all functions: {timer.elapsed:f}")
"""
def __init__(self) -> None:
+3 -5
View File
@@ -17,8 +17,6 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import annotations
from collections.abc import Iterable
from dataclasses import dataclass
from pathlib import Path
@@ -44,8 +42,8 @@ class Package(LazyLogging):
Attributes:
base(str): package base name
packager(str | None): package packager if available
packages(dict[str, PackageDescription): map of package names to their properties.
Filled only on load from archive
packages(dict[str, PackageDescription]): map of package names to their properties.
Available properties depend on the source used to load the package
remote(RemoteSource): package remote source if applicable
version(str): package full version
@@ -56,7 +54,7 @@ class Package(LazyLogging):
it will contain every data available in the JSON body. Otherwise, if generate package from local archive::
>>> package = Package.from_archive(local_path, pacman)
>>> package = Package.from_archive(local_path)
it will probably miss file descriptions (in case if there are multiple packages which belong to the base).
@@ -57,11 +57,13 @@ class PackageDescription:
>>> from pathlib import Path
>>> from ahriman.core.alpm.pacman import Pacman
>>> from ahriman.core.configuration import Configuration
>>> from ahriman.models.pacman_synchronization import PacmanSynchronization
>>> from ahriman.models.repository_id import RepositoryId
>>>
>>> configuration = Configuration()
>>> pacman = Pacman(RepositoryId("x86_64", "aur"), configuration)
>>> pyalpm_description = next(package for package in pacman.package_get("pacman"))
>>> pacman = Pacman(RepositoryId("x86_64", "aur"), configuration,
>>> refresh_database=PacmanSynchronization.DISABLED)
>>> pyalpm_description = next(package for package in pacman.package("pacman"))
>>> description = PackageDescription.from_package(
>>> pyalpm_description, Path("/var/cache/pacman/pkg/pacman-6.0.1-4-x86_64.pkg.tar.zst"))
"""
@@ -17,8 +17,6 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import annotations
from enum import StrEnum
from pathlib import Path
from urllib.parse import urlparse
+1 -1
View File
@@ -27,7 +27,7 @@ class Packagers:
Attributes:
default(str | None): default packager username if any to be used if no override for the specified base was found
overrides: dict[str, str | None]: packager username override for specific package base
overrides(dict[str, str | None]): packager username override for specific package base
"""
default: str | None = None
@@ -109,7 +109,7 @@ class PkgbuildPatch:
Args:
key(str | None): variable key
source(str): source value string to parse
source(str | list[str]): source string to parse or list to use as is
Returns:
Self: parsed patch object
@@ -17,8 +17,6 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import annotations
from enum import StrEnum
@@ -56,7 +56,7 @@ class RepositoryStats:
construct statistics from list of repository packages
Args:
packages(list[Packages]): list of repository packages
packages(list[Package]): list of repository packages
Returns:
Self: constructed statistics object
+2 -2
View File
@@ -17,7 +17,7 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import annotations
import itertools
from collections.abc import Callable, Iterable
from typing import Any, ClassVar, Self
@@ -102,7 +102,7 @@ class Result:
Returns:
list[Package]: list of packages with success result
"""
return list(self._added.values()) + list(self._updated.values())
return list(itertools.chain(self._added.values(), self._updated.values()))
def add_added(self, package: Package) -> None:
"""
@@ -41,7 +41,7 @@ class ScanPaths:
compiled regular expressions
Returns:
list[re.Pattern]: a list of compiled regular expressions
list[re.Pattern[str]]: a list of compiled regular expressions
"""
return [re.compile(path) for path in self.paths]
@@ -17,8 +17,6 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import annotations
from enum import StrEnum
@@ -17,8 +17,6 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import annotations
from enum import StrEnum
@@ -17,8 +17,6 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import annotations
from enum import StrEnum
@@ -17,8 +17,6 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import annotations
from enum import StrEnum
@@ -15,7 +15,7 @@ def pacman_database(configuration: Configuration, pacman: Pacman) -> PacmanDatab
pacman(Pacman): pacman test instance
Returns:
DatabaseSync: database sync test instance
PacmanDatabase: pacman database test instance
"""
database = next(iter(pacman.handle.get_syncdbs()))
return PacmanDatabase(database, configuration)
@@ -17,6 +17,8 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import itertools
from collections.abc import Callable
from pathlib import Path
@@ -117,7 +119,7 @@ class KeyringGenerator(PkgbuildGenerator):
source_path(Path): destination of the file content
"""
with source_path.open("w", encoding="utf8") as source_file:
for key in sorted(set(self.trusted + self.packagers + self.revoked)):
for key in sorted(set(itertools.chain(self.trusted, self.packagers, self.revoked))):
public_key = self.sign.key_export(key)
source_file.write(public_key)
source_file.write("\n")
@@ -17,8 +17,6 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import annotations
from ahriman.core.configuration import Configuration
from ahriman.core.database import SQLite
from ahriman.core.log import LazyLogging
@@ -39,8 +39,8 @@ def _response_schema(response: Schema | type[Schema] | None, response_code: type
response(Schema | type[Schema] | None): response schema type, set ``None`` for empty responses
response_code(type[HTTPException] | None, optional): code for the success response. If none set it will be
defined automatically (Default value = None)
error_400_enabled(bool, optional): include response for 404 codes (Default value = False)
error_403_enabled(bool, optional): include response for 403 codes (Default value = False)
error_400_enabled(bool, optional): include response for 400 codes (Default value = False)
error_403_enabled(bool, optional): include response for 403 codes (Default value = True)
error_404_description(str | None, optional): description for 404 codes if available (Default value = None)
Returns:
@@ -98,7 +98,7 @@ def apidocs(*,
permission(UserAccess): permission to access endpoint
response_code(type[HTTPException] | None, optional): code for the success response. If none set it will be
defined automatically (Default value = None)
error_400_enabled(bool, optional): include response for 404 codes (Default value = False)
error_400_enabled(bool, optional): include response for 400 codes (Default value = False)
error_404_description(str | None, optional): description for 404 codes if available (Default value = None)
schema(Schema | type[Schema] | None): response schema type, set ``None`` for empty responses
(Default value = None)
@@ -88,7 +88,7 @@ def _auth_handler(allow_read_only: bool) -> Middleware:
authorization and authentication middleware
Args:
allow_read_only: allow
allow_read_only(bool): allow read-only requests without authentication
Returns:
Middleware: built middleware
@@ -31,10 +31,11 @@ def test_get_provider() -> None:
assert OAuth.get_provider("GithubClient") == aioauth_client.GithubClient
def test_get_provider_not_a_type() -> None:
def test_get_provider_not_a_type(mocker: MockerFixture) -> None:
"""
must raise an exception if attribute is not a type
"""
mocker.patch.object(aioauth_client, "RANDOM", "not a type", create=True)
with pytest.raises(OptionError):
OAuth.get_provider("RANDOM")
+2 -2
View File
@@ -83,7 +83,7 @@ def schema_request(handler: Callable[..., Awaitable[Any]], *, location: str = "j
extract request schema from docs
Args:
handler(Callable[[], Awaitable[Any]]): request handler
handler(Callable[..., Awaitable[Any]]): request handler
location(str, optional): location of the request (Default value = "json")
Returns:
@@ -99,7 +99,7 @@ def schema_response(handler: Callable[..., Awaitable[Any]], *, code: int = 200)
extract response schema from docs
Args:
handler(Callable[[], Awaitable[Any]]): request handler
handler(Callable[..., Awaitable[Any]]): request handler
code(int, optional): return code of the request (Default value = 200)
Returns:
@@ -16,7 +16,7 @@ def authorization_policy(configuration: Configuration, database: SQLite) -> _Aut
database(SQLite): database fixture
Returns:
AuthorizationPolicy: authorization policy fixture
_AuthorizationPolicy: authorization policy fixture
"""
configuration.set_option("auth", "target", "configuration")
validator = Auth.load(configuration, database)
-4
View File
@@ -75,14 +75,10 @@ export class FetchClient {
async fetchPackageLogs(
packageBase: string,
repository: RepositoryId,
version?: string,
processId?: string,
head?: boolean,
): Promise<LogRecord[]> {
const query: Record<string, string | boolean> = { ...repository.toQuery() };
if (version) {
query.version = version;
}
if (processId) {
query.process_id = processId;
}
+28 -3
View File
@@ -19,15 +19,17 @@
*/
import "components/common/syntaxLanguages";
import { Box, useTheme } from "@mui/material";
import DownloadIcon from "@mui/icons-material/Download";
import { Box, IconButton, Tooltip, useTheme } from "@mui/material";
import CopyButton from "components/common/CopyButton";
import { useThemeMode } from "hooks/useThemeMode";
import React, { type RefObject } from "react";
import React, { type RefObject, useEffect, useRef } from "react";
import { Light as SyntaxHighlighter } from "react-syntax-highlighter";
import { githubGist, vs2015 } from "react-syntax-highlighter/dist/esm/styles/hljs";
interface CodeBlockProps {
content: string;
downloadFilename?: string;
height?: number | string;
language?: string;
onScroll?: () => void;
@@ -36,6 +38,7 @@ interface CodeBlockProps {
export default function CodeBlock({
content,
downloadFilename,
height,
language = "text",
onScroll,
@@ -43,6 +46,17 @@ export default function CodeBlock({
}: CodeBlockProps): React.JSX.Element {
const { mode } = useThemeMode();
const theme = useTheme();
const downloadRef = useRef<HTMLAnchorElement>(null);
useEffect(() => {
if (!downloadRef.current) {
return;
}
const url = URL.createObjectURL(new Blob([content], { type: "text/plain;charset=utf-8" }));
downloadRef.current.href = url;
return () => URL.revokeObjectURL(url);
}, [content, downloadFilename]);
return <Box sx={{ position: "relative" }}>
<Box
@@ -63,8 +77,19 @@ export default function CodeBlock({
{content}
</SyntaxHighlighter>
</Box>
{content && <Box sx={{ position: "absolute", right: 8, top: 8 }}>
{content && <Box sx={{ display: "flex", position: "absolute", right: 8, top: 8 }}>
<CopyButton text={content} />
{downloadFilename && <Tooltip title="Download">
<IconButton
aria-label="Download"
component="a"
download={downloadFilename}
ref={downloadRef}
size="small"
>
<DownloadIcon fontSize="small" />
</IconButton>
</Tooltip>}
</Box>}
</Box>;
}
@@ -33,12 +33,13 @@ import { type TabKey, tabs } from "components/package/TabKey";
import { QueryKeys } from "hooks/QueryKeys";
import { useAuth } from "hooks/useAuth";
import { useClient } from "hooks/useClient";
import { navigate, packageHref, useLocationQuery } from "hooks/useLocationQuery";
import { useNotification } from "hooks/useNotification";
import { useRepository } from "hooks/useRepository";
import type { Dependencies } from "models/Dependencies";
import type { PackageStatus } from "models/PackageStatus";
import type { Patch } from "models/Patch";
import React, { useState } from "react";
import React, { useEffect, useState } from "react";
import { StatusHeaderStyles } from "theme/StatusColors";
interface PackageInfoDialogProps {
@@ -59,11 +60,17 @@ export default function PackageInfoDialog({
const queryClient = useQueryClient();
const localPackageBase = packageBase;
const [activeTab, setActiveTab] = useState<TabKey>("logs");
const requestedTab = new URLSearchParams(useLocationQuery()).get("tab");
const activeTab = tabs.find(tab => tab.key === requestedTab)?.key ?? "logs";
const [refreshDatabase, setRefreshDatabase] = useState(true);
useEffect(() => {
if (open && requestedTab === null) {
navigate(packageHref({ tab: "logs" }));
}
}, [open, requestedTab]);
const handleClose = (): void => {
setActiveTab("logs");
setRefreshDatabase(true);
onClose();
};
@@ -167,7 +174,7 @@ export default function PackageInfoDialog({
{localPackageBase && currentRepository &&
<>
<Box sx={{ borderBottom: 1, borderColor: "divider", mt: 2 }}>
<Tabs onChange={(_, tab: TabKey) => setActiveTab(tab)} value={activeTab}>
<Tabs onChange={(_, tab: TabKey) => navigate(packageHref({ tab }))} value={activeTab}>
{tabs.map(({ key, label }) => <Tab key={key} label={label} value={key} />)}
</Tabs>
</Box>
@@ -19,12 +19,13 @@
*/
import ListIcon from "@mui/icons-material/List";
import { Box, Button, Menu, MenuItem, Typography } from "@mui/material";
import { keepPreviousData, skipToken, useQuery } from "@tanstack/react-query";
import { skipToken, useQuery } from "@tanstack/react-query";
import CodeBlock from "components/common/CodeBlock";
import { QueryKeys } from "hooks/QueryKeys";
import { useAutoScroll } from "hooks/useAutoScroll";
import { useBuildLogStream } from "hooks/useBuildLogStream";
import { useClient } from "hooks/useClient";
import { navigate, packageHref, useLocationQuery } from "hooks/useLocationQuery";
import type { LogRecord } from "models/LogRecord";
import type { RepositoryId } from "models/RepositoryId";
import React, { useEffect, useMemo, useState } from "react";
@@ -54,7 +55,8 @@ export default function BuildLogsTab({
}: BuildLogsTabProps): React.JSX.Element {
const client = useClient();
useBuildLogStream(packageBase, repository);
const [selectedVersionKey, setSelectedVersionKey] = useState<string | null>(null);
const query = new URLSearchParams(useLocationQuery());
const selectedProcessId = query.get("process_id");
const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
const { data: allLogs } = useQuery<LogRecord[]>({
@@ -70,53 +72,47 @@ export default function BuildLogsTab({
return [];
}
const grouped: Record<string, LogRecord & { minCreated: number }> = {};
const grouped = new Map<string, LogRecord & { minCreated: number }>();
for (const record of allLogs) {
const key = `${record.version}-${record.process_id}`;
const existing = grouped[key];
const key = record.process_id;
const existing = grouped.get(key);
if (!existing) {
grouped[key] = { ...record, minCreated: record.created };
grouped.set(key, { ...record, minCreated: record.created });
} else {
existing.minCreated = Math.min(existing.minCreated, record.created);
}
}
return Object.values(grouped)
return Array.from(grouped.values())
.sort((left, right) => right.minCreated - left.minCreated)
.map(record => ({
created: record.minCreated,
logs: convertLogs(
allLogs,
right => record.version === right.version && record.process_id === right.process_id,
right => record.process_id === right.process_id,
),
processId: record.process_id,
version: record.version,
}));
}, [allLogs]);
// Compute active index from selected version key, defaulting to newest (index 0)
const activeIndex = useMemo(() => {
if (selectedVersionKey) {
const index = versions.findIndex(record => `${record.version}-${record.processId}` === selectedVersionKey);
if (index >= 0) {
return index;
}
}
return 0;
}, [versions, selectedVersionKey]);
const activeVersion = versions.find(run => run.processId === selectedProcessId);
const newestProcessId = versions[0]?.processId;
const activeVersion = versions[activeIndex];
const activeVersionKey = activeVersion ? `${activeVersion.version}-${activeVersion.processId}` : null;
useEffect(() => {
if (selectedProcessId === null && newestProcessId) {
navigate(packageHref({ process_id: newestProcessId }));
}
}, [selectedProcessId, newestProcessId]);
// Refresh active version logs
const { data: versionLogs } = useQuery<LogRecord[]>({
placeholderData: keepPreviousData,
queryFn: activeVersion
? () => client.fetch.fetchPackageLogs(
packageBase, repository, activeVersion.version, activeVersion.processId,
packageBase, repository, activeVersion.processId,
)
: skipToken,
queryKey: QueryKeys.logsVersion(packageBase, repository, activeVersion?.version ?? "", activeVersion?.processId ?? ""),
queryKey: QueryKeys.logsRun(packageBase, repository, activeVersion?.processId ?? ""),
refetchOnMount: "always",
});
@@ -133,7 +129,7 @@ export default function BuildLogsTab({
// Reset scroll tracking when active version changes
useEffect(() => {
resetScroll();
}, [activeVersionKey, resetScroll]);
}, [selectedProcessId, resetScroll]);
// Scroll to bottom on new logs
useEffect(() => {
@@ -153,17 +149,18 @@ export default function BuildLogsTab({
onClose={() => setAnchorEl(null)}
open={Boolean(anchorEl)}
>
{versions.map((logs, index) =>
{versions.map(logs =>
<MenuItem
key={`${logs.version}-${logs.processId}`}
key={logs.processId}
onClick={() => {
setSelectedVersionKey(`${logs.version}-${logs.processId}`);
navigate(packageHref({ process_id: logs.processId }));
setAnchorEl(null);
resetScroll();
}}
selected={index === activeIndex}
selected={logs === activeVersion}
>
<Typography variant="body2">{new Date(logs.created * 1000).toISOStringShort()}</Typography>
<Typography variant="body2">
{logs.version} · {new Date(logs.created * 1000).toISOStringShort()}
</Typography>
</MenuItem>,
)}
{versions.length === 0 &&
@@ -175,6 +172,9 @@ export default function BuildLogsTab({
<Box sx={{ flex: 1 }}>
<CodeBlock
content={displayedLogs}
downloadFilename={activeVersion
? `${packageBase}-${activeVersion.version}-${activeVersion.processId}.log`
: undefined}
height={400}
onScroll={handleScroll}
preRef={preRef}
+14 -4
View File
@@ -17,7 +17,7 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { Box } from "@mui/material";
import { Box, MenuItem, TextField } from "@mui/material";
import { DataGrid, type GridColDef } from "@mui/x-data-grid";
import { useQuery } from "@tanstack/react-query";
import EventDurationLineChart from "components/charts/EventDurationLineChart";
@@ -26,7 +26,7 @@ import { useClient } from "hooks/useClient";
import type { Event } from "models/Event";
import type { RepositoryId } from "models/RepositoryId";
import type React from "react";
import { useMemo } from "react";
import { useMemo, useState } from "react";
import { DETAIL_TABLE_PROPS } from "utils";
interface EventsTabProps {
@@ -49,11 +49,12 @@ const columns: GridColDef<EventRow>[] = [
export default function EventsTab({ packageBase, repository }: EventsTabProps): React.JSX.Element {
const client = useClient();
const [limit, setLimit] = useState(30);
const { data: events = [] } = useQuery<Event[]>({
enabled: !!packageBase,
queryFn: () => client.fetch.fetchPackageEvents(repository, packageBase, 30),
queryKey: QueryKeys.events(repository, packageBase),
queryFn: () => client.fetch.fetchPackageEvents(repository, packageBase, limit),
queryKey: QueryKeys.events(repository, packageBase, limit),
refetchOnMount: "always",
});
@@ -65,6 +66,15 @@ export default function EventsTab({ packageBase, repository }: EventsTabProps):
})), [events]);
return <Box sx={{ mt: 1 }}>
<TextField
label="Show events"
onChange={event => setLimit(Number(event.target.value))}
select
size="small"
value={limit}
>
{[30, 100, 500].map(value => <MenuItem key={value} value={value}>Last {value} events</MenuItem>)}
</TextField>
<EventDurationLineChart events={events} />
<DataGrid columns={columns} rows={rows} {...DETAIL_TABLE_PROPS} />
</Box>;
+14 -4
View File
@@ -83,12 +83,14 @@ export default function PackageTable(): React.JSX.Element {
minWidth: 150,
renderCell: params =>
<Link
href={packageHref(currentRepository?.key ?? "", params.row.base)}
href={packageHref({ repository_id: currentRepository?.key, package: params.row.base })}
onClick={event => {
const modified = event.ctrlKey || event.metaKey || event.shiftKey || event.altKey;
if (event.button === 0 && !modified) {
event.preventDefault();
navigate(packageHref(currentRepository?.key ?? "", params.row.base));
navigate(packageHref({
repository_id: currentRepository?.key, package: params.row.base,
}));
}
}}
tabIndex={params.tabIndex}
@@ -101,13 +103,21 @@ export default function PackageTable(): React.JSX.Element {
createListColumn("packages", "packages", { flex: 1, minWidth: 120 }),
createListColumn("groups", "groups", { width: 150 }),
createListColumn("licenses", "licenses", { width: 150 }),
{ field: "packager", headerName: "packager", width: 150 },
{
field: "packager",
headerName: "packager",
type: "singleSelect",
valueOptions: [...new Set(table.rows.map(row => row.packager).filter(Boolean))].sort(),
width: 150,
},
{ align: "right", field: "timestamp", headerName: "last update", headerAlign: "right", width: 180 },
{
align: "center",
field: "status",
headerAlign: "center",
headerName: "status",
type: "singleSelect",
valueOptions: [...new Set(table.rows.map(row => row.status))].sort(),
renderCell: params =>
<StatusCell isHeld={params.row.isHeld} status={params.row.status} />,
width: 120,
@@ -136,7 +146,7 @@ export default function PackageTable(): React.JSX.Element {
],
} satisfies GridColDef<PackageRow>] : [],
],
[currentRepository, handleRemove, handleUpdate, isAuthorized],
[currentRepository, handleRemove, handleUpdate, isAuthorized, table.rows],
);
return <Box sx={{ display: "flex", flexDirection: "column", width: "100%" }}>
+1 -1
View File
@@ -34,7 +34,7 @@ export function RepositoryProvider({ children }: { children: ReactNode }): React
}, [repositories, repositoryKey]);
const setCurrentRepository = useCallback((repository: RepositoryId) => {
navigate(packageHref(repository.key, null));
navigate(packageHref({ repository_id: repository.key, package: null }));
}, []);
const value = useMemo(() => ({
+4 -3
View File
@@ -27,14 +27,15 @@ export const QueryKeys = {
dependencies: (packageBase: string, repository: RepositoryId) => ["dependencies", repository.key, packageBase] as const,
events: (repository: RepositoryId, objectId?: string) => ["events", repository.key, objectId] as const,
events: (repository: RepositoryId, objectId?: string, limit?: number) =>
["events", repository.key, objectId, limit] as const,
info: ["info"] as const,
logs: (packageBase: string, repository: RepositoryId) => ["logs", repository.key, packageBase] as const,
logsVersion: (packageBase: string, repository: RepositoryId, version: string, processId: string) =>
["logs", repository.key, packageBase, version, processId] as const,
logsRun: (packageBase: string, repository: RepositoryId, processId: string) =>
["logs", repository.key, packageBase, processId] as const,
package: (packageBase: string, repository: RepositoryId) => ["packages", repository.key, packageBase] as const,
+2 -2
View File
@@ -82,9 +82,9 @@ export function useBuildLogStream(packageBase: string, repository: RepositoryId)
existing => appendLogRecord(existing, record),
);
// Append to the version-specific cache
// Append to the run-specific cache
queryClient.setQueryData<LogRecord[]>(
["logs", repository.key, packageBase, record.version, record.process_id],
["logs", repository.key, packageBase, record.process_id],
existing => appendLogRecord(existing, record),
);
});
+10 -5
View File
@@ -32,13 +32,18 @@ export function useLocationQuery(): string {
return useSyncExternalStore(subscribe, getSnapshot);
}
export function packageHref(repositoryKey: string, packageBase: string | null): string {
export function packageHref(values: Record<string, string | null | undefined>): string {
const query = new URLSearchParams(window.location.search);
query.set("repository_id", repositoryKey);
if (packageBase) {
query.set("package", packageBase);
for (const [key, value] of Object.entries(values)) {
if (value) {
query.set(key, value);
} else {
query.delete("package");
query.delete(key);
}
}
if (values.package === null) {
query.delete("tab");
query.delete("process_id");
}
return `${window.location.pathname}?${query}`;
}
+1 -1
View File
@@ -50,7 +50,7 @@ export function useTableState(): UseTableStateResult {
const selectedPackage = currentRepository && packageBase ? packageBase : null;
const setSelectedPackage = (base: string | null): void => {
if (currentRepository) {
navigate(packageHref(currentRepository.key, base));
navigate(packageHref({ repository_id: currentRepository.key, package: base }));
}
};
const [searchText, setSearchText] = useState("");
@@ -29,7 +29,7 @@ class MethodType(StrEnum):
Attributes:
CLASS_METHOD(MethodType): (class attribute) class method
METHOD(MethodType): (class attribute) class method
METHOD(MethodType): (class attribute) instance method
"""
CLASS_METHOD = "classmethod"
METHOD = "method"