Skip to content

Commit

Permalink
🎨 black
Browse files Browse the repository at this point in the history
  • Loading branch information
RF-Tar-Railt committed Oct 16, 2023
1 parent 4aba3dd commit c0548e3
Show file tree
Hide file tree
Showing 22 changed files with 330 additions and 283 deletions.
44 changes: 18 additions & 26 deletions src/arclet/alconna/_internal/_analyser.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,7 @@
from ..core import Alconna
from ._argv import Argv

_SPECIAL = {
"help": handle_help,
"shortcut": handle_shortcut,
"completion": handle_completion
}
_SPECIAL = {"help": handle_help, "shortcut": handle_shortcut, "completion": handle_completion}


def _compile_opts(option: Option, data: dict[str, Sentence | Option | list[Option] | SubAnalyser]):
Expand Down Expand Up @@ -76,7 +72,7 @@ def default_compiler(analyser: SubAnalyser, pids: set[str]):
"""
for opts in analyser.command.options:
if isinstance(opts, Option):
if opts.compact or opts.action.type == 2 or not set(analyser.command.separators).issuperset(opts.separators):
if opts.compact or opts.action.type == 2 or not set(analyser.command.separators).issuperset(opts.separators): # noqa: E501
analyser.compact_params.append(opts)
_compile_opts(opts, analyser.compile_params) # type: ignore
if opts.default:
Expand All @@ -100,6 +96,7 @@ def default_compiler(analyser: SubAnalyser, pids: set[str]):
@dataclass
class SubAnalyser(Generic[TDC]):
"""子解析器, 用于子命令的解析"""

command: Subcommand
"""子命令"""
default_main_only: bool = field(default=False)
Expand Down Expand Up @@ -157,9 +154,7 @@ def result(self) -> SubcommandResult:
for k, v in self.default_sub_result.items():
if k not in self.subcommands_result:
self.subcommands_result[k] = v
res = SubcommandResult(
self.value_result, self.args_result, self.options_result, self.subcommands_result
)
res = SubcommandResult(self.value_result, self.args_result, self.options_result, self.subcommands_result)
self.reset()
return res

Expand Down Expand Up @@ -233,6 +228,7 @@ def get_sub_analyser(self, target: Subcommand) -> SubAnalyser[TDC] | None:

class Analyser(SubAnalyser[TDC], Generic[TDC]):
"""命令解析器"""

command: Alconna
"""命令实例"""
used_tokens: set[int]
Expand All @@ -252,10 +248,7 @@ def __init__(self, alconna: Alconna[TDC], compiler: TCompile | None = None):
self.used_tokens = set()
self.command_header = Header.generate(alconna.command, alconna.prefixes, alconna.meta.compact)
compiler = compiler or default_compiler
compiler(
self,
command_manager.resolve(self.command).param_ids
)
compiler(self, command_manager.resolve(self.command).param_ids)

def _clr(self):
self.used_tokens.clear()
Expand Down Expand Up @@ -285,15 +278,15 @@ def shortcut(
if isinstance(short, Arparma):
return short

argv.build(short.get('command', argv.converter(self.command.command or self.command.name)))
if not short.get('fuzzy') and data:
argv.build(short.get("command", argv.converter(self.command.command or self.command.name)))
if not short.get("fuzzy") and data:
exc = ParamsUnmatched(lang.require("analyser", "param_unmatched").format(target=data[0]))
if self.command.meta.raise_exception:
raise exc
return self.export(argv, True, exc)
if short.get('fuzzy') and reg and len(trigger) > reg.span()[1]:
argv.addon((trigger[reg.span()[1]:],))
argv.addon(short.get('args', []))
if short.get("fuzzy") and reg and len(trigger) > reg.span()[1]:
argv.addon((trigger[reg.span()[1] :],))
argv.addon(short.get("args", []))
data = _handle_shortcut_data(argv, data)
argv.bak_data = argv.raw_data.copy()
argv.addon(data)
Expand All @@ -318,11 +311,7 @@ def process(self, argv: Argv[TDC]) -> Arparma[TDC]:
ParamsUnmatched: 参数不匹配
ArgumentMissing: 参数缺失
"""
if (
argv.message_cache and
argv.token in self.used_tokens and
(res := command_manager.get_record(argv.token))
):
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 = analyse_header(self.command_header, argv)
Expand Down Expand Up @@ -363,7 +352,7 @@ def process(self, argv: Argv[TDC]) -> Arparma[TDC]:
rest = argv.release()
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()
argv.bak_data[-1] = argv.bak_data[-1][: -len(rest[-1])].rstrip()
return handle_completion(self, argv, rest[-2])
exc = ParamsUnmatched(lang.require("analyser", "param_unmatched").format(target=argv.next(move=False)[0]))
else:
Expand All @@ -388,7 +377,7 @@ def analyse(self, argv: Argv[TDC]) -> Arparma[TDC] | None:
except (ParamsUnmatched, ArgumentMissing) as e1:
if (rest := argv.release()) and isinstance(rest[-1], str):
if rest[-1] in argv.completion_names:
argv.bak_data[-1] = argv.bak_data[-1][:-len(rest[-1])].rstrip()
argv.bak_data[-1] = argv.bak_data[-1][: -len(rest[-1])].rstrip()
return handle_completion(self, argv)
if handler := argv.special.get(rest[-1]):
return _SPECIAL[handler](self, argv)
Expand All @@ -404,7 +393,10 @@ def analyse(self, argv: Argv[TDC]) -> Arparma[TDC] | None:
self.args_result = analyse_args(argv, self.self_args)

def export(
self, argv: Argv[TDC], fail: bool = False, exception: BaseException | None = None,
self,
argv: Argv[TDC],
fail: bool = False,
exception: BaseException | None = None,
) -> Arparma[TDC]:
"""创建 `Arparma` 解析结果, 其一定是一次解析的最后部分
Expand Down
17 changes: 9 additions & 8 deletions src/arclet/alconna/_internal/_argv.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,15 @@
@dataclass(repr=True)
class Argv(Generic[TDC]):
"""命令行参数"""

namespace: InitVar[Namespace] = field(default=config.default_namespace)
fuzzy_match: bool = field(default=False)
"""当前命令是否模糊匹配"""
preprocessors: dict[type, Callable[..., Any]] = field(default_factory=dict)
"""命令元素的预处理器"""
to_text: Callable[[Any], str | None] = field(default=lambda x: x if isinstance(x, str) else None)
"""将命令元素转换为文本, 或者返回None以跳过该元素"""
separators: tuple[str, ...] = field(default=(' ',))
separators: tuple[str, ...] = field(default=(" ",))
"""命令分隔符"""
filter_out: list[type] = field(default_factory=list)
"""需要过滤掉的命令元素"""
Expand Down Expand Up @@ -60,11 +61,11 @@ def __post_init__(self, namespace: Namespace):
self.reset()
self.special: dict[str, str] = {}
self.special.update(
[(i, "help") for i in namespace.builtin_option_name['help']] +
[(i, "completion") for i in namespace.builtin_option_name['completion']] +
[(i, "shortcut") for i in namespace.builtin_option_name['shortcut']]
[(i, "help") for i in namespace.builtin_option_name["help"]]
+ [(i, "completion") for i in namespace.builtin_option_name["completion"]]
+ [(i, "shortcut") for i in namespace.builtin_option_name["shortcut"]]
)
self.completion_names = namespace.builtin_option_name['completion']
self.completion_names = namespace.builtin_option_name["completion"]
if __cache := self.__class__._cache.get(self.__class__, {}):
self.preprocessors.update(__cache.get("preprocessors") or {})
self.filter_out.extend(__cache.get("filter_out") or [])
Expand Down Expand Up @@ -218,7 +219,7 @@ def free(self, separate: tuple[str, ...] | None = None):
self.bak_data.insert(self.current_index + 1, _rest_text)
self.raw_data.insert(self.current_index + 1, _rest_text)
self.ndata += 1
self.bak_data[self.current_index] = self.bak_data[self.current_index][:-len(_current_data)]
self.bak_data[self.current_index] = self.bak_data[self.current_index][: -len(_current_data)]
self.raw_data[self.current_index] = ""
else:
self.bak_data.pop(self.current_index)
Expand All @@ -235,10 +236,10 @@ def release(self, separate: tuple[str, ...] | None = None, recover: bool = False
list[str | Any]: 剩余的数据.
"""
_result = []
data = self.bak_data if recover else self.raw_data[self.current_index:]
data = self.bak_data if recover else self.raw_data[self.current_index :]
for _data in data:
if _data.__class__ is str:
_result.extend(split(_data, separate or (' ',), self.filter_crlf))
_result.extend(split(_data, separate or (" ",), self.filter_crlf))
else:
_result.append(_data)
return _result
Expand Down
Loading

0 comments on commit c0548e3

Please sign in to comment.