Skip to content

Commit

Permalink
fix bug
Browse files Browse the repository at this point in the history
  • Loading branch information
ice-black-tea committed Nov 12, 2023
1 parent e142790 commit d5961e6
Show file tree
Hide file tree
Showing 5 changed files with 80 additions and 33 deletions.
13 changes: 7 additions & 6 deletions src/linktools/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
from rich import get_console
from rich.tree import Tree

from linktools.cli.argparse import add_subparsers
from ._environ import environ
from .cli import BaseCommand, walk_commands
from .decorator import cached_property
Expand Down Expand Up @@ -92,24 +91,26 @@ def command_infos(self) -> Dict[CategoryInfo, List[CommandInfo]]:
return command_infos

def init_arguments(self, parser: ArgumentParser) -> None:
catalog_parsers = add_subparsers(parser, metavar="CATALOG", required=True)
catalog_parsers = parser.add_subparsers(metavar="CATALOG")
catalog_parsers.required = True
for category_info, command_infos in self.command_infos.items():
catalog_parser = catalog_parsers.add_parser(
category_info.name,
help=category_info.description
)
command_parsers = add_subparsers(catalog_parser, metavar="COMMAND", required=True)
command_parsers = catalog_parser.add_subparsers(metavar="COMMAND")
command_parsers.required = True
for command_info in command_infos:
command_parser = command_info.command.create_argument_parser(
command_info.name,
type=command_parsers.add_parser,
help=command_info.description,
)
command_parser.set_defaults(func=command_info.command)
command_parser.set_defaults(run_command=command_info.command)

def run(self, args: Namespace) -> Optional[int]:
if hasattr(args, "func") and callable(args.func):
return args.func(args)
if hasattr(args, "run_command") and callable(args.run_command):
return args.run_command(args)

tree = Tree("📎 All commands")
for category, commands in self.command_infos.items():
Expand Down
6 changes: 0 additions & 6 deletions src/linktools/cli/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,9 +122,3 @@ def wrapper(o):
raise ValueError("value not in range %s-%s" % (min, max))

return wrapper


def add_subparsers(parser: argparse.ArgumentParser, **kwargs):
if sys.version_info < (3, 7):
kwargs.pop("required", None)
return parser.add_subparsers(**kwargs)
10 changes: 6 additions & 4 deletions src/linktools/cli/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,16 @@
import sys
import textwrap
import traceback
from argparse import ArgumentParser, Action, Namespace, RawDescriptionHelpFormatter, SUPPRESS, FileType, HelpFormatter
from argparse import ArgumentParser, Action, Namespace
from argparse import RawDescriptionHelpFormatter, SUPPRESS, FileType, HelpFormatter
from importlib.util import module_from_spec
from pkgutil import walk_packages
from typing import Tuple, Type, Optional, List, Generator, Any, Callable, Iterable, Union, Set, Dict
from typing import Optional, Callable, List, Type, Tuple, Generator, Any, Iterable, Union, Set, Dict

import rich
from rich import get_console

from .argparse import BooleanOptionalAction, add_subparsers
from .argparse import BooleanOptionalAction
from .._environ import BaseEnviron, environ
from .._logging import LogHandler
from ..decorator import cached_property
Expand Down Expand Up @@ -275,7 +276,8 @@ def add_subcommands(self: "BaseCommand", parser: ArgumentParser = None, target:
parser = parser or self._argument_parser
target = target or self

subparsers = add_subparsers(parser, metavar="COMMAND", help="Command Help", required=True)
subparsers = parser.add_subparsers(metavar="COMMAND", help="Command Help")
subparsers.required = True # 兼容python3.6
for _, command_info in SubCommandMixin._find_command_infos(target):
command_actions = []
command_func = getattr(target, command_info.func.__name__)
Expand Down
5 changes: 3 additions & 2 deletions src/linktools/cli/commands/common/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@

from linktools import ToolError
from linktools.cli import BaseCommand
from linktools.cli.argparse import KeyValueAction, add_subparsers
from linktools.cli.argparse import KeyValueAction
from linktools.utils import DownloadError


Expand Down Expand Up @@ -61,7 +61,8 @@ def init_arguments(self, parser: ArgumentParser) -> None:
help="execute tools as a daemon")

tool_names = sorted([tool.name for tool in iter(self.environ.tools)])
subparsers = add_subparsers(parser, metavar="TOOL", help=f"{{{','.join(tool_names)}}}", required=True)
subparsers = parser.add_subparsers(metavar="TOOL", help=f"{{{','.join(tool_names)}}}")
subparsers.required = True
for tool_name in tool_names:
tool_parser = subparsers.add_parser(tool_name, prefix_chars=chr(0))
tool_parser.add_argument("tool_args", metavar="args", nargs="...")
Expand Down
79 changes: 64 additions & 15 deletions src/linktools/cli/device.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,32 @@
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# -*- coding: utf-8 -*-

"""
@author : Hu Ji
@file : device.py
@time : 2023/11/12
@site : https://github.com/ice-black-tea
@software: PyCharm
,----------------, ,---------,
,-----------------------, ," ,"|
," ,"| ," ," |
+-----------------------+ | ," ," |
| .-----------------. | | +---------+ |
| | | | | | -==----'| |
| | $ sudo rm -rf / | | | | | |
| | | | |/----|`---= | |
| | | | | ,/|==== ooo | ;
| | | | | // |(((( [33]| ,"
| `-----------------' |," .;'| |(((( | ,"
+-----------------------+ ;; | | |,"
/_)______________(_/ //' | +---------+
___________________________/___ `,
/ oooooooooooooooo .o. oooo /, \,"-----------
/ ==ooooooooooooooo==.o. ooo= // ,`\--{)B ,"
/_==__==========__==_ooo__ooo=_/' /___________,"
"""

import abc
import functools
import os
Expand All @@ -10,7 +37,7 @@
from rich.prompt import IntPrompt
from rich.table import Table

from .command import BaseCommand
from . import BaseCommand
from ..android import Adb, AdbError, Device as AdbDevice
from ..device import Bridge, BridgeError, BaseDevice, BridgeType, DeviceType
from ..ios import Sib, SibError, Device as SibDevice
Expand Down Expand Up @@ -170,11 +197,14 @@ def pick(bridge: Bridge):
device_parser = DevicePicker.copy_on_write(namespace, self.dest)
device_parser.func = pick

group = parser.add_argument_group(title="mobile device options").add_mutually_exclusive_group()
group.add_argument("-i", "--id", metavar="ID", dest="device_picker", action=IDAction,
help="specify unique device identifier", default=DevicePicker(pick))
group.add_argument("-l", "--last", dest="device_picker", nargs=0, const=True, action=LastAction,
help="use last device")
option_group = parser.add_argument_group(title="mobile device options")
option_group.set_defaults(device_picker=DevicePicker(pick))

device_group = option_group.add_mutually_exclusive_group()
device_group.add_argument("-i", "--id", metavar="ID", dest="device_picker", action=IDAction,
help="specify unique device identifier")
device_group.add_argument("-l", "--last", dest="device_picker", nargs=0, const=True, action=LastAction,
help="use last device")


class AndroidCommandMixin:
Expand Down Expand Up @@ -292,9 +322,9 @@ def __call__(self, parser, namespace, values, option_string=None):
device_parser.options.append(str(values))

option_group = parser.add_argument_group(title="adb options")
option_group.set_defaults(device_picker=AndroidPicker(pick))

option_group.add_argument("-a", "--all-interfaces", dest="device_picker", nargs=0, action=OptionAction,
default=AndroidPicker(pick),
help="listen on all network interfaces, not just localhost (adb -a option)")

device_group = option_group.add_mutually_exclusive_group()
Expand Down Expand Up @@ -401,13 +431,24 @@ def pick(sib: Sib):
device_parser = IOSPicker.copy_on_write(namespace, self.dest)
device_parser.func = pick

group = parser.add_argument_group(title="sib options").add_mutually_exclusive_group()
group.add_argument("-u", "--udid", metavar="UDID", dest="device_picker", action=UdidAction,
help="specify unique device identifier", default=IOSPicker(pick))
group.add_argument("-c", "--connect", metavar="IP:PORT", dest="device_picker", action=ConnectAction,
help="use device with TCP/IP")
group.add_argument("-l", "--last", dest="device_picker", nargs=0, const=True, action=LastAction,
help="use last device")
option_group = parser.add_argument_group(title="sib options")
option_group.set_defaults(device_picker=IOSPicker(pick))

device_group = option_group.add_mutually_exclusive_group()
device_group.add_argument("-u", "--udid", metavar="UDID", dest="device_picker", action=UdidAction,
help="specify unique device identifier")
device_group.add_argument("-c", "--connect", metavar="IP:PORT", dest="device_picker", action=ConnectAction,
help="use device with TCP/IP")
device_group.add_argument("-l", "--last", dest="device_picker", nargs=0, const=True, action=LastAction,
help="use last device")


class AndroidNamespace(Namespace):
device_picker: AndroidPicker = None


class IOSNamespace(Namespace):
device_picker: IOSPicker = None


class AndroidCommand(BaseCommand, metaclass=abc.ABCMeta):
Expand All @@ -420,6 +461,10 @@ def init_base_arguments(self, parser: ArgumentParser):
super().init_base_arguments(parser)
AndroidCommandMixin.add_android_options(self, parser)

@abc.abstractmethod
def run(self, args: AndroidNamespace) -> Optional[int]:
pass


class IOSCommand(BaseCommand, metaclass=abc.ABCMeta):

Expand All @@ -430,3 +475,7 @@ def known_errors(self) -> List[Type[BaseException]]:
def init_base_arguments(self, parser: ArgumentParser):
super().init_base_arguments(parser)
IOSCommandMixin.add_ios_options(self, parser)

@abc.abstractmethod
def run(self, args: IOSNamespace) -> Optional[int]:
pass

0 comments on commit d5961e6

Please sign in to comment.