Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
# croco-cli

[![Croco Logo](https://i.ibb.co/G5Pjt6M/logo.png)](https://t.me/crocofactory)
[![Croco Logo](https://i.ibb.co/G5Pjt6M/logo.png)](https://t.me/crocofactory)

[![PyPi version](https://img.shields.io/pypi/v/croco-cli)](https://pypi.org/project/croco-cli/)
[![PyPI Downloads](https://img.shields.io/pypi/dm/croco-cli)](https://pypi.org/project/croco-cli/)
[![License](https://img.shields.io/github/license/blnkoff/croco-cli.svg)](https://pypi.org/project/croco-cli/)
[![Last Commit](https://img.shields.io/github/last-commit/blnkoff/croco-cli.svg)](https://pypi.org/project/croco-cli/)
[![Development Status](https://img.shields.io/pypi/status/croco-cli)](https://pypi.org/project/croco-cli/)


The CLI for developing Web3-based projects in Croco Factory

Expand All @@ -19,6 +26,8 @@ Command `croco` display this in your console.
Let`s learn them:

- `change` - if you already have set multiple accounts, using `set` you can change current
- `export` - Export cli configuration
- `import` - Import cli configuration
- `init` - if you created you project or pacakge just now, you can initialize it, using template structure
- `install` - install Croco Factory packages. If package is placed in private GitHub repository, you need to have access
token with permission of downloading this package
Expand Down
117 changes: 81 additions & 36 deletions croco_cli/database.py → croco_cli/_database.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,46 +2,61 @@
This module provides a database interface
"""
import json
import sys
import os
import pickle
import getpass
from eth_account import Account
from github import Auth
from github import Github
from github import Auth, BadCredentialsException, Github
from typing import Type, Optional, ClassVar
from croco_cli.types import GithubUser, Wallet, CustomAccount, EnvVariable
from eth_utils.exceptions import ValidationError
from croco_cli.exceptions import InvalidToken, InvalidMnemonic
from croco_cli.types import GithubUser, Wallet, CustomAccount, EnvVar
from peewee import Model, CharField, BlobField, SqliteDatabase, BooleanField


class _DatabaseMeta(type):
_instance = None

def __call__(cls, *args, **kwargs):
if not isinstance(cls._instance, cls):
cls._instance = super().__call__(*args, **kwargs)

return cls._instance


def _get_cache_folder() -> str:
"""
Get the cache folder path based on the operating system.

:return: Cache folder path.
"""
username = getpass.getuser()
os_name = os.name

venv_path = sys.prefix

parent_path = venv_path[:venv_path.rfind('/')]
folder = os.path.basename(parent_path)

if os_name == "posix":
cache_path = f'/Users/{username}/.cache/croco_cli'
cache_folder = f'/Users/{username}/.croco_cli'
elif os_name == "nt":
cache_path = f'C:\\Users\\{username}\\AppData\\Local\\croco_cli'
cache_folder = f'C:/Users/{username}/AppData/Local/croco_cli'
else:
raise OSError(f"Unsupported Operating System {os_name}")

try:
if not os.path.exists(cache_folder):
os.mkdir(cache_folder)

cache_path = os.path.join(cache_folder, folder)

if not os.path.exists(cache_path):
os.mkdir(cache_path)
except FileExistsError:
pass

return cache_path


class _DatabaseMeta(type):
_instance = None

def __call__(cls, *args, **kwargs):
if not isinstance(cls._instance, cls):
cls._instance = super().__call__(*args, **kwargs)

return cls._instance


class Database(metaclass=_DatabaseMeta):
_path: ClassVar[str] = os.path.join(_get_cache_folder(), 'user.db')
interface: ClassVar[SqliteDatabase] = SqliteDatabase(_path)
Expand Down Expand Up @@ -129,15 +144,19 @@ def drop_database(self) -> None:
"""
self.interface.drop_tables([self.github_users, self.wallets, self.custom_accounts, self.env_variables])

def get_wallets(self) -> list[Wallet] | None:
def get_wallets(self, current: bool = False) -> list[Wallet] | None:
"""
Returns a list of all ethereum wallets of the user
:return: a list of all ethereum wallets of the user
"""
query = self.wallets.select()
if not self.wallets.table_exists():
return None

if not current:
query = self.wallets.select()
else:
query = self.wallets.select().where(self._wallets.current)

wallets = [
Wallet(
public_key=wallet.public_key,
Expand All @@ -148,7 +167,7 @@ def get_wallets(self) -> list[Wallet] | None:
)
for wallet in query
]
return wallets
return wallets if wallets else None

def get_github_user(self) -> GithubUser | None:
"""
Expand Down Expand Up @@ -183,13 +202,16 @@ def set_github_user(self, token: str) -> None:
_auth = Auth.Token(token)

with Github(auth=_auth) as github_api:
user = github_api.get_user()
_emails = user.get_emails()
try:
user = github_api.get_user()
_emails = user.get_emails()

for email in _emails:
if email.primary:
user_email = email.email
break
for email in _emails:
if email.primary:
user_email = email.email
break
except BadCredentialsException:
raise InvalidToken

github_users.create(
data=pickle.dumps(user),
Expand Down Expand Up @@ -218,6 +240,16 @@ def get_public_key(private_key: str) -> str:
public_key = account.address
return public_key

@staticmethod
def _get_private_key(mnemonic: str) -> str:
try:
Account.enable_unaudited_hdwallet_features()
account = Account.from_mnemonic(mnemonic)
private_key = account.key.hex()
return private_key
except ValidationError:
raise InvalidMnemonic

def set_wallet(
self,
private_key: str,
Expand All @@ -234,8 +266,14 @@ def set_wallet(
wallets = self._wallets
database = self.interface

if label == 'None':
label = None

database.create_tables([wallets])

if mnemonic and private_key != self._get_private_key(mnemonic):
raise InvalidMnemonic

existing_wallets = wallets.select().where(wallets.private_key == private_key)

current_wallets = wallets.select().where(wallets.current)
Expand Down Expand Up @@ -291,11 +329,12 @@ def get_custom_accounts(
current=account.current,
email=account.email,
email_password=account.email_password,
data=account.data
data=json.loads(account.data)
)
for account in query
]
return accounts

return accounts if accounts else None

def set_custom_account(
self,
Expand Down Expand Up @@ -344,19 +383,25 @@ def set_custom_account(
data=json.dumps(data)
)

def delete_custom_accounts(self, account: str, email: str) -> None:
def delete_custom_accounts(self, account: str, email: Optional[str] = None) -> None:
"""
Delete custom user accounts
:param account: A name of accounts
:param email: Email of accounts
:return: None
"""
custom_accounts = self._custom_accounts
custom_accounts.delete().where(
custom_accounts.account == account and custom_accounts.email == email
).execute()

def set_env_variable(
if email:
custom_accounts.delete().where(
custom_accounts.account == account and custom_accounts.email == email
).execute()
else:
custom_accounts.delete().where(
custom_accounts.account == account
).execute()

def set_envar(
self,
key: str,
value: str
Expand All @@ -375,15 +420,15 @@ def set_env_variable(
value=value
)

def get_env_variables(self) -> list[EnvVariable] | None:
def get_env_variables(self) -> list[EnvVar] | None:
env_variables = self._env_variables
if not env_variables.table_exists():
return

query = env_variables.select()

return [
EnvVariable(
EnvVar(
key=env_variable.key,
value=env_variable.value
)
Expand Down
2 changes: 1 addition & 1 deletion croco_cli/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
This sub-package provides command-line interface
"""

from .cli import cli
from ._cli import cli
65 changes: 54 additions & 11 deletions croco_cli/cli/change.py → croco_cli/cli/_change.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import click
from croco_cli.database import Database
from croco_cli.types import Option, Wallet, CustomAccount
from croco_cli.utils import show_key_mode, sort_wallets, echo_error, make_screen_option
from croco_cli._database import Database
from croco_cli.tools.keymode import KeyMode
from croco_cli.tools.option import Option
from croco_cli.types import CustomAccount
from croco_cli.utils import Wallet
from croco_cli.utils import sort_wallets
from croco_cli.croco_echo import CrocoEcho


@click.group()
Expand All @@ -19,6 +23,26 @@ def _handler():

def _deleting_handler():
database.delete_wallet(wallet['private_key'])
wallets = database.get_wallets()

if wallets:
try:
last_wallet = database.get_wallets()[-1]
current_wallet = filter(lambda x: x['current'], wallets)

try:
current_wallet = next(current_wallet)
except StopIteration:
current_wallet = None

if not current_wallet:
database.set_wallet(
last_wallet['private_key'],
last_wallet['label'],
last_wallet['mnemonic']
)
except IndexError:
pass

if wallet["current"]:
label = f'{label} (Current)'
Expand All @@ -45,6 +69,24 @@ def _handler():
def _deleting_handler():
database.delete_custom_accounts(account['account'], account['email'])

custom_accounts = database.get_custom_accounts(account['account'])

if custom_accounts:
try:
last_custom_account = custom_accounts[-1]
current_account = filter(lambda x: x['current'], custom_accounts)

try:
current_account = next(current_account)
except StopIteration:
current_account = None

if not current_account:
last_custom_account.pop('current')
database.set_custom_account(**last_custom_account)
except IndexError:
pass

if account["current"]:
label = f'{label} (Current)'

Expand All @@ -67,13 +109,14 @@ def _wallet():
wallets = database.get_wallets()

if len(wallets) < 2:
echo_error('There are no wallets in the database to change.')
CrocoEcho.error('There are no wallets in the database to change.')
return

wallets = sort_wallets(wallets)

options = [_make_wallet_option(wallet) for wallet in wallets]
show_key_mode(options, 'Change wallet for unit tests')
keymode = KeyMode(options, 'Change wallet for unit tests')
keymode()


@change.command()
Expand All @@ -84,7 +127,7 @@ def custom():

custom_accounts = database.get_custom_accounts()
if not custom_accounts or not len(custom_accounts):
echo_error('There are no custom accounts in the database to change.')
CrocoEcho.error('There are no custom accounts in the database to change.')
return

for account in custom_accounts:
Expand All @@ -103,11 +146,10 @@ def custom():
description = f'Change {key.capitalize()} account'

def deleting_handler():
custom_accounts = database.custom_accounts
custom_accounts.delete().where(custom_accounts.account == key).execute()
database.delete_custom_accounts(key)

screen_options.append(
make_screen_option(
KeyMode.screen_option(
key.capitalize(),
description,
account_options,
Expand All @@ -116,7 +158,8 @@ def deleting_handler():
)

if not len(screen_options):
echo_error('There are no custom accounts in the database to change.')
CrocoEcho.error('There are no custom accounts in the database to change.')
return

show_key_mode(screen_options, 'Change custom account')
keymode = KeyMode(screen_options, 'Change custom account')
keymode()
Loading