示例#1
0
    def test_choice_combination(self):
        prompt = ListPrompt(message="Test combo", choices=["hello"])
        self.assertEqual(prompt._qmark, "?")
        self.assertEqual(prompt.instruction, "")

        self.assertRaises(InvalidArgument, ListPrompt, "",
                          [Separator(), Separator()])
示例#2
0
 def test_checkbox_control_exceptions(self):
     self.assertRaises(
         RequiredKeyNotFound,
         InquirerPyCheckboxControl,
         [
             {
                 "what": "apple",
                 "value": "peach"
             },
             "pear",
         ],
         "watermelon",
         "",
         "",
         "",
         None,
     )
     self.assertRaises(InvalidArgument, InquirerPyCheckboxControl, [], None,
                       "", "", "", None)
     self.assertRaises(
         InvalidArgument,
         InquirerPyCheckboxControl,
         [Separator(), Separator()],
         None,
         "",
         "",
         "",
         None,
     )
示例#3
0
    def test_safety_check(self):
        control = InquirerPyListControl(
            choices=[1],
            default=None,
            pointer=INQUIRERPY_POINTER_SEQUENCE,
            marker=INQUIRERPY_POINTER_SEQUENCE,
            session_result=None,
            multiselect=False,
            marker_pl=" ",
        )
        control._choices = []
        self.assertRaises(InvalidArgument, control._safety_check)

        control._choices = control._get_choices(
            [Separator(), Separator()], None)
        self.assertRaises(InvalidArgument, control._safety_check)
示例#4
0
def main():
    fruit = inquirer.rawlist(
        message="Pick your favourites:",
        choices=[
            "Apple",
            "Orange",
            "Peach",
            "Cherry",
            "Melon",
            "Strawberry",
            "Grapes",
        ],
        default=3,
        multiselect=True,
        transformer=lambda result: ", ".join(result),
        validate=lambda result: len(result) > 1,
        invalid_message="Minimum 2 selections",
    ).execute()
    method = inquirer.rawlist(
        message="Select your preferred method:",
        choices=[
            Choice(name="Delivery", value="dl"),
            Choice(name="Pick Up", value="pk"),
            Separator(line=15 * "*"),
            Choice(name="Car Park", value="cp"),
            Choice(name="Third Party", value="tp"),
        ],
    ).execute()
示例#5
0
def main():
    questions = [
        {
            "type": "list",
            "message": "Select an action:",
            "choices": ["Upload", "Download",
                        Choice(value=None, name="Exit")],
            "default": None,
        },
        {
            "type":
            "list",
            "message":
            "Select regions:",
            "choices": [
                Choice("ap-southeast-2", name="Sydney"),
                Choice("ap-southeast-1", name="Singapore"),
                Separator(),
                "us-east-1",
                "us-east-2",
            ],
            "multiselect":
            True,
            "transformer":
            lambda result:
            f"{len(result)} region{'s' if len(result) > 1 else ''} selected",
            "when":
            lambda result: result[0] is not None,
        },
    ]

    result = prompt(questions=questions)
示例#6
0
def question2_choice(_):
    return [
        ExpandChoice(key="d", name="Delivery", value="dl"),
        ExpandChoice(key="p", name="Pick Up", value="pk"),
        Separator(line=15 * "*"),
        ExpandChoice(key="c", name="Car Park", value="cp"),
        ExpandChoice(key="t", name="Third Party", value="tp"),
    ]
示例#7
0
    def test_handle_up(self):
        prompt = ListPrompt(message="Select one:",
                            choices=[1, 2, Separator(), 3])
        self.assertEqual(prompt.content_control.selected_choice_index, 0)
        prompt._handle_up(None)
        self.assertEqual(prompt.content_control.selected_choice_index, 3)
        prompt._handle_up(None)
        self.assertEqual(prompt.content_control.selected_choice_index, 1)
        prompt._handle_up(None)
        self.assertEqual(prompt.content_control.selected_choice_index, 0)
        prompt._handle_up(None)
        self.assertEqual(prompt.content_control.selected_choice_index, 3)

        prompt = ListPrompt(message="Select one:",
                            choices=[1, 2, 3, Separator()])
        self.assertEqual(prompt.content_control.selected_choice_index, 0)
        prompt._handle_up(None)
        self.assertEqual(prompt.content_control.selected_choice_index, 2)
示例#8
0
    def test_handle_up_no_cycle(self):
        prompt = ListPrompt(
            message="Select one:",
            choices=[Separator(), 1, 2, 3, Separator()],
            cycle=False,
        )
        self.assertEqual(prompt.content_control.selected_choice_index, 1)
        prompt._handle_up(None)
        self.assertEqual(prompt.content_control.selected_choice_index, 1)

        prompt = ListPrompt(
            message="Select one:",
            choices=[1, 2, 3, Separator()],
            cycle=False,
        )
        self.assertEqual(prompt.content_control.selected_choice_index, 0)
        prompt._handle_up(None)
        self.assertEqual(prompt.content_control.selected_choice_index, 0)
示例#9
0
    def test_separator_movement(self):
        prompt = ListPrompt(message="..", choices=[Separator("hello"), "yes"])
        self.assertEqual(prompt.content_control.selected_choice_index, 1)
        prompt._handle_down(None)
        self.assertEqual(prompt.content_control.selected_choice_index, 1)
        prompt._handle_up(None)
        self.assertEqual(prompt.content_control.selected_choice_index, 1)

        prompt = ListPrompt(
            message="..",
            choices=[Separator("hello"), "yes",
                     Separator(), "no"])
        self.assertEqual(prompt.content_control.selected_choice_index, 1)
        prompt._handle_down(None)
        self.assertEqual(prompt.content_control.selected_choice_index, 3)
        prompt._handle_up(None)
        self.assertEqual(prompt.content_control.selected_choice_index, 1)
        prompt._handle_up(None)
        self.assertEqual(prompt.content_control.selected_choice_index, 3)
示例#10
0
    def test_content_control_exceptions(self):
        choices = [{"hello": "hello"}]
        self.assertRaises(
            RequiredKeyNotFound,
            InquirerPyRawlistControl,
            choices,
            "",
            "",
            "",
            "",
            None,
            False,
            " ",
        )

        choices = [Separator(), Separator()]
        self.assertRaises(
            InvalidArgument,
            InquirerPyRawlistControl,
            choices,
            "",
            "",
            "",
            "",
            None,
            True,
            " ",
        )

        choices = []
        self.assertRaises(
            InvalidArgument,
            InquirerPyRawlistControl,
            choices,
            "",
            "",
            "",
            "",
            None,
            False,
            " ",
        )
示例#11
0
 def test_handle_down(self) -> None:
     prompt = ListPrompt(
         message="Select one:",
         choices=[1, 2, 3, Separator()],
     )
     self.assertEqual(prompt.content_control.selected_choice_index, 0)
     prompt._handle_down(None)
     self.assertEqual(prompt.content_control.selected_choice_index, 1)
     prompt._handle_down(None)
     prompt._handle_down(None)
     self.assertEqual(prompt.content_control.selected_choice_index, 0)
示例#12
0
def main():
    questions = [
        {
            "type":
            "rawlist",
            "choices": [
                "Apple",
                "Orange",
                "Peach",
                "Cherry",
                "Melon",
                "Strawberry",
                "Grapes",
            ],
            "message":
            "Pick your favourites:",
            "default":
            3,
            "multiselect":
            True,
            "transformer":
            lambda result: ", ".join(result),
            "validate":
            lambda result: len(result) > 1,
            "invalid_message":
            "Minimum 2 selections",
        },
        {
            "type":
            "rawlist",
            "choices": [
                Choice(name="Delivery", value="dl"),
                Choice(name="Pick Up", value="pk"),
                Separator(line=15 * "*"),
                Choice(name="Car Park", value="cp"),
                Choice(name="Third Party", value="tp"),
            ],
            "message":
            "Select your preferred method:",
        },
    ]

    result = prompt(questions)
示例#13
0
 def test_get_choices_list(self):
     sep = Separator()
     choice = [1, 2, 3, sep]
     default = 2
     control = InquirerPyListControl(
         choices=choice,
         default=default,
         pointer=INQUIRERPY_POINTER_SEQUENCE,
         marker=INQUIRERPY_POINTER_SEQUENCE,
         session_result=None,
         multiselect=False,
         marker_pl=" ",
     )
     self.assertEqual(control.selected_choice_index, 1)
     choices = control._get_choices(choice, 1)
     self.assertEqual(
         choices,
         [
             {
                 "name": "1",
                 "value": 1,
                 "enabled": False
             },
             {
                 "name": "2",
                 "value": 2,
                 "enabled": False
             },
             {
                 "name": "3",
                 "value": 3,
                 "enabled": False
             },
             {
                 "enabled": False,
                 "name": "---------------",
                 "value": sep
             },
         ],
     )
     self.assertEqual(control.selected_choice_index, 0)
示例#14
0
def main():
    action = inquirer.select(
        message="Select an action:",
        choices=[
            "Upload",
            "Download",
            Choice(value=None, name="Exit"),
        ],
        default=None,
    ).execute()
    if action:
        region = inquirer.select(
            message="Select regions:",
            choices=[
                Choice("ap-southeast-2", name="Sydney"),
                Choice("ap-southeast-1", name="Singapore"),
                Separator(),
                "us-east-1",
                "us-east-2",
            ],
            multiselect=True,
            transformer=lambda result:
            f"{len(result)} region{'s' if len(result) > 1 else ''} selected",
        ).execute()
def mainMenu(ctx: click.Context):
    global CHECKED, VERSION

    click.clear()

    if not CHECKED:
        result = subprocess.run('pip index versions projectalice-cli'.split(),
                                capture_output=True,
                                text=True)
        if 'error' not in result.stderr.lower():
            regex = re.compile(
                r"INSTALLED:.*(?P<installed>[\d]+\.[\d]+\.[\d]+)\n.*LATEST:.*(?P<latest>[\d]+\.[\d]+\.[\d]+)"
            )
            match = regex.search(result.stdout.strip())

            if not match:
                click.secho(message='Failed checking CLI version\n', fg='red')
            else:
                installed = Version.fromString(match.group('installed'))
                latest = Version.fromString(match.group('latest'))

                if installed < latest:
                    click.secho(
                        f'Project Alice CLI version {str(installed)}\n',
                        fg='red')
                    click.secho(
                        message=
                        f'CLI version {str(latest)} is available, you should consider updating using `pip install projectalice-cli --upgrade`\n',
                        fg='red')
                else:
                    click.secho(
                        f'Project Alice CLI version {str(installed)}\n',
                        fg='green')

                VERSION = str(installed)
        else:
            click.secho(message='Failed checking CLI version\n', fg='red')

        CHECKED = True
    else:
        click.echo(f'Project Alice CLI version {VERSION}\n')

    action = inquirer.select(
        message='',
        default=None,
        choices=[
            Separator(line='\n------- Network -------'),
            Choice(lambda: ctx.invoke(discover),
                   name='Discover devices on network'),
            Choice(lambda: ctx.invoke(connect), name='Connect to a device'),
            Separator(line='\n------- Setup -------'),
            Choice(lambda: ctx.invoke(prepareSdCard),
                   name='Prepare your SD card'),
            Choice(lambda: ctx.invoke(changePassword),
                   name='Change device\'s password'),
            Choice(lambda: ctx.invoke(changeHostname),
                   name='Set device\'s name'),
            Choice(lambda: ctx.invoke(installSoundDevice),
                   name='Install your sound device'),
            Choice(lambda: ctx.invoke(soundTest), name='Sound test'),
            Choice(lambda: ctx.invoke(installAlice), name='Install Alice'),
            Separator(line='\n------- Service -------'),
            Choice(lambda: ctx.invoke(systemctl, option='start'),
                   name='Start Alice'),
            Choice(lambda: ctx.invoke(systemctl, option='restart'),
                   name='Restart Alice'),
            Choice(lambda: ctx.invoke(systemctl, option='stop'),
                   name='Stop Alice'),
            Choice(lambda: ctx.invoke(systemctl, option='enable'),
                   name='Enable Alice service'),
            Choice(lambda: ctx.invoke(systemctl, option='disable'),
                   name='Disable Alice service'),
            Separator(line='\n------- Updates -------'),
            Choice(lambda: ctx.invoke(updateAlice), name='Update Alice'),
            Choice(lambda: ctx.invoke(updateSystem), name='Update system'),
            Choice(lambda: ctx.invoke(upgradeSystem), name='Upgrade system'),
            Separator(line='\n------- Logs -------'),
            Choice(lambda: ctx.invoke(reportBug),
                   name='Enable bug report for next session'),
            Choice(lambda: ctx.invoke(aliceLogs), name='Check Alice logs'),
            Choice(lambda: ctx.invoke(systemLogs), name='Check system logs'),
            Separator(line='\n------- Tools -------'),
            Choice(lambda: ctx.invoke(reboot), name='Reboot device'),
            Choice(lambda: ctx.invoke(uninstallSoundDevice),
                   name='Uninstall your sound device'),
            Choice(lambda: ctx.invoke(disableRespeakerLeds),
                   name='Turn off Respeaker bright white leds'),
            Choice(lambda: sys.exit(0), name='Exit')
        ]).execute()

    action()
示例#16
0
class TestCheckbox(unittest.TestCase):
    separator = Separator()
    choices = [
        "boy",
        "girl",
        separator,
        {
            "name": "mix",
            "value": "boy&girl",
            "enabled": True
        },
    ]

    def test_checkbox_control(self):
        checkbox_control = InquirerPyCheckboxControl(self.choices, "boy&girl",
                                                     "1", "2", "3", None)
        self.assertEqual(
            checkbox_control.choices,
            [
                {
                    "name": "boy",
                    "value": "boy",
                    "enabled": False
                },
                {
                    "name": "girl",
                    "value": "girl",
                    "enabled": False
                },
                {
                    "name": 15 * "-",
                    "value": self.separator,
                    "enabled": False
                },
                {
                    "name": "mix",
                    "value": "boy&girl",
                    "enabled": True
                },
            ],
        )
        self.assertEqual(checkbox_control.selected_choice_index, 3)
        self.assertEqual(
            checkbox_control._get_formatted_choices(),
            [
                ("", " "),
                ("", " "),
                ("class:checkbox", "3"),
                ("", " "),
                ("", "boy"),
                ("", "\n"),
                ("", " "),
                ("", " "),
                ("class:checkbox", "3"),
                ("", " "),
                ("", "girl"),
                ("", "\n"),
                ("", " "),
                ("", " "),
                ("class:separator", "---------------"),
                ("", "\n"),
                ("class:pointer", "1"),
                ("", " "),
                ("class:checkbox", "2"),
                ("", " "),
                ("[SetCursorPosition]", ""),
                ("class:pointer", "mix"),
            ],
        )
        self.assertEqual(checkbox_control.choice_count, 4)
        self.assertEqual(
            checkbox_control.selection,
            {
                "name": "mix",
                "value": "boy&girl",
                "enabled": True
            },
        )

    def test_checkbox_control_exceptions(self):
        self.assertRaises(
            RequiredKeyNotFound,
            InquirerPyCheckboxControl,
            [
                {
                    "what": "apple",
                    "value": "peach"
                },
                "pear",
            ],
            "watermelon",
            "",
            "",
            "",
            None,
        )
        self.assertRaises(InvalidArgument, InquirerPyCheckboxControl, [], None,
                          "", "", "", None)
        self.assertRaises(
            InvalidArgument,
            InquirerPyCheckboxControl,
            [Separator(), Separator()],
            None,
            "",
            "",
            "",
            None,
        )

    def test_checkbox_prompt(self):
        prompt = CheckboxPrompt(
            message="Select something",
            choices=self.choices,
            default="boy&girl",
            style=None,
            vi_mode=False,
            qmark="!",
            pointer="<",
            instruction="TAB",
        )
        self.assertEqual(prompt._editing_mode, EditingMode.EMACS)
        self.assertIsInstance(prompt.content_control,
                              InquirerPyCheckboxControl)
        self.assertIsInstance(prompt._kb, KeyBindings)
        self.assertIsInstance(prompt._style, Style)
        self.assertEqual(prompt._message, "Select something")
        self.assertEqual(prompt._qmark, "!")
        self.assertEqual(prompt.instruction, "TAB")

    def test_minimum_args(self):
        CheckboxPrompt(message="yes", choices=self.choices)

    def test_checkbox_prompt_message(self):
        prompt = CheckboxPrompt(
            message="Select something",
            choices=self.choices,
            instruction="TAB",
        )
        self.assertEqual(
            prompt._get_prompt_message(),
            [
                ("class:questionmark", "?"),
                ("class:question", " Select something"),
                ("class:instruction", " TAB "),
            ],
        )

    def test_checkbox_bindings(self):
        prompt = CheckboxPrompt(message="", choices=self.choices)
        self.assertEqual(prompt.content_control.selected_choice_index, 0)
        prompt._handle_down(None)
        self.assertEqual(prompt.content_control.selected_choice_index, 1)
        prompt._handle_down(None)
        self.assertEqual(prompt.content_control.selected_choice_index, 3)
        prompt._handle_down(None)
        self.assertEqual(prompt.content_control.selected_choice_index, 0)
        prompt._handle_up(None)
        self.assertEqual(prompt.content_control.selected_choice_index, 3)
        prompt._handle_up(None)
        self.assertEqual(prompt.content_control.selected_choice_index, 1)

        self.assertEqual(prompt.status["result"], None)
        self.assertEqual(prompt.status["answered"], False)
        self.assertEqual(prompt.status["skipped"], False)
        with patch("prompt_toolkit.utils.Event") as mock:
            event = mock.return_value
            prompt._handle_enter(event)
        self.assertEqual(prompt.status["result"], ["mix"])
        self.assertEqual(prompt.status["answered"], True)

        prompt._handle_toggle_choice(None)
        self.assertEqual(
            prompt.content_control.choices,
            [
                {
                    "enabled": False,
                    "name": "boy",
                    "value": "boy"
                },
                {
                    "enabled": True,
                    "name": "girl",
                    "value": "girl"
                },
                {
                    "enabled": False,
                    "name": "---------------",
                    "value": ANY
                },
                {
                    "enabled": True,
                    "name": "mix",
                    "value": "boy&girl"
                },
            ],
        )

        prompt._handle_toggle_all(None)
        self.assertEqual(
            prompt.content_control.choices,
            [
                {
                    "enabled": True,
                    "name": "boy",
                    "value": "boy"
                },
                {
                    "enabled": False,
                    "name": "girl",
                    "value": "girl"
                },
                {
                    "enabled": False,
                    "name": "---------------",
                    "value": ANY
                },
                {
                    "enabled": False,
                    "name": "mix",
                    "value": "boy&girl"
                },
            ],
        )

        prompt._handle_toggle_all(None, True)
        self.assertEqual(
            prompt.content_control.choices,
            [
                {
                    "enabled": True,
                    "name": "boy",
                    "value": "boy"
                },
                {
                    "enabled": True,
                    "name": "girl",
                    "value": "girl"
                },
                {
                    "enabled": False,
                    "name": "---------------",
                    "value": ANY
                },
                {
                    "enabled": True,
                    "name": "mix",
                    "value": "boy&girl"
                },
            ],
        )

    def test_validator(self):
        prompt = CheckboxPrompt(
            message="",
            choices=self.choices,
            validate=lambda x: len(x) > 2,
            invalid_message="hello",
        )
        with patch("prompt_toolkit.utils.Event") as mock:
            self.assertEqual(prompt._invalid, False)
            event = mock.return_value
            prompt._handle_enter(event)
            self.assertEqual(prompt._invalid, True)
            self.assertEqual(prompt._invalid_message, "hello")

    def test_kb(self):
        prompt = CheckboxPrompt(message="", choices=self.choices)
        prompt._invalid = True

        @prompt.register_kb("b")
        def test(_):
            pass

        test("")  # type: ignore
        self.assertEqual(prompt._invalid, False)

    def test_checkbox_enter_empty(self):
        prompt = CheckboxPrompt(message="", choices=["haah", "haha", "what"])
        with patch("prompt_toolkit.utils.Event") as mock:
            event = mock.return_value
            prompt._handle_enter(event)
        self.assertEqual(prompt.status["result"], [])
示例#17
0
from InquirerPy import prompt
from InquirerPy.base import Choice
from InquirerPy.separator import Separator

question1_choice = [
    Separator(),
    Choice("ap-southeast-2", name="Sydney", enabled=True),
    Choice("ap-southeast-1", name="Singapore", enabled=False),
    Separator(),
    "us-east-1",
    "us-west-1",
    Separator(),
]


def question2_choice(_):
    return [
        "Apple",
        "Cherry",
        "Orange",
        "Peach",
        "Melon",
        "Strawberry",
        "Grapes",
    ]


def main():
    questions = [
        {
            "type": "checkbox",
示例#18
0
文件: fabfile.py 项目: nyssance/Free
def install(c, pypi_mirror=True):
    """安装"""
    questions = [{
        'type': 'list',
        'message': gettext('HTTP Proxy'),
        'choices': ['127.0.0.1:7890', Choice('', 'No proxy')],
        'name': 'proxy'
    }, {
        'type': 'checkbox',
        'message': gettext('install'),
        'instruction': '(Space for select)',
        'transformer': lambda result: ', '.join(result) if len(result) > 0 else '',
        'validate': lambda result: len(result) > 0,
        'invalid_message': 'should be at least 1 selection',
        'choices': [
            Separator(),
            Choice('android', 'Android'),
            Choice('ios', 'iOS / macOS'),
            Choice('java', 'Java'),
            Choice('python', 'Python'),
            Separator('-- Database ---'),
            Choice('mysql', 'MySQL'),
            Choice('redis', 'Redis'),
            Separator('-- Front-end --'),
            Choice('angular', 'Angular'),
            'gulp',
            Separator('-- Apps -------'),
            Choice('apps', 'GitHub Desktop, Google Chrome, Postman, Visual Studio Code'),
            Separator('-- Fonts ------'),
            Choice('font-cascadia-code', 'Cascadia Code'),
            Choice('font-fira-code', 'Fira Code'),
            Separator('-- Others -----'),
            Choice('docker', 'Docker'),
            'docsify'
            'fastlane',
            Choice('mysqlworkbench', 'MySQL Workbench'),
            Separator()
        ],
        'name': 'roles'
    }]  # yapf: disable
    result = prompt(questions)
    proxy = result['proxy']
    roles = result['roles']
    if not roles:
        return
    if HTTP_PROXY != proxy:
        c.run(f'sed -i "" "s|HTTP_PROXY = \'{HTTP_PROXY}\'|HTTP_PROXY = \'{proxy}\'|g" fabfile.py')
    # if 'zh_CN' in locale.getdefaultlocale():
    #     hint('configure RubyGems')
    #     c.run('gem sources --add https://mirrors.aliyun.com/rubygems/ --remove https://rubygems.org/')
    if 'android' in roles:
        hint('install Android Studio, ktlint')
        c.run('brew install --cask android-studio')
        c.run('brew install ktlint')
    if 'ios' in roles:
        hint('install CocoaPods, SwiftFormat, SwiftLint')
        c.run('brew install cocoapods swiftformat swiftlint')
    if 'java' in roles:
        hint('install OpenJDK')
        c.run('brew install openjdk')
    if 'python' in roles:
        hint('install Pipenv, Black, isort, Pylint, YAPF')
        c.run(f'pip install pipenv black isort pylint yapf{f" -i {PYPI_MIRROR}" if pypi_mirror else ""}')
    # 数据库
    if 'mysql' in roles:
        hint('install MySQL')
        c.run('brew install mysql')
    if 'redis' in roles:
        hint('install Redis')
        c.run('brew install redis')
    # 前端
    if 'angular' in roles or 'gulp' in roles:
        hint('install Node.js')
        c.run('brew install node')
        if 'zh_CN' in locale.getdefaultlocale():
            hint('configure npm')
            c.run('npm config set registry https://registry.npmmirror.com')
    if 'angular' in roles:
        hint('install Angular CLI')
        c.run('npm install -g @angular/cli')
    if 'gulp' in roles:
        hint('install gulp-cli')
        c.run('npm install -g gulp-cli')
    if 'docsify' in roles:
        hint('install docsify-cli')
        c.run('npm install -g docsify-cli')
    # 应用
    if 'apps' in roles:
        hint('install GitHub Desktop, Google Chrome, Postman, Visual Studio Code')
        c.run('brew install --cask github google-chrome postman visual-studio-code')
    # 字体
    if 'font-cascadia-code' in roles:
        hint('install Cascadia Code')
        c.run('brew tap homebrew/cask-fonts')
        c.run('brew install --cask font-cascadia-code')
    if 'font-fira-code' in roles:
        hint('install Fira Code')
        c.run('brew tap homebrew/cask-fonts')
        c.run('brew install --cask font-fira-code')
    # 其他
    if 'docker' in roles:
        hint('install Docker')
        c.run('brew install --cask docker')
    if 'fastlane' in roles:
        hint('install fastlane')
        c.run('brew install fastlane')
    if 'mysqlworkbench' in roles:
        hint('install MySQL Workbench')
        c.run('brew install --cask mysqlworkbench')
    cleanup(c)
示例#19
0
def init(dirname: str = typer.Argument(".")):
    dirname = Path(dirname)

    basemap_zoom = 18  # TODO: Fix

    if Path(dirname.joinpath(FILENAME)).exists():
        typer.Abort()

    if not dirname.is_dir():
        typer.Abort()

    shortdirname = dirname.resolve().name

    uid = inquirer.text(message="Twin ID:", default=shortdirname).execute()

    location_keywords = None
    location = None
    bbox = []
    default_name = ""

    while True:
        location_keywords = inquirer.text(
            message="Location keywords (leave blank to skip):",
        ).execute()

        if not location_keywords:
            break

        geolocator = Nominatim(user_agent="owntwin-cli")
        location_candidates = geolocator.geocode(
            location_keywords, exactly_one=False, limit=5
        )

        if not location_candidates:
            typer.echo("Not found. Please Try again.")
            continue

        location = inquirer.select(
            message="Select nearby location:",
            choices=list(
                map(lambda x: {"name": x.address, "value": x}, location_candidates)
            )
            + [Separator(), {"name": "(Back)", "value": False}],
        ).execute()

        if location:
            break

    if not location_keywords:

        def validate(text):
            try:
                return len(tuple(map(lambda x: float(x.strip()), text.split(",")))) == 2
            except:
                return False

        location_coordinate = inquirer.text(
            message="Location coordinate [latitude, longitude] (leave blank to skip):",
            validate=validate,
            filter=lambda text: tuple(map(lambda x: float(x.strip()), text.split(","))),
        ).execute()
        location = namedtuple("location", ["latitude", "longitude", "address"])
        location.latitude, location.longitude = location_coordinate
        location.address = ""

    if location:
        lat, lng = location.latitude, location.longitude
        # print(location, lat, lng)
        size = inquirer.text(
            message="Side length (meter):",
            filter=lambda x: float(x),
            validate=NumberValidator(float_allowed=True),
        ).execute()

        # bbox = [
        #     lng + utils.meter_to_lng(size, lat, lng),  # east
        #     lat - utils.meter_to_lat(size, lat, lng),  # south
        #     lng - utils.meter_to_lng(size, lat, lng),  # west
        #     lat + utils.meter_to_lat(size, lat, lng),  # north
        # ]
        bbox = [
            lng - utils.meter_to_lng(size, lat, lng),  # west
            lat - utils.meter_to_lat(size, lat, lng),  # south
            lng + utils.meter_to_lng(size, lat, lng),  # east
            lat + utils.meter_to_lat(size, lat, lng),  # north
        ]
        tiles = mercantile.tiles(*bbox, basemap_zoom)
        tiles = list(tiles)
        basemap_bbox = utils.tiles_bounds(tiles)
        bbox = basemap_bbox

        typer.echo(
            "  Left (lng): {}\n  Bottom (lat): {}\n  Right (lng): {}\n  Top (lat): {}".format(
                *bbox
            )
        )
        typer.confirm("Is this OK?", default=True, abort=True)
        default_name = location.address

    name = inquirer.text(message="Twin name:", default=default_name).execute()
    type = inquirer.text(message="Twin type:", default="").execute()
    iri = inquirer.text(
        message="IRI or URL:", default=f"https://beta.owntwin.com/twin/{uid}"
    ).execute()
    description = inquirer.text(message="Description:", default="").execute()

    twin = {
        "id": uid,
        "name": name,
        "type": type,
        "type_label": type,
        "iri": iri,
        "description": description,
        "bbox": bbox,
        "canvas": {
            "width": 1024,
            "height": 1024,
        },
        "terrain": {
            "path": "assets/levelmap.json",
        },
        "building": {
            "path": "assets/buildings.json",
        },
        "modules": {},
    }

    # twin = {
    #     "name": name,
    #     ...
    #     "terrain": "levelmap.json",
    #     "objects": {
    #       "building": "building.json",
    #     },
    #     "modules": {},
    # }

    typer.echo(f"About to create {FILENAME}:\n")
    typer.echo(json.dumps(twin, ensure_ascii=False, indent=2))
    typer.confirm("Is this OK?", default=True, abort=True)

    if not dirname.exists():
        dirname.mkdir()

    save_config(twin, dirname.joinpath(FILENAME))
示例#20
0
class TestExpandPrompt(unittest.TestCase):
    choices = [
        Separator(),
        {
            "name": "hello",
            "value": "world",
            "key": "b"
        },
        Separator("**********"),
        ExpandChoice(name="foo", value="boo", key="f"),
    ]

    def test_content_control(self):
        expand_help = ExpandHelp(message="(haha)")
        content_control = InquirerPyExpandControl(
            choices=self.choices,
            default="f",
            expand_help=expand_help,
            expand_pointer=">> ",
            pointer=" ",
            separator=") ",
            marker=">",
            session_result=None,
            multiselect=True,
            marker_pl=" ",
        )
        self.assertEqual(content_control._pointer, " ")
        self.assertEqual(content_control._marker, ">")
        self.assertEqual(content_control._separator, ") ")
        self.assertEqual(content_control._expanded, False)
        self.assertEqual(content_control._key_maps, {"b": 1, "f": 3, "h": 4})
        self.assertEqual(content_control._expand_pointer, ">> ")
        self.assertEqual(
            content_control.choices,
            [
                {
                    "name": "---------------",
                    "value": ANY,
                    "enabled": False
                },
                {
                    "key": "b",
                    "name": "hello",
                    "value": "world",
                    "enabled": False
                },
                {
                    "name": "**********",
                    "value": ANY,
                    "enabled": False
                },
                {
                    "key": "f",
                    "name": "foo",
                    "value": "boo",
                    "enabled": False
                },
                {
                    "key": "h",
                    "name": "(haha)",
                    "value": expand_help,
                    "enabled": False,
                },
            ],
        )
        self.assertIsInstance(content_control.choices[0]["value"], Separator)

        self.assertEqual(
            content_control._get_formatted_choices(),
            [("class:pointer", ">> "), ("", "foo")],
        )
        self.assertEqual(
            content_control._get_hover_text(content_control.choices[1]),
            [
                ("class:pointer", " "),
                ("class:marker", " "),
                ("class:pointer", "b) "),
                ("[SetCursorPosition]", ""),
                ("class:pointer", "hello"),
            ],
        )
        self.assertEqual(
            content_control._get_normal_text(content_control.choices[1]),
            [("", " "), ("class:marker", " "), ("", "b) "), ("", "hello")],
        )

    def test_content_control_exceptions(self):
        self.assertRaises(
            InvalidArgument,
            InquirerPyExpandControl,
            ["asdfasfd", {
                "name": "hello",
                "value": "hello",
                "key": "j"
            }],
            "f",
            "",
            "",
            "",
            "",
            "",
            None,
            False,
            " ",
        )

        self.assertRaises(
            RequiredKeyNotFound,
            InquirerPyExpandControl,
            [
                {
                    "name": "foo",
                    "value": "boo"
                },
                {
                    "name": "hello",
                    "value": "hello",
                    "key": "j"
                },
            ],
            "f",
            "",
            "",
            "",
            "",
            "",
            None,
            False,
            " ",
        )

    def test_prompt(self):
        prompt = ExpandPrompt(
            message="Choose one of the following",
            default="boo",
            choices=self.choices,
            vi_mode=True,
            help_msg="What",
        )
        self.assertEqual(prompt.content_control.selected_choice_index, 3)
        self.assertEqual(prompt.instruction, "(bfh)")
        prompt._instruction = "hello"
        self.assertEqual(prompt.instruction, "hello")

    @patch.object(BaseComplexPrompt, "register_kb")
    def test_kb_added(self, mocked_add):
        prompt = ExpandPrompt(
            message="hello",
            choices=self.choices,
        )
        try:
            mocked_add.assert_has_calls([call("b", filter=True)])
            self.fail("kb should be added in after_render")
        except:
            pass
        prompt._on_rendered("")
        mocked_add.assert_has_calls([call("f")])
        mocked_add.assert_has_calls([call("h")])

    def test_prompt_message(self):
        prompt = ExpandPrompt(message="Choose one", choices=self.choices)
        self.assertEqual(
            prompt._get_prompt_message(),
            [
                ("class:questionmark", "?"),
                ("class:question", " Choose one"),
                ("class:instruction", " (bfh) "),
                ("class:input", "b"),
            ],
        )

        prompt = ExpandPrompt(message="Choose one",
                              choices=self.choices,
                              default="f")
        self.assertEqual(
            prompt._get_prompt_message(),
            [
                ("class:questionmark", "?"),
                ("class:question", " Choose one"),
                ("class:instruction", " (bfh) "),
                ("class:input", "f"),
            ],
        )
        prompt._handle_up(None)
        prompt._handle_up(None)
        prompt._handle_down(None)
        self.assertEqual(
            prompt._get_prompt_message(),
            [
                ("class:questionmark", "?"),
                ("class:question", " Choose one"),
                ("class:instruction", " (bfh) "),
                ("class:input", "f"),
            ],
        )
        prompt.content_control._expanded = True
        prompt._handle_down(None)
        self.assertEqual(
            prompt._get_prompt_message(),
            [
                ("class:questionmark", "?"),
                ("class:question", " Choose one"),
                ("class:instruction", " (bfh) "),
                ("class:input", "b"),
            ],
        )

        prompt.status["result"] = "foo"
        prompt.status["answered"] = True
        self.assertEqual(
            prompt._get_prompt_message(),
            [
                ("class:answermark", "?"),
                ("class:answered_question", " Choose one"),
                ("class:answer", " foo"),
            ],
        )

    def test_bindings(self):
        prompt = ExpandPrompt(message="Choose one", choices=self.choices)
        prompt.content_control._expanded = True
        self.assertEqual(prompt.content_control.selected_choice_index, 1)
        prompt._handle_down(None)
        self.assertEqual(prompt.content_control.selected_choice_index, 3)
        prompt._handle_down(None)
        self.assertEqual(prompt.content_control.selected_choice_index, 1)
        prompt._handle_up(None)
        self.assertEqual(prompt.content_control.selected_choice_index, 3)
        with patch("prompt_toolkit.utils.Event") as mock:
            event = mock.return_value
            prompt._handle_enter(event)
        self.assertEqual(prompt.status["result"], "foo")
        self.assertEqual(prompt.status["answered"], True)
        self.assertEqual(prompt.status["skipped"], False)

    def test_key_not_expand(self):
        expand_help = ExpandHelp()
        prompt = ExpandPrompt(message="",
                              choices=self.choices,
                              expand_help=expand_help,
                              multiselect=True)
        self.assertEqual(
            prompt.content_control.choices,
            [
                {
                    "enabled": False,
                    "name": "---------------",
                    "value": ANY
                },
                {
                    "enabled": False,
                    "key": "b",
                    "name": "hello",
                    "value": "world"
                },
                {
                    "enabled": False,
                    "name": "**********",
                    "value": ANY
                },
                {
                    "enabled": False,
                    "key": "f",
                    "name": "foo",
                    "value": "boo"
                },
                {
                    "enabled": False,
                    "key": "h",
                    "name": "Help, list all choices",
                    "value": expand_help,
                },
            ],
        )
        self.assertEqual(prompt.content_control.selected_choice_index, 1)
        prompt._handle_down(None)
        self.assertEqual(prompt.content_control.selected_choice_index, 1)
        prompt._handle_up(None)
        self.assertEqual(prompt.content_control.selected_choice_index, 1)
        prompt._handle_toggle_choice(None)
        self.assertEqual(
            prompt.content_control.selection,
            {
                "enabled": False,
                "key": "b",
                "name": "hello",
                "value": "world"
            },
        )
        prompt._handle_toggle_all(None)
        self.assertEqual(
            prompt.content_control.choices,
            [
                {
                    "enabled": False,
                    "name": "---------------",
                    "value": ANY
                },
                {
                    "enabled": False,
                    "key": "b",
                    "name": "hello",
                    "value": "world"
                },
                {
                    "enabled": False,
                    "name": "**********",
                    "value": ANY
                },
                {
                    "enabled": False,
                    "key": "f",
                    "name": "foo",
                    "value": "boo"
                },
                {
                    "enabled": False,
                    "key": "h",
                    "name": "Help, list all choices",
                    "value": expand_help,
                },
            ],
        )

    def test_key_expand(self):
        expand_help = ExpandHelp()
        prompt = ExpandPrompt(message="",
                              choices=self.choices,
                              expand_help=expand_help,
                              multiselect=True)
        prompt.content_control._expanded = True
        prompt._handle_toggle_choice(None)
        self.assertEqual(
            prompt.content_control.selection,
            {
                "enabled": True,
                "key": "b",
                "name": "hello",
                "value": "world"
            },
        )
        prompt._handle_toggle_choice(None)
        self.assertEqual(
            prompt.content_control.selection,
            {
                "enabled": False,
                "key": "b",
                "name": "hello",
                "value": "world"
            },
        )
        prompt._handle_toggle_all(None)
        self.assertEqual(
            prompt.content_control.choices,
            [
                {
                    "enabled": False,
                    "name": "---------------",
                    "value": ANY
                },
                {
                    "enabled": True,
                    "key": "b",
                    "name": "hello",
                    "value": "world"
                },
                {
                    "enabled": False,
                    "name": "**********",
                    "value": ANY
                },
                {
                    "enabled": True,
                    "key": "f",
                    "name": "foo",
                    "value": "boo"
                },
                {
                    "enabled": False,
                    "key": "h",
                    "name": "Help, list all choices",
                    "value": expand_help,
                },
            ],
        )
        prompt._handle_toggle_all(None, True)
        prompt._handle_toggle_all(None)
        self.assertEqual(
            prompt.content_control.choices,
            [
                {
                    "enabled": False,
                    "name": "---------------",
                    "value": ANY
                },
                {
                    "enabled": False,
                    "key": "b",
                    "name": "hello",
                    "value": "world"
                },
                {
                    "enabled": False,
                    "name": "**********",
                    "value": ANY
                },
                {
                    "enabled": False,
                    "key": "f",
                    "name": "foo",
                    "value": "boo"
                },
                {
                    "enabled": False,
                    "key": "h",
                    "name": "Help, list all choices",
                    "value": expand_help,
                },
            ],
        )

    def test_choice_missing_key(self):
        expand_help = ExpandHelp()
        choices = [
            ExpandChoice(1),
            ExpandChoice(2),
            ExpandChoice("ava"),
            ExpandChoice("Bva"),
        ]

        prompt = ExpandPrompt(message="Select one:",
                              choices=choices,
                              expand_help=expand_help)

        self.assertEqual(
            prompt.content_control.choices,
            [
                {
                    "enabled": False,
                    "key": "1",
                    "name": "1",
                    "value": 1
                },
                {
                    "enabled": False,
                    "key": "2",
                    "name": "2",
                    "value": 2
                },
                {
                    "enabled": False,
                    "key": "a",
                    "name": "ava",
                    "value": "ava"
                },
                {
                    "enabled": False,
                    "key": "b",
                    "name": "Bva",
                    "value": "Bva"
                },
                {
                    "enabled": False,
                    "key": "h",
                    "name": "Help, list all choices",
                    "value": expand_help,
                },
            ],
        )
示例#21
0
ANIMATION_FLAG = Event()
ANIMATION_THREAD: Optional[Thread] = None
HIDDEN = '[hidden]'
NO_EMPTY = 'Cannot be empty'
COUNTRY_CODES = [
	Choice('CH', name='Switzerland'),
	Choice('DE', name='Germany'),
	Choice('US', name='United States of America (the)'),
	Choice('AU', name='Australia'),
	Choice('GB', name='United Kingdom of Great Britain and Northern Ireland (the)'),
	Choice('FR', name='France'),
	Choice('IT', name='Italy'),
	Choice('PL', name='Poland'),
	Choice('PT', name='Portugal'),
	Choice('BR', name='Brazil'),
	Separator(),
	Choice('AF', name='Afghanistan'),
	Choice('AL', name='Albania'),
	Choice('DZ', name='Algeria'),
	Choice('AS', name='American Samoa'),
	Choice('AD', name='Andorra'),
	Choice('AO', name='Angola'),
	Choice('AI', name='Anguilla'),
	Choice('AQ', name='Antarctica'),
	Choice('AG', name='Antigua and Barbuda'),
	Choice('AR', name='Argentina'),
	Choice('AM', name='Armenia'),
	Choice('AW', name='Aruba'),
	Choice('AT', name='Austria'),
	Choice('AZ', name='Azerbaijan'),
	Choice('BS', name='Bahamas (the)'),
示例#22
0
class TestRawList(unittest.TestCase):
    choices = [
        {
            "name": "foo",
            "value": "boo",
            "enabled": True
        },
        "hello",
        Separator(),
        "yes",
    ]

    def test_content_control(self):
        content_control = InquirerPyRawlistControl(self.choices, "yes", " ",
                                                   ") ", ">", None, True, " ")
        self.assertEqual(content_control._pointer, " ")
        self.assertEqual(content_control._separator, ") ")
        self.assertEqual(content_control.choice_count, 4)
        self.assertEqual(content_control.selected_choice_index, 3)
        self.assertEqual(
            content_control._get_hover_text(content_control.choices[0]),
            [
                ("class:pointer", " "),
                ("class:marker", ">"),
                ("class:pointer", "1) "),
                ("[SetCursorPosition]", ""),
                ("class:pointer", "foo"),
            ],
        )
        self.assertEqual(
            content_control._get_normal_text(content_control.choices[0]),
            [("", " "), ("class:marker", ">"), ("", "1) "), ("", "foo")],
        )
        self.assertEqual(
            content_control.choices,
            [
                {
                    "actual_index": 0,
                    "display_index": 1,
                    "name": "foo",
                    "value": "boo",
                    "enabled": True,
                },
                {
                    "actual_index": 1,
                    "display_index": 2,
                    "name": "hello",
                    "value": "hello",
                    "enabled": False,
                },
                {
                    "name": "---------------",
                    "value": ANY,
                    "enabled": False
                },
                {
                    "actual_index": 3,
                    "display_index": 3,
                    "name": "yes",
                    "value": "yes",
                    "enabled": False,
                },
            ],
        )
        self.assertEqual(
            content_control._get_formatted_choices(),
            [
                ("", " "),
                ("class:marker", ">"),
                ("", "1) "),
                ("", "foo"),
                ("", "\n"),
                ("", " "),
                ("class:marker", " "),
                ("", "2) "),
                ("", "hello"),
                ("", "\n"),
                ("", " "),
                ("class:marker", " "),
                ("class:separator", "---------------"),
                ("", "\n"),
                ("class:pointer", " "),
                ("class:marker", " "),
                ("class:pointer", "3) "),
                ("[SetCursorPosition]", ""),
                ("class:pointer", "yes"),
            ],
        )

        content_control = InquirerPyRawlistControl(self.choices, 2, " ", ")",
                                                   ">", None, False, " ")
        self.assertEqual(content_control.selected_choice_index, 1)

    def test_content_control_exceptions(self):
        choices = [{"hello": "hello"}]
        self.assertRaises(
            RequiredKeyNotFound,
            InquirerPyRawlistControl,
            choices,
            "",
            "",
            "",
            "",
            None,
            False,
            " ",
        )

        choices = [Separator(), Separator()]
        self.assertRaises(
            InvalidArgument,
            InquirerPyRawlistControl,
            choices,
            "",
            "",
            "",
            "",
            None,
            True,
            " ",
        )

        choices = []
        self.assertRaises(
            InvalidArgument,
            InquirerPyRawlistControl,
            choices,
            "",
            "",
            "",
            "",
            None,
            False,
            " ",
        )

    def test_prompt(self):
        rawlist_prompt = RawlistPrompt(
            message="hello",
            choices=self.choices,
            default="hello",
            separator=".",
            instruction="bb",
        )
        self.assertEqual(rawlist_prompt.instruction, "bb")
        self.assertEqual(rawlist_prompt._message, "hello")

    def test_minimum_args(self):
        RawlistPrompt(message="what", choices=self.choices)

    def test_prompt_message(self):
        prompt = RawlistPrompt(
            message="hello",
            choices=self.choices,
            default="hello",
            separator=".",
            instruction="bb",
        )
        self.assertEqual(
            prompt._get_prompt_message(),
            [
                ("class:questionmark", "?"),
                ("class:question", " hello"),
                ("class:instruction", " bb "),
                ("class:input", "2"),
            ],
        )
        prompt.status["answered"] = True
        prompt.status["result"] = []
        self.assertEqual(
            prompt._get_prompt_message(),
            [
                ("class:answermark", "?"),
                ("class:answered_question", " hello"),
                ("class:answer", " []"),
            ],
        )

    def test_prompt_bindings(self):
        prompt = RawlistPrompt(
            message="hello",
            choices=self.choices,
            default="hello",
            separator=".",
            instruction="bb",
        )
        self.assertEqual(prompt.content_control.selected_choice_index, 1)
        prompt._handle_down(None)
        self.assertEqual(prompt.content_control.selected_choice_index, 3)
        prompt._handle_down(None)
        self.assertEqual(prompt.content_control.selected_choice_index, 0)
        prompt._handle_up(None)
        self.assertEqual(prompt.content_control.selected_choice_index, 3)
        prompt._handle_up(None)
        self.assertEqual(prompt.content_control.selected_choice_index, 1)

        self.assertEqual(prompt.status["result"], None)
        self.assertEqual(prompt.status["answered"], False)
        with patch("prompt_toolkit.utils.Event") as mock:
            event = mock.return_value
            prompt._handle_enter(event)
        self.assertEqual(prompt.status["result"], "hello")
        self.assertEqual(prompt.status["answered"], True)

    @patch.object(BaseComplexPrompt, "register_kb")
    def test_kb_added(self, mocked_add):
        prompt = RawlistPrompt(
            message="hello",
            choices=self.choices,
            default="hello",
            separator=".",
            instruction="bb",
        )
        prompt._on_rendered("")
        mocked_add.assert_has_calls([call("1")])
        mocked_add.assert_has_calls([call("2")])
        mocked_add.assert_has_calls([call("3")])

    def test_rawlist_10(self):
        prompt = RawlistPrompt(message="", choices=[i for i in range(10)])
        self.assertRaises(InvalidArgument, prompt._on_rendered, "")
        prompt = RawlistPrompt(message="", choices=[i for i in range(9)])
        prompt._after_render(None)