Skip to content

Commit

Permalink
🎨 format
Browse files Browse the repository at this point in the history
  • Loading branch information
RF-Tar-Railt committed Oct 13, 2024
1 parent 5bf68a8 commit cc2f4d8
Show file tree
Hide file tree
Showing 31 changed files with 176 additions and 211 deletions.
1 change: 0 additions & 1 deletion benchmark.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ def __repr__(self):


with namespace("test") as np:
np.enable_message_cache = False
np.to_text = lambda x: x.text if x.__class__ is Plain else None
alc = Alconna(
["."],
Expand Down
4 changes: 2 additions & 2 deletions devtool.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@
from typing import Any, Literal

from arclet.alconna._internal._analyser import Analyser, default_compiler
from arclet.alconna._internal._handlers import analyse_args as ala
from arclet.alconna._internal._handlers import HEAD_HANDLES
from arclet.alconna._internal._handlers import analyse_args as ala
from arclet.alconna._internal._handlers import analyse_option as alo
from arclet.alconna._internal._header import Header
from arclet.alconna.args import Args
from arclet.alconna.argv import Argv
from arclet.alconna.base import Option, Subcommand
from arclet.alconna.config import Namespace
from arclet.alconna.typing import DataCollection, CommandMeta
from arclet.alconna.typing import CommandMeta, DataCollection


class AnalyseError(Exception):
Expand Down
4 changes: 2 additions & 2 deletions src/arclet/alconna/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@
from .arparma import ArparmaBehavior as ArparmaBehavior
from .base import Option as Option
from .base import Subcommand as Subcommand
from .builtin import set_default as set_default
from .builtin import conflict as conflict
from .builtin import set_default as set_default
from .completion import CompSession as CompSession
from .config import Namespace as Namespace
from .config import config as config
Expand All @@ -45,9 +45,9 @@
from .typing import Kw as Kw
from .typing import MultiVar as MultiVar
from .typing import Nargs as Nargs
from .typing import StrMulti as StrMulti
from .typing import UnpackVar as UnpackVar
from .typing import Up as Up
from .typing import StrMulti as StrMulti

__version__ = "1.8.31"

Expand Down
3 changes: 1 addition & 2 deletions src/arclet/alconna/_dcls.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
from __future__ import annotations
from typing import TYPE_CHECKING

from dataclasses import dataclass

from typing import TYPE_CHECKING

if TYPE_CHECKING:

Expand Down
75 changes: 18 additions & 57 deletions src/arclet/alconna/_internal/_analyser.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@
from ..arparma import Arparma
from ..base import Completion, Help, Option, Shortcut, Subcommand
from ..completion import comp_ctx
from ..constraint import SHORTCUT_ARGS, SHORTCUT_REGEX_MATCH, SHORTCUT_REST, SHORTCUT_TRIGGER
from ..exceptions import (
ArgumentMissing,
FuzzyMatchSuccess,
InvalidHeader,
InvalidParam,
ParamsUnmatched,
PauseTriggered,
Expand All @@ -26,7 +26,6 @@
from ..typing import TDC
from ._handlers import (
HEAD_HANDLES,
handle_head_fuzzy,
analyse_args,
analyse_param,
handle_completion,
Expand All @@ -35,7 +34,6 @@
handle_shortcut,
prompt,
)
from ._shortcut import shortcut
from ._header import Header
from ._util import levenshtein

Expand Down Expand Up @@ -209,8 +207,6 @@ class Analyser(SubAnalyser):

command: Alconna
"""命令实例"""
used_tokens: set[int]
"""已使用的token"""
command_header: Header
"""命令头部"""
header_handler: Callable[[Header, Argv], HeadResult]
Expand All @@ -225,7 +221,6 @@ def __init__(self, alconna: Alconna, compiler: TCompile | None = None):
"""
super().__init__(alconna)
self._compiler = compiler or default_compiler
self.used_tokens = set()

def compile(self, param_ids: set[str]):
self.extra_allow = not self.command.meta.strict or not self.command.namespace_config.strict
Expand All @@ -234,78 +229,45 @@ def compile(self, param_ids: set[str]):
self._compiler(self, param_ids)
return self

def _clr(self):
self.used_tokens.clear()
super()._clr()

def __repr__(self):
return f"<{self.__class__.__name__} of {self.command.path}>"

def process(self, argv: Argv[TDC]) -> Arparma[TDC] | None:
def process(self, argv: Argv[TDC]) -> Exception | None:
"""主体解析函数, 应针对各种情况进行解析
Args:
argv (Argv[TDC]): 命令行参数
Returns:
Arparma[TDC]: Arparma 解析结果
Raises:
ValueError: 快捷命令查找失败
InvalidParam: 参数不匹配
ArgumentMissing: 参数缺失
"""
if argv.message_cache and argv.token in self.used_tokens and (res := command_manager.get_record(argv.token)):
return res
try:
self.header_result = self.header_handler(self.command_header, argv)
except InvalidParam as e:
_next = e.args[1]
if _next.__class__ is not str or not _next:
raise e
argv.context[SHORTCUT_TRIGGER] = _next
if not self.header_result:
try:
rest, short, mat = command_manager.find_shortcut(self.command, [_next] + argv.release())
except ValueError as exc:
if argv.fuzzy_match and (res := handle_head_fuzzy(self.command_header, _next, argv.fuzzy_threshold)):
output_manager.send(self.command.name, lambda: res)
raise FuzzyMatchSuccess(res) from None
raise e from exc

argv.context[SHORTCUT_ARGS] = short
argv.context[SHORTCUT_REST] = rest
argv.context[SHORTCUT_REGEX_MATCH] = mat
self.reset()
if isinstance(short, Arparma):
return short
shortcut(argv, rest, short, mat)
self.header_result = self.header_handler(self.command_header, argv)
self.header_result.origin = _next

except RuntimeError as e:
exc = InvalidParam(lang.require("header", "error").format(target=argv.release(recover=True)[0]))
raise exc from e
self.header_result = self.header_handler(self.command_header, argv)
except InvalidHeader as e:
return e
except RuntimeError:
exc = InvalidParam(lang.require("header", "error").format(target=argv.release(recover=True)[0]))
return exc

try:
while analyse_param(self, argv) and argv.current_index != argv.ndata:
argv.current_node = None
except FuzzyMatchSuccess as e:
output_manager.send(self.command.name, lambda: str(e))
raise e
return e
except SpecialOptionTriggered as sot:
raise _SPECIAL[sot.args[0]](self, argv)
return _SPECIAL[sot.args[0]](self, argv)
except (InvalidParam, ArgumentMissing) as e1:
if (rest := argv.release()) and isinstance(rest[-1], str):
if rest[-1] in argv.completion_names and "completion" not in argv.namespace.disable_builtin_options:
argv.bak_data[-1] = argv.bak_data[-1][: -len(rest[-1])].rstrip()
raise handle_completion(self, argv)
return handle_completion(self, argv)
if (handler := argv.special.get(rest[-1])) and handler not in argv.namespace.disable_builtin_options:
raise _SPECIAL[handler](self, argv)
return _SPECIAL[handler](self, argv)
if comp_ctx.get(None):
if isinstance(e1, InvalidParam):
argv.free(argv.current_node.separators if argv.current_node else None)
raise PauseTriggered(prompt(self, argv), e1, argv) from e1
raise
return PauseTriggered(prompt(self, argv), e1, argv)
return e1

if self.default_main_only and not self.args_result:
self.args_result = analyse_args(argv, self.self_args)
Expand All @@ -317,15 +279,15 @@ def process(self, argv: Argv[TDC]) -> Arparma[TDC] | None:
if len(rest) > 0:
if isinstance(rest[-1], str) and rest[-1] in argv.completion_names:
argv.bak_data[-1] = argv.bak_data[-1][: -len(rest[-1])].rstrip()
raise handle_completion(self, argv, rest[-2])
return handle_completion(self, argv, rest[-2])
exc = ParamsUnmatched(lang.require("analyser", "param_unmatched").format(target=argv.next(move=False)[0]))
else:
exc = ArgumentMissing(
self.self_args.argument[0].field.get_missing_tips(lang.require("analyser", "param_missing"))
)
if comp_ctx.get(None) and isinstance(exc, ArgumentMissing):
raise PauseTriggered(prompt(self, argv), exc, argv)
raise exc
return PauseTriggered(prompt(self, argv), exc, argv)
return exc

def export(
self,
Expand Down Expand Up @@ -357,7 +319,6 @@ def export(
result.unpack()
if argv.message_cache:
command_manager.record(argv.token, result)
self.used_tokens.add(argv.token)
self.reset()
return result # type: ignore

Expand Down
2 changes: 1 addition & 1 deletion src/arclet/alconna/_internal/_argv.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from __future__ import annotations

from dataclasses import dataclass, field, fields, InitVar
from dataclasses import InitVar, dataclass, field, fields
from typing import Any, Callable, ClassVar, Generic, Iterable, Literal
from typing_extensions import Self

Expand Down
34 changes: 20 additions & 14 deletions src/arclet/alconna/_internal/_handlers.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,31 @@
from __future__ import annotations

import re
from typing import TYPE_CHECKING, Any, Iterable, Callable
from typing import TYPE_CHECKING, Any, Callable, Iterable
from typing_extensions import NoReturn

from nepattern import ANY, STRING, AnyString, BasePattern, TPattern
from tarina import Empty, lang, safe_eval, split_once
from typing_extensions import NoReturn

from ..action import Action
from ..args import Arg, Args
from ..base import Option, Subcommand
from ..completion import Prompt, comp_ctx
from ..config import config
from ..exceptions import AlconnaException, ArgumentMissing, FuzzyMatchSuccess, InvalidParam, PauseTriggered, SpecialOptionTriggered
from ..exceptions import (
AlconnaException,
ArgumentMissing,
FuzzyMatchSuccess,
InvalidHeader,
InvalidParam,
PauseTriggered,
SpecialOptionTriggered,
)
from ..model import HeadResult, OptionResult
from ..output import output_manager
from ..typing import KWBool, MultiKeyWordVar, MultiVar, _ShortcutRegWrapper, _StrMulti, _AllParamPattern
from ..typing import KWBool, MultiKeyWordVar, MultiVar, _AllParamPattern, _StrMulti
from ._header import Header
from ._util import escape, levenshtein, unescape
from ._util import levenshtein

if TYPE_CHECKING:
from ._analyser import Analyser, SubAnalyser
Expand Down Expand Up @@ -479,7 +487,7 @@ def _header_handle0(header: "Header[set[str], TPattern]", argv: Argv):
if header.compact and (mat := header.compact_pattern.match(cmd)):
argv.rollback(cmd[len(mat[0]):], replace=True)
return HeadResult(mat[0], mat[0], True, mat.groupdict(), header.mapping)
_after_analyse_header(header, argv, head_text, may_cmd, _str, _m_str)
_after_analyse_header(argv, head_text, may_cmd, _str, _m_str)


def _header_handle1(header: "Header[TPattern, TPattern]", argv: Argv):
Expand All @@ -499,7 +507,7 @@ def _header_handle1(header: "Header[TPattern, TPattern]", argv: Argv):
if header.compact and (mat := header.compact_pattern.match(cmd)):
argv.rollback(cmd[len(mat[0]):], replace=True)
return HeadResult(mat[0], mat[0], True, mat.groupdict(), header.mapping)
_after_analyse_header(header, argv, head_text, may_cmd, _str, _m_str)
_after_analyse_header(argv, head_text, may_cmd, _str, _m_str)


def _header_handle2(header: "Header[BasePattern, BasePattern]", argv: Argv):
Expand All @@ -511,7 +519,7 @@ def _header_handle2(header: "Header[BasePattern, BasePattern]", argv: Argv):
argv.rollback(head_text[len(str(val._value)):], replace=True)
return HeadResult(val.value, val._value, True, fixes=header.mapping)
may_cmd, _m_str = argv.next()
_after_analyse_header(header, argv, head_text, may_cmd, _str, _m_str)
_after_analyse_header(argv, head_text, may_cmd, _str, _m_str)


HEAD_HANDLES: dict[int, Callable[[Header, Argv], HeadResult]] = {
Expand All @@ -521,15 +529,15 @@ def _header_handle2(header: "Header[BasePattern, BasePattern]", argv: Argv):
}


def _after_analyse_header(header: Header, argv: Argv, head_text: Any, may_cmd: Any, _str: bool, _m_str: bool) -> NoReturn:
def _after_analyse_header(argv: Argv, head_text: Any, may_cmd: Any, _str: bool, _m_str: bool) -> NoReturn:
if _str:
argv.rollback(may_cmd)
raise InvalidParam(lang.require("header", "error").format(target=head_text), head_text)
raise InvalidHeader(lang.require("header", "error").format(target=head_text), head_text)
if _m_str and may_cmd:
cmd = f"{head_text}{argv.separators[0]}{may_cmd}"
raise InvalidParam(lang.require("header", "error").format(target=cmd), cmd)
raise InvalidHeader(lang.require("header", "error").format(target=cmd), cmd)
argv.rollback(may_cmd)
raise InvalidParam(lang.require("header", "error").format(target=head_text), None)
raise InvalidHeader(lang.require("header", "error").format(target=head_text), None)


def handle_head_fuzzy(header: Header, source: str, threshold: float):
Expand Down Expand Up @@ -579,8 +587,6 @@ def handle_shortcut(analyser: Analyser, argv: Argv):
raise ArgumentMissing(lang.require("shortcut", "name_require"))
if opt_v.get("action") == "delete":
msg = analyser.command.shortcut(opt_v["name"], delete=True)
elif opt_v["command"] == "_":
msg = analyser.command.shortcut(opt_v["name"], None)
elif opt_v["command"] == "$":
msg = analyser.command.shortcut(opt_v["name"], fuzzy=True)
else:
Expand Down
2 changes: 1 addition & 1 deletion src/arclet/alconna/_internal/_header.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from __future__ import annotations

import re
from typing import TypeVar, Generic
from typing import Generic, TypeVar

from nepattern import BasePattern, MatchMode, all_patterns, parser
from nepattern.util import TPattern
Expand Down
5 changes: 2 additions & 3 deletions src/arclet/alconna/_internal/_shortcut.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,9 @@
from tarina import lang

from ..exceptions import ArgumentMissing, ParamsUnmatched
from ..typing import _ShortcutRegWrapper, TDC, InnerShortcutArgs
from ._util import escape, unescape
from ..typing import InnerShortcutArgs, _ShortcutRegWrapper
from ._argv import Argv

from ._util import escape, unescape

INDEX_SLOT = re.compile(r"\{%(\d+)\}")
WILDCARD_SLOT = re.compile(r"\{\*(.*)\}", re.DOTALL)
Expand Down
14 changes: 11 additions & 3 deletions src/arclet/alconna/_stargazing/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,35 @@
from typing import Any, Iterable, Sequence, overload

import tarina
from elaina_segment import Buffer
from elaina_triehard import TrieHard

from arclet.alconna import Alconna, Arg, Args, Arparma, HeadResult, Option, OptionResult, Subcommand, SubcommandResult
from arclet.alconna.exceptions import ArgumentMissing, InvalidArgs, InvalidParam, NullMessage, ParamsUnmatched, UnexpectedElement
from arclet.alconna.exceptions import (
ArgumentMissing,
InvalidArgs,
InvalidParam,
NullMessage,
ParamsUnmatched,
UnexpectedElement,
)
from arclet.alconna.sistana import (
Analyzer,
AnalyzeSnapshot,
Fragment,
LoopflowExitReason,
OptionPattern,
Preset,
SubcommandPattern,
Track,
Value,
AnalyzeSnapshot,
)
from arclet.alconna.sistana.err import ParsePanic, Rejected
from arclet.alconna.sistana.model.fragment import _Fragment
from arclet.alconna.sistana.model.pointer import PointerRole
from arclet.alconna.sistana.model.snapshot import SubcommandTraverse

from .flywheel import build_runes
from elaina_segment import Buffer


def _alc_args_to_fragments(args: Args) -> deque[_Fragment]:
Expand Down
4 changes: 3 additions & 1 deletion src/arclet/alconna/_stargazing/flywheel.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
from __future__ import annotations

from typing import Sequence, TypeVar

from elaina_segment import Runes, build_runes as _build_runes
from elaina_segment import Runes
from elaina_segment import build_runes as _build_runes
from flywheel import wrap_anycast

T = TypeVar("T")
Expand Down
Loading

0 comments on commit cc2f4d8

Please sign in to comment.