Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
hsz1273327 committed Jun 19, 2024
1 parent e39cbfc commit 898eb9f
Show file tree
Hide file tree
Showing 8 changed files with 75 additions and 16 deletions.
10 changes: 10 additions & 0 deletions Changelog.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
# 0.2.1

## bug修复

+ 修复多层节点情况下无法返回返回值

## 改进

+ 在有返回值时由__call__中返回的值会包含节点信息

# 0.2.0

## 新增特性
Expand Down
1 change: 1 addition & 0 deletions build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
python -m build --wheel
18 changes: 11 additions & 7 deletions schema_entry/entrypoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

from .protocol import SUPPORT_SCHEMA
from .utils import get_parent_tree, parse_value_string_by_schema, parse_schema_as_cmd, pydantic_schema_to_protocol
from .entrypoint_base import SchemaType, PropertyType, EntryPointABC, PydanticModelLike
from .entrypoint_base import SchemaType, PropertyType, EntryPointABC, PydanticModelLike, CallerReturnType


class EntryPoint(EntryPointABC):
Expand Down Expand Up @@ -185,7 +185,7 @@ def with_schema(self, schemaObj: Union[str, dict, PydanticModelLike]) -> Union[s
self.__doc__ = schemaObj.__doc__
return schemaObj

def __call__(self, argv: Sequence[str]) -> Optional[Any]:
def __call__(self, argv: Sequence[str]) -> Optional[CallerReturnType]:
if not self.usage:
if len(self._subcmds) == 0:
self.usage = f"{self.prog} [options]"
Expand Down Expand Up @@ -215,23 +215,27 @@ def __call__(self, argv: Sequence[str]) -> Optional[Any]:
description=self.__doc__,
usage=self.usage,
formatter_class=argparse.RawDescriptionHelpFormatter)
self.pass_args_to_sub(parser, argv)
return None
return self.pass_args_to_sub(parser, argv)

else:
parser = argparse.ArgumentParser(
prog=self.prog,
epilog=self.epilog,
description=self.__doc__,
usage=self.usage)
return self.parse_args(parser, argv)
result = self.parse_args(parser, argv)
if result is None:
return result
else:
return {"caller": self.name, "result": result}

def pass_args_to_sub(self, parser: argparse.ArgumentParser, argv: Sequence[str]) -> None:
def pass_args_to_sub(self, parser: argparse.ArgumentParser, argv: Sequence[str]) -> Optional[CallerReturnType]:
scmds = list(self._subcmds.keys())
scmdss = ",".join(scmds)
parser.add_argument('subcmd', help=f'执行子命令,可选的子命有{scmdss}')
args = parser.parse_args(argv[0:1])
if self._subcmds.get(args.subcmd):
self._subcmds[args.subcmd](argv[1:])
return self._subcmds[args.subcmd](argv[1:])
else:
print(f'未知的子命令 `{argv[0]}`')
parser.print_help()
Expand Down
9 changes: 7 additions & 2 deletions schema_entry/entrypoint_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ def model_json_schema(self, *args: Any, **kwargs: Any) -> Dict[str, Any]:
...


class CallerReturnType(TypedDict):
caller: str
result: Any


class ItemType(TypedDict):
type: str
enum: List[Union[int, float, str]]
Expand Down Expand Up @@ -148,7 +153,7 @@ def with_schema(self, schemaObj: Union[str, dict, PydanticModelLike]) -> Union[s
"""

@abc.abstractmethod
def __call__(self, argv: Sequence[str]) -> Optional[Any]:
def __call__(self, argv: Sequence[str]) -> Optional[CallerReturnType]:
"""执行命令.
如果当前的命令节点不是终点(也就是下面还有子命令)则传递参数到下一级;
Expand All @@ -160,7 +165,7 @@ def __call__(self, argv: Sequence[str]) -> Optional[Any]:
"""
@abc.abstractmethod
def pass_args_to_sub(self, parser: argparse.ArgumentParser, argv: Sequence[str]) -> None:
def pass_args_to_sub(self, parser: argparse.ArgumentParser, argv: Sequence[str]) -> Optional[CallerReturnType]:
"""解析复杂命令行参数并将参数传递至下一级."""

@abc.abstractmethod
Expand Down
2 changes: 1 addition & 1 deletion schema_entry/version.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "0.2.0"
__version__ = "0.2.1"
2 changes: 2 additions & 0 deletions test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
python -m coverage run --source=schema_entry -m unittest discover -v -s .
python -m coverage report
47 changes: 41 additions & 6 deletions tests/test_entrypoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ class Test_A(EntryPoint):
root = Test_A()
assert root.name == "test_b"


def test_default_entry_usage(self) -> None:
class Test_A(EntryPoint):
schema = {
Expand Down Expand Up @@ -78,10 +77,13 @@ class Test_A(EntryPoint):
root = Test_A()
config = root(["--a-a=4.2"])
target = {
"a_a": 4.2
"caller": "test_a",
"result": {
"a_a": 4.2
}
}
self.assertDictEqual(config,target)
self.assertDictEqual(config, target)

def test_main_return(self) -> None:
class Test_A(EntryPoint):
schema = {
Expand All @@ -95,13 +97,14 @@ class Test_A(EntryPoint):
},
"required": ["a_a"]
}

def do_main(self) -> str:
return "a test"
root = Test_A()
get_value = root(["--a-a=4.2"])
target = "a test"
target = {"caller": "test_a", "result": "a test"}
assert get_value == target

def test_override_do_main(self) -> None:
class Test_A(EntryPoint):
schema = {
Expand Down Expand Up @@ -177,6 +180,38 @@ def _(a: int) -> None:
"a": 2
})

def test_subcmd_return(self) -> None:
class A(EntryPoint):
pass

class B(EntryPoint):
pass

class C(EntryPoint):
schema = {
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"a": {
"type": "integer"
}
},
"required": ["a"]
}
root = A()
a_b_c = root.regist_sub(B).regist_sub(C)

@a_b_c.as_main
def _(a: int) -> int:
return a
os.environ['A_B_C_A'] = "2"
call_result = root(["b", "c"])

self.assertDictEqual(call_result, {
"caller": "c",
"result": 2
})


class LoadConfigTest(unittest.TestCase):
@classmethod
Expand Down
2 changes: 2 additions & 0 deletions typecheck.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
python -m pycodestyle --max-line-length=140 --ignore=E501 --first --statistics schema_entry
python -m mypy --ignore-missing-imports --show-column-numbers --follow-imports=silent --check-untyped-defs --disallow-untyped-defs --no-implicit-optional --warn-unused-ignores schema_entry

0 comments on commit 898eb9f

Please sign in to comment.