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 (75)
Showing
with 90 additions and 64 deletions
......@@ -35,10 +35,10 @@ variables:
include:
- project: 'hive/hive'
ref: a2c01ea7a46878e1b829703788a12c82b9430fc5
ref: b09d1eb5f6858b6e2ba0f4b77d4d7ce47e76e31f
file: '/scripts/ci-helpers/prepare_data_image_job.yml'
- project: 'hive/common-ci-configuration'
ref: b2ff9f5a48bc8fb379c66ec4e7907ea1e796ff1b
ref: d4e29410ea168096e1a822f77c7ce741d9cfb57a
file: '/templates/python_projects.gitlab-ci.yml'
image: ${CI_BASE_IMAGE}
......@@ -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.9'
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: # noqa: ANN401
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.")
......@@ -40,5 +40,5 @@ class AbstractClassMessagePump(AbstractClass, metaclass=MessagePumpABCMeta):
See the :class:`AbstractClass` class for more details.
"""
def __new__(cls, *args: Any, **kwargs: Any) -> Any:
def __new__(cls, *args: Any, **kwargs: Any) -> Any: # noqa: ANN401
return super().__new__(cls, AbstractClassMessagePump, *args, **kwargs)
......@@ -17,7 +17,7 @@ async def info(ctx: typer.Context) -> None: # noqa: ARG001
@beekeeper.command()
async def spawn(
background: bool = typer.Option(True, help="Run in background."),
background: bool = typer.Option(default=True, help="Run in background."), # noqa: FBT001
) -> None:
"""Spawn beekeeper process."""
from clive.__private.cli.commands.beekeeper import BeekeeperSpawn
......
......@@ -54,7 +54,7 @@ class CliveTyper(typer.Typer):
*,
name: Optional[str] = Default(None),
help: Optional[str] = Default(None), # noqa: A002
chain: bool = Default(False),
chain: bool = Default(value=False),
) -> None:
super().__init__(
name=name,
......@@ -65,7 +65,7 @@ class CliveTyper(typer.Typer):
no_args_is_help=True,
)
def __call__(self, *args: Any, **kwargs: Any) -> Any:
def __call__(self, *args: Any, **kwargs: Any) -> Any: # noqa: ANN401
try:
return super().__call__(*args, **kwargs)
except Exception as error: # noqa: BLE001
......@@ -90,7 +90,7 @@ class CliveTyper(typer.Typer):
def decorator(f: CommandFunctionType) -> CommandFunctionType:
@wraps(f)
def wrapper(*args: Any, **_kwargs: Any) -> Any:
def wrapper(*args: Any, **_kwargs: Any) -> Any: # noqa: ANN401
if len(args) > 0:
raise RuntimeError("Positional arguments are not supported")
......@@ -121,13 +121,13 @@ 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,
*,
help: Optional[str] = Default(None), # noqa: A002
invoke_without_command: bool = Default(False),
invoke_without_command: bool = Default(value=False),
result_callback: Optional[Callable[..., Any]] = Default(None),
) -> Callable[[CommandFunctionType], CommandFunctionType]:
return self.__common_decorator(
......@@ -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(
......@@ -202,7 +202,7 @@ class CliveTyper(typer.Typer):
return {"ctx": ctx, **kwargs}
@staticmethod
def __patch_command_sig(wrapper: Any, common_option: type[CommonOptionsBase]) -> None:
def __patch_command_sig(wrapper: Any, common_option: type[CommonOptionsBase]) -> None: # noqa: ANN401
sig = signature(wrapper)
new_parameters = sig.parameters.copy()
......
......@@ -35,7 +35,7 @@ class ContextualCLICommand(Generic[AsyncContextManagerType], ExternalCLICommand,
return
async def _hook_before_entering_context_manager(self) -> None:
"""Hook called before entering the context manager."""
"""Additional hook called before entering the context manager."""
return
async def run(self) -> None:
......
......@@ -12,7 +12,7 @@ class ExternalCLICommand(ABC):
@abstractmethod
async def _run(self) -> None:
"""The actual implementation of the command."""
"""Actual implementation of the command."""
async def run(self) -> None:
if not self._skip_validation:
......
......@@ -46,7 +46,7 @@ class ProcessTransferSchedule(OperationCommand):
return None
def validate_existence(
self, pair_id: int, scheduled_transfer: TransferSchedule | None, should_exists: bool
self, pair_id: int, scheduled_transfer: TransferSchedule | None, *, should_exists: bool
) -> None:
"""Validate if scheduled_transfer (recurrent transfer) exists."""
exists = scheduled_transfer is not None
......@@ -105,7 +105,7 @@ class ProcessTransferScheduleCreate(ProcessTransferSchedule):
if scheduled_transfers:
scheduled_transfer = self.get_scheduled_transfer(self.pair_id, scheduled_transfers)
self.validate_existence(self.pair_id, scheduled_transfer, False)
self.validate_existence(self.pair_id, scheduled_transfer, should_exists=False)
await super().validate_inside_context_manager()
async def validate(self) -> None:
......@@ -153,7 +153,7 @@ class ProcessTransferScheduleModify(ProcessTransferSchedule):
self.pair_id = 0 if self.pair_id is None else self.pair_id
scheduled_transfer = self.get_scheduled_transfer(self.pair_id, scheduled_transfers)
self.validate_existence(self.pair_id, scheduled_transfer, True)
self.validate_existence(self.pair_id, scheduled_transfer, should_exists=True)
self.scheduled_transfer = scheduled_transfer
await super().validate_inside_context_manager()
......@@ -191,6 +191,6 @@ class ProcessTransferScheduleRemove(ProcessTransferSchedule):
self.pair_id = 0 if self.pair_id is None else self.pair_id
scheduled_transfer = self.get_scheduled_transfer(self.pair_id, scheduled_transfers)
self.validate_existence(self.pair_id, scheduled_transfer, True)
self.validate_existence(self.pair_id, scheduled_transfer, should_exists=True)
self.scheduled_transfer = scheduled_transfer
await super().validate_inside_context_manager()
......@@ -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))):
......
......@@ -13,7 +13,7 @@ class OperationCommonOptions(CommonOptionsBase):
password: Optional[str] = options.password_optional_option
sign: Optional[str] = typer.Option(None, help="Key alias to sign the transaction with.", show_default=False)
beekeeper_remote: Optional[str] = options.beekeeper_remote_option
broadcast: bool = typer.Option(True, help="Whether broadcast the transaction. (i.e. dry-run)")
broadcast: bool = typer.Option(default=True, help="Whether broadcast the transaction. (i.e. dry-run)")
save_file: Optional[str] = typer.Option(
None,
help="The file to save the transaction to (format is determined by file extension - .bin or .json).",
......
......@@ -50,11 +50,11 @@ def _get_default_beekeeper_remote() -> str | None:
return None
def get_default_or_make_required(value: Any) -> Any:
def get_default_or_make_required(value: Any) -> Any: # noqa: ANN401
return ... if value is None else value
def modified_option(option: OptionInfo, **kwargs: Any) -> Any:
def modified_option(option: OptionInfo, **kwargs: Any) -> Any: # noqa: ANN401
"""
Create option based on another option, but with some attributes modified.
......
......@@ -43,9 +43,15 @@ def _parse_asset(raw: str, *allowed_assets: type[ParsedAssetT]) -> ParsedAssetT:
Also provides a nice error message if something is wrong with the asset input.
E.g. when Asset.LiquidT is allowed:
--amount "5.0 notexisting" -> Invalid value for '--amount': Unknown asset type: 'NOTEXISTING'. Only ['HIVE', 'HBD'] are allowed.
--amount "5.0 vests" -> Invalid value for '--amount': Only ['HIVE', 'HBD'] are allowed.
--amount "5.0000000 hive" -> Invalid value for '--amount': Invalid asset amount format: '5.0000000'. Reason: ['Invalid precision for HIVE. Must be <=3.']
--amount "5.0 notexisting"
"Invalid value for '--amount': Unknown asset type: 'NOTEXISTING'. Only ['HIVE', 'HBD'] are allowed."
--amount "5.0 vests"
"Invalid value for '--amount': Only ['HIVE', 'HBD'] are allowed."
--amount "5.0000000 hive"
"Invalid value for '--amount': Invalid asset amount format: '5.0000000'. Reason: ['Invalid precision for HIVE.
Must be <=3.']"
"""
from clive.models.asset import Asset, AssetAmountInvalidFormatError, UnknownAssetTypeError
......@@ -97,7 +103,7 @@ def decimal_percent(raw: str) -> Decimal:
@rename("text")
def smart_frequency_parser(raw: str) -> int:
"""Helper parser function for frequency flag used in transfer-schedule."""
"""Parser function for frequency flag used in transfer-schedule."""
try:
td = shorthand_timedelta_to_timedelta(raw.lower())
except ValueError as err:
......
......@@ -30,7 +30,11 @@ async def set_chain_id(
async def unset_chain_id(
ctx: typer.Context, # noqa: ARG001
) -> None:
"""Unset the actual chain ID for the profile. Will be dynamically set to the one from node get_config api when needed first time."""
"""
Unset the actual chain ID for the profile.
Will be dynamically set to the one from node get_config api when needed first time.
"""
from clive.__private.cli.commands.configure.chain_id import UnsetChainId
common = ProfileCommonOptions.get_instance()
......
......@@ -32,8 +32,8 @@ async def add_key(
async def remove_key(
ctx: typer.Context, # noqa: ARG001
alias: str = typer.Option(..., help="The key alias to remove.", show_default=False),
from_beekeeper: bool = typer.Option(
False,
from_beekeeper: bool = typer.Option( # noqa: FBT001
default=False,
help="Remove the key from the Beekeeper as well.",
),
password: str = options.password_option,
......
......@@ -6,7 +6,6 @@ from typing import TYPE_CHECKING
from click import ClickException
if TYPE_CHECKING:
from clive.__private.core.profile_data import ProfileData
......@@ -95,19 +94,28 @@ class CLIBroadcastCannotBeUsedWithForceUnsignError(CLIPrettyError):
class PowerDownInProgressError(CLIPrettyError):
def __init__(self) -> None:
message = "Power-down is already in progress, if you want to discard existing power-down and create new then use command `clive process power-down restart`"
message = (
"Power-down is already in progress, if you want to discard existing power-down and create new then use"
" command `clive process power-down restart`"
)
super().__init__(message, errno.EPERM)
class WithdrawRoutesZeroPercentError(CLIPrettyError):
def __init__(self) -> None:
message = "Withdraw routes can't have zero percent, if you want to remove withdraw route then use command `clive process withdraw-routes remove`"
message = (
"Withdraw routes can't have zero percent, if you want to remove withdraw route then use command"
" `clive process withdraw-routes remove`"
)
super().__init__(message, errno.EPERM)
class DelegationsZeroAmountError(CLIPrettyError):
def __init__(self) -> None:
message = "Delegation amount can't be zero, if you want to remove delegation then use command `clive process delegations remove`"
message = (
"Delegation amount can't be zero, if you want to remove delegation then use command"
" `clive process delegations remove`"
)
super().__init__(message, errno.EPERM)
......@@ -115,52 +123,53 @@ class ProcessTransferScheduleAlreadyExistsError(CLIPrettyError):
def __init__(self, to: str, pair_id: int) -> None:
self.to = to
self.pair_id = pair_id
self.message = (
message = (
f"Scheduled transfer to `{self.to}` with pair_id `{self.pair_id}` already exists.\n"
"Please use command `clive process transfer-schedule modify` to change it, "
"or command `clive process transfer-schedule remove` to delete it."
)
super().__init__(self.message, errno.EPERM)
super().__init__(message, errno.EPERM)
class ProcessTransferScheduleDoesNotExistsError(CLIPrettyError):
def __init__(self, to: str, pair_id: int) -> None:
self.to = to
self.pair_id = pair_id
self.message = (
message = (
f"Scheduled transfer to `{self.to}` with pair_id `{self.pair_id}` does not exists.\n"
f"Please create it first by using `clive process transfer-schedule create` command."
)
super().__init__(self.message, errno.EPERM)
super().__init__(message, errno.EPERM)
class ProcessTransferScheduleNoScheduledTransfersError(CLIPrettyError):
def __init__(self, from_account: str) -> None:
self.from_account = from_account
self.message = f"Account `{self.from_account}` has no scheduled transfers."
super().__init__(self.message, errno.EPERM)
message = f"Account `{self.from_account}` has no scheduled transfers."
super().__init__(message, errno.EPERM)
class ProcessTransferScheduleInvalidAmountError(CLIPrettyError):
def __init__(self) -> None:
self.message = (
message = (
"Amount for `clive process transfer-schedule create` or `clive process transfer-schedule modify` "
"commands must be greater than 0 HIVE/HBD.\n"
"If you want to remove scheduled transfer, please use `clive process transfer-schedule remove` command."
)
super().__init__(self.message, errno.EPERM)
super().__init__(message, errno.EPERM)
class ProcessTransferScheduleNullPairIdError(CLIPrettyError):
def __init__(self) -> None:
self.message = "Pair id must be set explicit, when there are multiple scheduled transfers defined."
super().__init__(self.message, errno.EPERM)
message = "Pair id must be set explicit, when there are multiple scheduled transfers defined."
super().__init__(message, errno.EPERM)
class ProcessTransferScheduleTooLongLifetimeError(CLIPrettyError):
def __init__(self, requested_lifetime: str) -> None:
self.requested_lifetime = requested_lifetime
self.message = (
message = (
f"Requested lifetime of scheduled transfer is too long ({self.requested_lifetime}).\n"
"Maximum available lifetime are two years."
)
super().__init__(message, errno.EPERM)
......@@ -24,7 +24,7 @@ async def process_claim_new_account_token(
show_default=False,
),
) -> None:
"""Obtains account creation token, paying either with HIVE or RC."""
"""Obtain account creation token, pay either with HIVE or RC."""
from clive.__private.cli.commands.process.process_claim_new_account_token import ProcessClaimNewAccountToken
common = OperationCommonOptions.get_instance()
......
......@@ -18,7 +18,7 @@ async def process_delegations_set(
delegatee: str = options.delegatee_account_name_option,
amount: str = options.voting_amount_option,
) -> None:
"""Adds or modifies vesting shares delegation for pair of accounts "account-name" and "delegatee"."""
"""Add or modify vesting shares delegation for pair of accounts "account-name" and "delegatee"."""
from clive.__private.cli.commands.process.process_delegations import ProcessDelegations
common = OperationCommonOptions.get_instance()
......@@ -33,7 +33,7 @@ async def process_delegations_remove(
account_name: str = options.account_name_option,
delegatee: str = options.delegatee_account_name_option,
) -> None:
"""Clears vesting shares delegation (by setting it to zero) for pair of accounts "account-name" and "delegatee"."""
"""Clear vesting shares delegation (by setting it to zero) for pair of accounts "account-name" and "delegatee"."""
from clive.__private.cli.commands.process.process_delegations import ProcessDelegationsRemove
common = OperationCommonOptions.get_instance()
......
......@@ -17,7 +17,11 @@ async def process_power_down_start(
account_name: str = options.from_account_name_option,
amount: str = options.voting_amount_option,
) -> None:
"""Start power down with given amount. If there is power down in progress displays error."""
"""
Start power down with given amount.
If there is power down in progress displays error.
"""
from clive.__private.cli.commands.process.process_power_down import ProcessPowerDownStart
common = OperationCommonOptions.get_instance()
......@@ -32,7 +36,11 @@ async def process_power_down_restart(
account_name: str = options.from_account_name_option,
amount: str = options.voting_amount_option,
) -> None:
"""Restart power down with given amount. If there is power down in progress overrides it. If there is no power down in progress creates new."""
"""
Restart power down with given amount.
If there is power down in progress overrides it. If there is no power down in progress creates new.
"""
from clive.__private.cli.commands.process.process_power_down import ProcessPowerDown
common = OperationCommonOptions.get_instance()
......@@ -46,7 +54,7 @@ async def process_power_down_cancel(
ctx: typer.Context, # noqa: ARG001
account_name: str = options.account_name_option,
) -> None:
"""Stops power down by setting amount to 0."""
"""Stop power down by setting amount to 0."""
from clive.__private.cli.commands.process.process_power_down import ProcessPowerDownCancel
common = OperationCommonOptions.get_instance()
......
......@@ -14,13 +14,13 @@ async def process_withdraw_routes_set(
from_account: str = options.from_account_name_option,
to_account: str = options.to_account_name_no_default_option,
percent: Decimal = options.percent_option,
auto_vest: bool = typer.Option(
False,
auto_vest: bool = typer.Option( # noqa: FBT001
default=False,
help="If auto-vest is set, then the amount of the Hive is immediately converted into HP on the balance. "
"With no-auto-vest there is no conversion from Hive into HP.",
),
) -> None:
"""Adds new withdraw route/modifies existing route for pair of accounts "from" and "to"."""
"""Add new withdraw route/modify existing route for pair of accounts "from" and "to"."""
from clive.__private.cli.commands.process.process_withdraw_routes import ProcessWithdrawRoutes
common = OperationCommonOptions.get_instance()
......@@ -36,7 +36,7 @@ async def process_withdraw_routes_remove(
from_account: str = options.from_account_name_option,
to_account: str = options.to_account_name_no_default_option,
) -> None:
"""Clears withdraw route for pair of accounts "from" and "to"."""
"""Clear withdraw route for pair of accounts "from" and "to"."""
from clive.__private.cli.commands.process.process_withdraw_routes import ProcessWithdrawRoutesRemove
common = OperationCommonOptions.get_instance()
......
......@@ -65,7 +65,7 @@ else:
async def process_transaction(
ctx: typer.Context, # noqa: ARG001
from_file: str = typer.Option(..., help="The file to load the transaction from.", show_default=False),
force_unsign: bool = typer.Option(False, help="Whether to force unsigning the transaction."),
force_unsign: bool = typer.Option(default=False, help="Whether to force unsigning the transaction."), # noqa: FBT001
already_signed_mode: AlreadySignedModeEnum = typer.Option(
ALREADY_SIGNED_MODE_DEFAULT, help="How to handle the situation when transaction is already signed."
),
......@@ -96,7 +96,7 @@ async def process_update_memo_key(
show_default=False,
),
) -> None:
"""Sets memo key."""
"""Set memo key."""
from clive.__private.cli.commands.process.process_account_update import ProcessAccountUpdate, set_memo_key
update_memo_key_callback = partial(set_memo_key, key=memo_key)
......