Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • hive/clive
1 result
Show changes
Commits on Source (27)
Showing
with 60 additions and 59 deletions
......@@ -57,9 +57,12 @@ lint_code_with_ruff:
stage: static_code_analysis
extends: .lint_code_with_ruff_template
formatting_with_black_check:
formatting_with_ruff_check:
stage: static_code_analysis
extends: .formatting_with_black_check_template
extends: .project_develop_configuration_template
script:
- echo -e "${TXT_BLUE}Checking code formatting with Ruff...${TXT_CLEAR}" &&
ruff format --check --diff ${PACKAGES_TO_CHECK}
type_check_with_mypy:
stage: static_code_analysis
......
......@@ -43,16 +43,13 @@ repos:
- stylelint-config-standard-scss@13.0.0
args: [ "--fix" ]
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: 'v0.2.2'
rev: 'v0.4.8'
hooks:
- id: ruff
name: linting code with Ruff
args: [ "--fix" ]
- repo: https://github.com/psf/black-pre-commit-mirror
rev: 24.2.0
hooks:
- id: black
name: format code using black
- id: ruff-format
name: format code using Ruff formatter
- repo: local
hooks:
- id: mypy
......
......@@ -13,7 +13,7 @@ class AbstractClass(ABC): # noqa: B024
Even when no abstract methods were defined, this class cannot be instantiated. (default ABC allows for that).
"""
def __new__(cls, abstract_type: type[AbstractClass] | None = None, *args, **kwargs) -> Any: # type: ignore
def __new__(cls, abstract_type: type[AbstractClass] | None = None, *args: Any, **kwargs: Any) -> Any:
abstract_type = AbstractClass if abstract_type is None else abstract_type
if abstract_type in cls.__bases__:
raise TypeError(f"Abstract class `{cls.__name__}` cannot be instantiated.")
......
......@@ -121,7 +121,7 @@ class CliveTyper(typer.Typer):
super().command, name=name, common_options=common_options, help=help, epilog=epilog
)
def callback( # type: ignore[override]
def callback( # type: ignore[override] # noqa: PLR0913
self,
name: Optional[str] = Default(None),
common_options: list[type[CommonOptionsBase]] | None = None,
......@@ -154,7 +154,7 @@ class CliveTyper(typer.Typer):
# If ClickException was raised in the registered error handler, we need to format it like Typer does.
rich_utils.rich_format_error(error)
sys.exit(error.exit_code)
except Exception as error:
except Exception as error: # noqa: BLE001
# See: `typer/mian.py` -> `Typer.__call__` -> `except Exception as e:`
# If any other exception was raised in the registered error handler, we need to format it like Typer does.
setattr(
......
......@@ -147,7 +147,6 @@ class ShowTransferSchedule(WorldBasedCommand):
data: NodeData,
deepth: int = DEFAULT_FUTURE_DEEPTH,
) -> FutureScheduledTransfers:
future_scheduled_transfers: FutureScheduledTransfers = []
for scheduled_transfer in scheduled_transfers:
for idx, remains in enumerate(range(min(scheduled_transfer.remaining_executions, deepth))):
......
......@@ -6,7 +6,6 @@ from typing import TYPE_CHECKING
from click import ClickException
if TYPE_CHECKING:
from clive.__private.core.profile_data import ProfileData
......
......@@ -34,7 +34,7 @@ transfer_schedule = CliveTyper(name="transfer-schedule", help="Create, modify or
@transfer_schedule.command(name="create", common_options=[TransferScheduleCommonOptions, OperationCommonOptions])
async def process_transfer_schedule_create(
async def process_transfer_schedule_create( # noqa: PLR0913
ctx: typer.Context, # noqa: ARG001
amount: str = liquid_amount_option,
repeat: int = repeat_value_option,
......@@ -55,12 +55,12 @@ async def process_transfer_schedule_create(
repeat=repeat,
frequency=frequency,
memo=memo,
pair_id=pair_id
pair_id=pair_id,
).run()
@transfer_schedule.command(name="modify", common_options=[TransferScheduleCommonOptions, OperationCommonOptions])
async def process_transfer_schedule_modify(
async def process_transfer_schedule_modify( # noqa: PLR0913
ctx: typer.Context, # noqa: ARG001
amount: str = liquid_amount_optional_option,
repeat: Optional[int] = repeat_value_optional_option,
......@@ -80,13 +80,14 @@ async def process_transfer_schedule_modify(
repeat=repeat,
frequency=frequency,
memo=memo,
pair_id=pair_id
pair_id=pair_id,
).run()
@transfer_schedule.command(name="remove", common_options=[TransferScheduleCommonOptions, OperationCommonOptions])
async def process_transfer_schedule_remove(
ctx: typer.Context, pair_id: Optional[int] = pair_id_value_none_option # noqa: ARG001
ctx: typer.Context, # noqa: ARG001
pair_id: Optional[int] = pair_id_value_none_option,
) -> None:
"""Remove an existing recurrent transfer."""
from clive.__private.cli.commands.process.process_transfer_schedule import ProcessTransferScheduleRemove
......
......@@ -159,7 +159,7 @@ async def show_witness(
@show.command(name="proposals", common_options=[WorldWithoutBeekeeperCommonOptions])
async def show_proposals(
async def show_proposals( # noqa: PLR0913
ctx: typer.Context, # noqa: ARG001
account_name: str = options.account_name_option,
order_by: OrdersEnum = typer.Option(
......@@ -225,7 +225,8 @@ async def show_proposal(
@show.command(name="owner-authority", common_options=[WorldWithoutBeekeeperCommonOptions])
async def show_owner_authority(
ctx: typer.Context, account_name: str = options.account_name_option # noqa: ARG001
ctx: typer.Context, # noqa: ARG001
account_name: str = options.account_name_option,
) -> None:
"""Fetch from blockchain and display owner authority of selected account."""
from clive.__private.cli.commands.show.show_authority import ShowAuthority
......@@ -236,7 +237,8 @@ async def show_owner_authority(
@show.command(name="active-authority", common_options=[WorldWithoutBeekeeperCommonOptions])
async def show_active_authority(
ctx: typer.Context, account_name: str = options.account_name_option # noqa: ARG001
ctx: typer.Context, # noqa: ARG001
account_name: str = options.account_name_option,
) -> None:
"""Fetch from blockchain and display active authority of selected account."""
from clive.__private.cli.commands.show.show_authority import ShowAuthority
......@@ -247,7 +249,8 @@ async def show_active_authority(
@show.command(name="posting-authority", common_options=[WorldWithoutBeekeeperCommonOptions])
async def show_posting_authority(
ctx: typer.Context, account_name: str = options.account_name_option # noqa: ARG001
ctx: typer.Context, # noqa: ARG001
account_name: str = options.account_name_option,
) -> None:
"""Fetch from blockchain and display posting authority of selected account."""
from clive.__private.cli.commands.show.show_authority import ShowAuthority
......@@ -288,7 +291,8 @@ async def show_hive_power(
@show.command(name="new-account-token", common_options=[WorldWithoutBeekeeperCommonOptions])
async def show_new_account_token(
ctx: typer.Context, account_name: str = options.account_name_option # noqa: ARG001
ctx: typer.Context, # noqa: ARG001
account_name: str = options.account_name_option,
) -> None:
"""Shows number of possessed tokens for account creation. To get account creation fee use command clive show chain."""
from clive.__private.cli.commands.show.show_new_account_token import ShowNewAccountToken
......
......@@ -4,11 +4,11 @@ from datetime import datetime
from pathlib import Path
from typing import Final
from dynaconf import Dynaconf # type: ignore
from dynaconf import Dynaconf # type: ignore[import-untyped]
ROOT_DIRECTORY: Final[Path] = Path(__file__).parent.parent
TESTS_DIRECTORY: Final[Path] = ROOT_DIRECTORY.parent / "tests"
LAUNCH_TIME: Final[datetime] = datetime.now()
LAUNCH_TIME: Final[datetime] = datetime.now() # noqa: DTZ005; we want to use the local timezone
_DATA_DIRECTORY: Final[Path] = Path.home() / ".clive"
# order matters - later paths override earlier values for the same key of earlier paths
......
......@@ -5,7 +5,7 @@ from datetime import datetime
from typing import TYPE_CHECKING, ClassVar
from clive.__private.core.alarms.alarm import Alarm, BaseAlarmData
from clive.__private.core.formatters.humanize import _is_null_date
from clive.__private.core.date_utils import is_null_date
if TYPE_CHECKING:
from clive.__private.core.commands.data_retrieval.update_alarms_data import AccountAlarmsData
......@@ -35,7 +35,7 @@ class GovernanceNoActiveVotes(Alarm[datetime, GovernanceNoActiveVotesAlarmData])
def update_alarm_status(self, data: AccountAlarmsData) -> None:
expiration = data.governance_vote_expiration_ts
if _is_null_date(expiration):
if is_null_date(expiration):
new_identifier = expiration
self.enable_alarm(new_identifier, GovernanceNoActiveVotesAlarmData(expiration_date=expiration))
return
......
......@@ -5,7 +5,8 @@ from datetime import datetime, timezone
from typing import TYPE_CHECKING, ClassVar, Final
from clive.__private.core.alarms.alarm import Alarm, BaseAlarmData
from clive.__private.core.formatters.humanize import _is_null_date, humanize_datetime
from clive.__private.core.date_utils import is_null_date
from clive.__private.core.formatters.humanize import humanize_datetime
if TYPE_CHECKING:
from clive.__private.core.commands.data_retrieval.update_alarms_data import AccountAlarmsData
......@@ -45,7 +46,7 @@ class GovernanceVotingExpiration(Alarm[datetime, GovernanceVotingExpirationAlarm
def update_alarm_status(self, data: AccountAlarmsData) -> None:
expiration: datetime = data.governance_vote_expiration_ts
if _is_null_date(expiration):
if is_null_date(expiration):
self.disable_alarm()
return
......
......@@ -29,7 +29,7 @@ def api(foo: FooT) -> FooT:
)
).result
return impl # type: ignore
return impl # type: ignore[return-value]
class BeekeeperApi:
......
......@@ -23,7 +23,7 @@ class InvalidOptionError(CliveError):
def webserver_default() -> Url:
return Url("http", "0.0.0.0", 0)
return Url("http", "127.0.0.1", 0)
def _wallet_dir_default() -> Path:
......
......@@ -32,7 +32,7 @@ class BeekeeperExecutable:
run_in_background: bool = False,
) -> None:
self.__config = config
self.__executable: Path = self.get_path_from_settings() # type: ignore
self.__executable: Path = self.get_path_from_settings() # type: ignore[assignment]
if self.__executable is None:
raise BeekeeperNotConfiguredError
......
......@@ -85,7 +85,8 @@ class BeekeeperNotificationsServer:
@classmethod
def __parse_endpoint_notification(cls, details: dict[str, str]) -> Url:
return Url.parse(
f"{details['address'].replace('0.0.0.0', '127.0.0.1')}:{details['port']}", protocol=details["type"].lower()
f"{details['address']}:{details['port']}",
protocol=details["type"].lower(),
)
async def close(self) -> None:
......
......@@ -12,7 +12,6 @@ class CommandDataRetrieval(
CommandDataRetrievalBase[HarvestedDataT, SanitizedDataT, CommandResultT],
CommandWithResult[CommandResultT],
):
async def _execute(self) -> None:
result = await super()._perform_data_operations()
self._result = result
......@@ -22,7 +22,7 @@ class FindScheduledTransfersFromAccountMismatchError(FindScheduledTransfersError
account_name: str
transfer_schedule: TransferSchedule
def __init__(self, command: Command, account_name: str, transfer_schedule: TransferSchedule):
def __init__(self, command: Command, account_name: str, transfer_schedule: TransferSchedule) -> None:
self.account_name = account_name
self.transfer_schedule = transfer_schedule
self.reason = f"Wrong from account '{self.transfer_schedule.from_}' should be '{self.account_name}'."
......
......@@ -3,11 +3,12 @@ from __future__ import annotations
import re
from collections import defaultdict
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from datetime import datetime, timedelta
from typing import TYPE_CHECKING, Final
from clive.__private.core.calcluate_hive_power import calculate_hive_power
from clive.__private.core.commands.abc.command_data_retrieval import CommandDataRetrieval
from clive.__private.core.date_utils import utc_epoch, utc_now
from clive.__private.core.hive_vests_conversions import vests_to_hive
from clive.__private.core.iwax import (
calculate_current_manabar_value,
......@@ -37,10 +38,6 @@ if TYPE_CHECKING:
from schemas.fields.compound import Manabar
def _get_utc_epoch() -> datetime:
return datetime.fromtimestamp(0, timezone.utc)
class SuppressNotExistingApis:
_API_NOT_FOUND_REGEX: Final[str] = (
r"'Assert Exception:api_itr != data\._registered_apis\.end\(\): Could not find API (\w+_api)'"
......@@ -82,7 +79,7 @@ class _AccountSanitizedData:
@dataclass
class _AccountProcessedData:
core: SchemasAccount
last_history_entry: datetime = field(default_factory=lambda: _get_utc_epoch())
last_history_entry: datetime = field(default_factory=lambda: utc_epoch())
"""Could be missing if account_history_api is not available"""
rc: RcAccount | None = None
"""Could be missing if rc_api is not available"""
......@@ -135,15 +132,15 @@ class UpdateNodeData(CommandDataRetrieval[HarvestedDataRaw, SanitizedData, Dynam
account_harvested_data = harvested_data.account_harvested_data
for account in self.accounts:
account_harvested_data[account].account_history = (
await node.api.account_history_api.get_account_history(
account=account.name,
limit=1,
operation_filter_low=non_virtual_operations_filter,
include_reversible=True,
)
account_history = await node.api.account_history_api.get_account_history(
account=account.name,
limit=1,
operation_filter_low=non_virtual_operations_filter,
include_reversible=True,
)
account_harvested_data[account].account_history = account_history
return harvested_data
async def _sanitize_data(self, data: HarvestedDataRaw) -> SanitizedData:
......@@ -189,7 +186,7 @@ class UpdateNodeData(CommandDataRetrieval[HarvestedDataRaw, SanitizedData, Dynam
hp_balance=calculate_hive_power(gdpo, self._calculate_vests_balance(info.core)),
proxy=info.core.proxy,
hp_unclaimed=info.core.reward_vesting_balance,
last_refresh=self.__normalize_datetime(datetime.utcnow()),
last_refresh=utc_now(),
last_history_entry=info.last_history_entry,
last_account_update=info.core.last_account_update,
recovery_account=info.core.recovery_account,
......@@ -211,8 +208,8 @@ class UpdateNodeData(CommandDataRetrieval[HarvestedDataRaw, SanitizedData, Dynam
def __get_account_last_history_entry(self, data: GetAccountHistory | None) -> datetime:
if data is None:
return _get_utc_epoch()
return self.__normalize_datetime(data.history[0][1].timestamp)
return utc_epoch()
return data.history[0][1].timestamp
def _calculate_vests_balance(self, account: SchemasAccount) -> int:
return (
......@@ -259,10 +256,6 @@ class UpdateNodeData(CommandDataRetrieval[HarvestedDataRaw, SanitizedData, Dynam
- gdpo_time
)
@staticmethod
def __normalize_datetime(date: datetime) -> datetime:
return date.replace(microsecond=0, tzinfo=timezone.utc)
def __get_account(self, name: str) -> Account:
return next(filter(lambda account: account.name == name, self.accounts))
......
......@@ -2,10 +2,12 @@ from __future__ import annotations
from collections import OrderedDict
from dataclasses import dataclass, field
from datetime import datetime
from typing import TYPE_CHECKING, ClassVar, Literal, TypeAlias
from clive.__private.core.commands.abc.command_data_retrieval import CommandDataRetrieval
from clive.__private.core.commands.abc.command_data_retrieval import (
CommandDataRetrieval,
)
from clive.__private.core.date_utils import utc_epoch
from clive.__private.core.formatters.humanize import (
humanize_datetime,
humanize_hbd_exchange_rate,
......@@ -13,6 +15,8 @@ from clive.__private.core.formatters.humanize import (
)
if TYPE_CHECKING:
from datetime import datetime
from clive.__private.core.node import Node
from clive.models.aliased import DynamicGlobalProperties, Witness, WitnessesList, WitnessVotes
......@@ -20,7 +24,7 @@ if TYPE_CHECKING:
@dataclass
class WitnessData:
name: str
created: datetime = field(default_factory=lambda: datetime.fromtimestamp(0))
created: datetime = field(default_factory=utc_epoch)
voted: bool = False
votes: str = "?"
rank: int | None = None
......
......@@ -16,7 +16,7 @@ class IsPasswordValidCommandError(CommandError):
class WalletNotFoundError(IsPasswordValidCommandError):
def __init__(self, command: IsPasswordValid, wallet_name: str):
def __init__(self, command: IsPasswordValid, wallet_name: str) -> None:
super().__init__(command, f"Wallet `{wallet_name}` not found on the beekeeper.")
......