Skip to content

Commit

Permalink
black all code, compat OrderBy for django 3.0
Browse files Browse the repository at this point in the history
  • Loading branch information
voidZXL committed Dec 10, 2024
1 parent 476c70f commit 42733d2
Show file tree
Hide file tree
Showing 183 changed files with 10,207 additions and 6,867 deletions.
22 changes: 12 additions & 10 deletions utilmeta/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
__website__ = 'https://utilmeta.com'
__homepage__ = 'https://utilmeta.com/py'
__author__ = 'Xulin Zhou (@voidZXL)'
__version__ = '2.7.0'
__website__ = "https://utilmeta.com"
__homepage__ = "https://utilmeta.com/py"
__author__ = "Xulin Zhou (@voidZXL)"
__version__ = "2.7.0"


def version_info() -> str:
Expand All @@ -10,12 +10,14 @@ def version_info() -> str:
from pathlib import Path

info = {
'utilmeta version': __version__,
'installed path': Path(__file__).resolve().parent,
'python version': sys.version,
'platform': platform.platform(),
"utilmeta version": __version__,
"installed path": Path(__file__).resolve().parent,
"python version": sys.version,
"platform": platform.platform(),
}
return '\n'.join('{:>30} {}'.format(k + ':', str(v).replace('\n', ' ')) for k, v in info.items())
return "\n".join(
"{:>30} {}".format(k + ":", str(v).replace("\n", " ")) for k, v in info.items()
)


def init_settings():
Expand All @@ -35,6 +37,6 @@ def init_settings():

from .core.server.service import UtilMeta

service: 'UtilMeta' # current service in this process
service: "UtilMeta" # current service in this process

_cmd_env = False
139 changes: 75 additions & 64 deletions utilmeta/bin/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from functools import partial


__all__ = ['command', 'Arg', 'BaseCommand']
__all__ = ["command", "Arg", "BaseCommand"]


def command(name: str = None, *aliases, options: Options = None):
Expand All @@ -27,50 +27,52 @@ def wrapper(f):
f.__command__ = f.__name__ if name is None else name
f.__aliases__ = aliases
return f

return wrapper


class Arg(Field):
def __init__(self,
alias: str = None,
alias_from: Union[str, List[str], Callable, List[Callable]] = None,
*,
required: bool = False,
default=None,
default_factory: Callable = None,
case_insensitive: bool = None,
mode: str = None,
deprecated: Union[bool, str] = False,
discriminator=None, # discriminate the schema union by it's field
no_input: Union[bool, str, Callable] = False,
on_error: Literal["exclude", "preserve", "throw"] = None, # follow the options
dependencies: Union[list, str, property] = None,
# --- ANNOTATES ---
title: str = None,
description: str = None,
example=unprovided,
# --- CONSTRAINTS ---
const=unprovided,
enum: Iterable = None,
gt=None,
ge=None,
lt=None,
le=None,
regex: str = None,
length: Union[int, ConstraintMode] = None,
max_length: Union[int, ConstraintMode] = None,
min_length: int = None,
# number
max_digits: Union[int, ConstraintMode] = None,
decimal_places: Union[int, ConstraintMode] = None,
round: int = None,
multiple_of: Union[int, ConstraintMode] = None,
# array
contains: type = None,
max_contains: int = None,
min_contains: int = None,
unique_items: Union[bool, ConstraintMode] = None,
):
def __init__(
self,
alias: str = None,
alias_from: Union[str, List[str], Callable, List[Callable]] = None,
*,
required: bool = False,
default=None,
default_factory: Callable = None,
case_insensitive: bool = None,
mode: str = None,
deprecated: Union[bool, str] = False,
discriminator=None, # discriminate the schema union by it's field
no_input: Union[bool, str, Callable] = False,
on_error: Literal["exclude", "preserve", "throw"] = None, # follow the options
dependencies: Union[list, str, property] = None,
# --- ANNOTATES ---
title: str = None,
description: str = None,
example=unprovided,
# --- CONSTRAINTS ---
const=unprovided,
enum: Iterable = None,
gt=None,
ge=None,
lt=None,
le=None,
regex: str = None,
length: Union[int, ConstraintMode] = None,
max_length: Union[int, ConstraintMode] = None,
min_length: int = None,
# number
max_digits: Union[int, ConstraintMode] = None,
decimal_places: Union[int, ConstraintMode] = None,
round: int = None,
multiple_of: Union[int, ConstraintMode] = None,
# array
contains: type = None,
max_contains: int = None,
min_contains: int = None,
unique_items: Union[bool, ConstraintMode] = None,
):
if required:
default = default_factory = unprovided
kwargs = dict(locals())
Expand All @@ -80,7 +82,7 @@ def __init__(self,


class BaseCommand:
_commands: Dict[str, Union[Type['BaseCommand'], Callable]] = {}
_commands: Dict[str, Union[Type["BaseCommand"], Callable]] = {}
_documents: Dict[str, str] = {}
_aliases: Dict[str, str] = {}

Expand All @@ -101,7 +103,7 @@ def __init_subclass__(cls, **kwargs):
documents = {}
aliases = {}

for base in reversed(cls.__bases__): # mro
for base in reversed(cls.__bases__): # mro
if issubclass(base, BaseCommand):
commands.update(base._commands)
documents.update(base._documents)
Expand All @@ -111,13 +113,13 @@ def __init_subclass__(cls, **kwargs):
if isinstance(cmd, type) and issubclass(cmd, BaseCommand):
commands[name] = cmd
cmd_documents = cmd._documents
documents[name] = get_doc(cmd) or cmd_documents.get('')
documents[name] = get_doc(cmd) or cmd_documents.get("")

for name, func in cls.__dict__.items():
name: str
if name in commands:
continue
if name.startswith('_'):
if name.startswith("_"):
continue
cls_func = False
if isinstance(func, classmethod):
Expand All @@ -126,10 +128,10 @@ def __init_subclass__(cls, **kwargs):
# func.__classmethod__ = True
if not inspect.isfunction(func):
continue
command_name = getattr(func, '__command__', None)
command_name = getattr(func, "__command__", None)
if command_name is None:
continue
command_aliases = getattr(func, '__aliases__', [])
command_aliases = getattr(func, "__aliases__", [])
documents[command_name] = get_doc(func)
# if cls_func:
# func = partial(func, cls)
Expand All @@ -150,15 +152,15 @@ def __init__(self, *argv: str, cwd: str):
if argv:
self.arg_name, *self.args = argv
else:
self.arg_name = ''
self.arg_name = ""
self.args = []

def get_command_cls(self, name: str) -> Union[Type['BaseCommand'], Callable]:
def get_command_cls(self, name: str) -> Union[Type["BaseCommand"], Callable]:
alias = self._aliases.get(name, name)
return self._commands.get(alias)

def command_not_found(self):
print(RED % F'{self.script_name or "meta"}: command not found: {self.arg_name}')
print(RED % f'{self.script_name or "meta"}: command not found: {self.arg_name}')
exit(1)

def __call__(self, **kwargs):
Expand All @@ -180,13 +182,15 @@ def __call__(self, **kwargs):
return
elif self.name:
# subclasses
root_cmd = self.get_command_cls('')
root_cmd = self.get_command_cls("")
if root_cmd:
# the arg_name is actually the calling args for root cmd
cmd_cls = root_cmd
self.args = self.argv
else:
raise ValueError(f'{self.script_name or "meta"} {self.name or ""}: Invalid command: {self.argv}')
raise ValueError(
f'{self.script_name or "meta"} {self.name or ""}: Invalid command: {self.argv}'
)
else:
self.command_not_found()

Expand All @@ -212,15 +216,15 @@ def __call__(self, **kwargs):
args = []
for arg in self.args:
arg = str(arg)
if arg.startswith('--'):
if '=' in arg:
key, *values = arg.split('=')
val = '='.join(values)
if arg.startswith("--"):
if "=" in arg:
key, *values = arg.split("=")
val = "=".join(values)
kwargs[key] = val # = kwargs[str(key).strip('--')]
else:
kwargs[arg] = True # = kwargs[str(arg).strip('--')]
elif arg.startswith('-'):
kwargs[arg] = True # kwargs[arg.strip('-')] =
elif arg.startswith("-"):
kwargs[arg] = True # kwargs[arg.strip('-')] =
else:
args.append(arg)
try:
Expand All @@ -230,27 +234,34 @@ def __call__(self, **kwargs):

def handle_parse_error(self, e: Exception):
if isinstance(e, AbsenceError):
message = f'required command argument: {repr(e.item)} is absence'
message = f"required command argument: {repr(e.item)} is absence"
else:
message = str(e)
error = Error(e)
error.setup()
print(error.full_info)
print(RED % F'{self.script_name or "meta"} {self.name or ""}: command [{self.arg_name}] failed: {message}')
print(
RED
% f'{self.script_name or "meta"} {self.name or ""}: command [{self.arg_name}] failed: {message}'
)
exit(1)

@classmethod
def mount(cls, cmd_cls: Type['BaseCommand'], name: str = '', *aliases: str):
def mount(cls, cmd_cls: Type["BaseCommand"], name: str = "", *aliases: str):
if not issubclass(cmd_cls, BaseCommand):
raise TypeError(f'Invalid command class: {cmd_cls}, should be BaseCommand subclass')
raise TypeError(
f"Invalid command class: {cmd_cls}, should be BaseCommand subclass"
)
for alias in aliases:
cls._aliases[alias] = name
cls._commands[name] = cmd_cls

@classmethod
def merge(cls, cmd_cls: Type['BaseCommand']):
def merge(cls, cmd_cls: Type["BaseCommand"]):
if not issubclass(cmd_cls, BaseCommand):
raise TypeError(f'Invalid command class: {cmd_cls}, should be BaseCommand subclass')
raise TypeError(
f"Invalid command class: {cmd_cls}, should be BaseCommand subclass"
)
cls._commands.update(cmd_cls._commands)
cls._aliases.update(cmd_cls._aliases)
cls._documents.update(cmd_cls._documents)
Expand Down
Loading

0 comments on commit 42733d2

Please sign in to comment.