Skip to content

Commit

Permalink
⬆️ update to Tarina 0.6.4
Browse files Browse the repository at this point in the history
  • Loading branch information
RF-Tar-Railt committed Nov 15, 2024
1 parent 15aa4a8 commit 8f049af
Show file tree
Hide file tree
Showing 21 changed files with 969 additions and 942 deletions.
156 changes: 78 additions & 78 deletions pdm.lock

Large diffs are not rendered by default.

13 changes: 7 additions & 6 deletions src/arclet/alconna/args.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@
from typing_extensions import dataclass_transform, ParamSpec, Concatenate, TypeAlias

from nepattern import NONE, Pattern, RawStr, UnionPattern, parser
from tarina import Empty, lang
from tarina import Empty

from .i18n import i18n
from ._dcls import safe_dcls_kw, safe_field_kw
from .exceptions import InvalidArgs
from .utils import TAValue, parent_frame_namespace, merge_cls_and_parent_ns
Expand Down Expand Up @@ -122,16 +123,16 @@ def __init__(
**kwargs,
):
if not isinstance(name, str) or name.startswith("$"):
raise InvalidArgs(lang.require("args", "name_error"))
raise InvalidArgs(i18n.require("args.name_error"))
if not name.strip():
raise InvalidArgs(lang.require("args", "name_empty"))
raise InvalidArgs(i18n.require("args.name_empty"))
self.name = name
_value = parser(type_ or RawStr(name))
default = field if isinstance(field, Field) else Field(field)
if isinstance(_value, UnionPattern) and _value.optional:
default.default = None if default.default is Empty else default.default # type: ignore
if _value == NONE:
raise InvalidArgs(lang.require("args", "value_error").format(target=name))
raise InvalidArgs(i18n.require("args.value_error").format(target=name))
self.type_ = _value # type: ignore
self.field = default

Expand Down Expand Up @@ -236,12 +237,12 @@ def __check_vars__(self):
raise InvalidArgs("varkey cannot use the same sep as varpos's Arg")
self.vars_keyword.append((flag, arg))
elif self.keyword_only:
raise InvalidArgs(lang.require("args", "exclude_mutable_args"))
raise InvalidArgs(i18n.require("args.exclude_mutable_args"))
else:
self.vars_positional.append((flag, arg))
elif arg.field.kw_only:
if self.vars_keyword:
raise InvalidArgs(lang.require("args", "exclude_mutable_args"))
raise InvalidArgs(i18n.require("args.exclude_mutable_args"))
self.keyword_only[arg.name] = arg
else:
self.normal.append(arg)
Expand Down
7 changes: 4 additions & 3 deletions src/arclet/alconna/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@
from nepattern import TPattern
from typing_extensions import Self

from tarina import Empty, lang
from tarina import Empty

from .i18n import i18n
from .action import Action, store
from .args import ARGS_PARAM, Arg, ArgsBase, ArgsBuilder, _Args, handle_args
from .exceptions import InvalidArgs
Expand Down Expand Up @@ -162,7 +163,7 @@ def check_fuzzy(self, source: str, threshold: float):
headers_text.append(f"{prefix} {command}")
for ht in headers_text:
if levenshtein(source, ht) >= threshold:
return lang.require("fuzzy", "matched").format(target=source, source=ht)
return i18n.require("fuzzy.matched").format(target=source, source=ht)


def _handle_default(node: CommandNode):
Expand Down Expand Up @@ -251,7 +252,7 @@ def __init__(
name = _aliases[0]
aliases.extend(_aliases[1:])
if not name:
raise InvalidArgs(lang.require("common", "name_empty"))
raise InvalidArgs(i18n.require("common.name_empty"))
aliases.insert(0, name)
self.name = name
self.aliases = frozenset(aliases)
Expand Down
10 changes: 5 additions & 5 deletions src/arclet/alconna/builtin.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@

from tarina import Empty

from .i18n import i18n
from .arparma import Arparma, ArparmaBehavior
from .config import lang
from .exceptions import BehaveCancelled
from .base import OptionResult, SubcommandResult

Expand All @@ -22,10 +22,10 @@ class ConflictWith(ArparmaBehavior):

def get_type(self, res):
if isinstance(res, OptionResult):
return lang.require("builtin", "conflict.option")
return i18n.require("builtin.conflict.option")
if isinstance(res, SubcommandResult):
return lang.require("builtin", "conflict.subcommand")
return lang.require("builtin", "conflict.arg")
return i18n.require("builtin.conflict.subcommand")
return i18n.require("builtin.conflict.arg")

def operate(self, interface: Arparma):
if (s_r := interface.query(self.source, Empty)) is not Empty and (t_r := interface.query(self.target, Empty)) is not Empty:
Expand All @@ -35,7 +35,7 @@ def operate(self, interface: Arparma):
return
if self.target_limiter and not self.target_limiter(t_r):
return
interface.behave_fail(lang.require("builtin", "conflict.msg").format(
interface.behave_fail(i18n.require("builtin.conflict.msg").format(
source_type=source_type,
target_type=target_type,
source=self.source,
Expand Down
6 changes: 3 additions & 3 deletions src/arclet/alconna/config.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from __future__ import annotations

from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Callable, ContextManager, Literal, TypedDict
from typing import TYPE_CHECKING, Any, Callable, ContextManager, TypedDict

from .i18n import lang as lang
from .i18n import i18n as i18n
from .base import Config
from .utils import DataCollection

Expand Down Expand Up @@ -123,4 +123,4 @@ def default_namespace(self, np: str | Namespace):

global_config = _AlconnaConfig()

__all__ = ["global_config", "Namespace", "namespace", "lang"]
__all__ = ["global_config", "Namespace", "namespace", "i18n"]
15 changes: 8 additions & 7 deletions src/arclet/alconna/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@
from weakref import WeakSet

from nepattern import TPattern
from tarina import init_spec, lang, Empty
from tarina import init_spec, Empty

from .i18n import i18n
from .ingedia._analyser import Analyser
from .ingedia._handlers import analyse_header
from .ingedia._argv import Argv, __argv_type__
Expand Down Expand Up @@ -50,7 +51,7 @@ def handle_argv():

def add_builtin_options(options: list[Option | Subcommand], router: Router, conf: Config) -> None:
if "help" not in conf.disable_builtin_options:
options.append(hlp := Help("|".join(conf.builtin_option_name["help"]), dest="$help", help_text=lang.require("builtin", "option_help"), soft_keyword=False)) # noqa: E501
options.append(hlp := Help("|".join(conf.builtin_option_name["help"]), dest="$help", help_text=i18n.require("builtin.option_help"), soft_keyword=False)) # noqa: E501

@router.route(f"*.{hlp.name}")
@router.route("$help")
Expand All @@ -67,7 +68,7 @@ def _(command: Alconna, arp: Arparma):
"|".join(conf.builtin_option_name["shortcut"]),
Args.action("delete|list", optional=True).name(str, optional=True).command(str, optional=True),
dest="$shortcut",
help_text=lang.require("builtin", "option_shortcut"),
help_text=i18n.require("builtin.option_shortcut"),
soft_keyword=False,
)
)
Expand All @@ -81,7 +82,7 @@ def _(command: Alconna, arp: Arparma):
arp.output = "\n".join(data)
return True
if not res.args.get("name"):
raise ValueError(lang.require("shortcut", "name_require"))
raise ValueError(i18n.require("shortcut.name_require"))
if res.args.get("action") == "delete":
msg = command.shortcut(res.args["name"], delete=True)
else:
Expand All @@ -92,7 +93,7 @@ def _(command: Alconna, arp: Arparma):
router._routes.pop("$shortcut", None)

if "completion" not in conf.disable_builtin_options:
options.append(comp := Completion("|".join(conf.builtin_option_name["completion"]), dest="$completion", help_text=lang.require("builtin", "option_completion"), soft_keyword=False)) # noqa: E501
options.append(comp := Completion("|".join(conf.builtin_option_name["completion"]), dest="$completion", help_text=i18n.require("builtin.option_completion"), soft_keyword=False)) # noqa: E501

@router.route(f"*.{comp.name}")
@router.route("$completion")
Expand All @@ -110,8 +111,8 @@ def _(command: Alconna, arp: Arparma):
[*arp.value_result.keys()],
trigger
):
prompt_other = lang.require("completion", "prompt_other")
node = lang.require('completion', 'node')
prompt_other = i18n.require("completion.prompt_other")
node = i18n.require('completion', 'node')
node = f"{node}\n" if node else ""
arp.output = f"{node}{prompt_other}" + f"\n{prompt_other}".join([i.text for i in res])
return True
Expand Down
19 changes: 10 additions & 9 deletions src/arclet/alconna/formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@
from typing import TYPE_CHECKING, Any, TypedDict

from nepattern import ANY, AnyString
from tarina import Empty, lang
from tarina import Empty

from .i18n import i18n
from .args import Arg, _Args
from .base import Option, Subcommand
from .utils import AllParam
Expand Down Expand Up @@ -179,7 +180,7 @@ def parameters(self, args: _Args) -> str:
res += self.param(arg) + sep
notice = [(arg.name, arg.field.notice) for arg in args.data if arg.field.notice]
return (
(f"{res}\n## {lang.require('format', 'notice')}\n " + "\n ".join([f"{v[0]}: {v[1]}" for v in notice]))
(f"{res}\n## {i18n.require('format', 'notice')}\n " + "\n ".join([f"{v[0]}: {v[1]}" for v in notice]))
if notice
else res
)
Expand All @@ -191,8 +192,8 @@ def header(self, root: TraceHead) -> tuple[str, str, str, str]:
root (TraceHead): 头部节点数据
"""
help_string = f"{desc}" if (desc := root["description"]) else ""
usage = f"{lang.require('format', 'usage')}:\n{usage}" if (usage := root.get("usage")) else ""
example = f"{lang.require('format', 'example')}:\n{example}" if (example := root.get("example")) else ""
usage = f"{i18n.require('format', 'usage')}:\n{usage}" if (usage := root.get("usage")) else ""
example = f"{i18n.require('format', 'example')}:\n{example}" if (example := root.get("example")) else ""
return root["name"], help_string, usage, example

def opt(self, node: Option) -> str:
Expand All @@ -212,8 +213,8 @@ def sub(self, node: Subcommand) -> str:
for sub in filter(lambda x: isinstance(x, Subcommand), node.options)
]
)
opt_help = f" {lang.require('format', 'subcommands.opts')}:\n " if opt_string else ""
sub_help = f" {lang.require('format', 'subcommands.subs')}:\n " if sub_string else ""
opt_help = f" {i18n.require('format', 'subcommands.opts')}:\n " if opt_string else ""
sub_help = f" {i18n.require('format', 'subcommands.subs')}:\n " if sub_string else ""
return (
f"* {node.help_text}\n"
f" {alias_text}{node.separators[0]}{self.parameters(node.args)}\n"
Expand All @@ -227,8 +228,8 @@ def body(self, parts: list[Option | Subcommand]) -> str:
[self.opt(opt) for opt in parts if isinstance(opt, Option) and opt.name not in self.ignore_names]
)
subcommand_string = "".join([self.sub(sub) for sub in parts if isinstance(sub, Subcommand)])
option_help = f"{lang.require('format', 'options')}:\n" if option_string else ""
subcommand_help = f"{lang.require('format', 'subcommands')}:\n" if subcommand_string else ""
option_help = f"{i18n.require('format', 'options')}:\n" if option_string else ""
subcommand_help = f"{i18n.require('format', 'subcommands')}:\n" if subcommand_string else ""
return f"{subcommand_help}{subcommand_string}{option_help}{option_string}"

def shortcut(self, shortcuts: dict[str, Any]) -> str:
Expand All @@ -243,7 +244,7 @@ def shortcut(self, shortcuts: dict[str, Any]) -> str:
result.append(f"'{prefixes}{_key}' => {prefixes}{short.command} {' '.join(map(str, short.args))}")
else:
result.append(f"'{key}' => {short.origin!r}")
return f"{lang.require('format', 'shortcuts')}:\n" + "\n".join(result)
return f"{i18n.require('format', 'shortcuts')}:\n" + "\n".join(result)


__all__ = ["TextFormatter", "Trace", "TraceHead"]
4 changes: 2 additions & 2 deletions src/arclet/alconna/i18n/.config.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
{
"default": "zh-CN",
"frozen": [
"builtin"
"alconna.builtin"
],
"require": [
"builtin"
"alconna.builtin"
]
}
Loading

0 comments on commit 8f049af

Please sign in to comment.