Пример #1
0
def main(args):
    pb = PushBullet()

    try:
        pb.retrieve_devices()
    except InvalidAccessTokenError:
        if not prompt_for_api_key(pb):
            return False
    command_completer = CommandCompleter(pb)

    def loop(txt):
        if 'quit' == txt.lower():
            exit(0)
        elif 'devices' == txt.lower():
            for device in pb.devices:
                if not isinstance(device, AllDevice):
                    print(device)
        elif 'help' == txt.lower():
            print(help_string)
        elif '' == txt.lower():
            pass
        else:
            try:
                command, device, msg = parse(txt, pb.devices,
                                             pb.valid_commands)
                pb.push(command, device, msg)
            except UnknownCommandError:
                print('Unknown command, try \'help\' for a list of valid ones')
            except UnknownDeviceError:
                print('Device name not recognized')

    if args:
        loop(' '.join(args))
    else:
        try:
            while True:
                text = get_input('> ', completer=command_completer)
                loop(text)
        except KeyboardInterrupt:
            return
Пример #2
0
class CompleterTestCase(unittest.TestCase):

    def setUp(self):
        self.pushbullet = PushBullet()
        self.completer = CommandCompleter(self.pushbullet)

    def test_command_list(self):
        document = MockDocument('')
        words = [i.text for i in self.completer.get_completions(document, None)]
        self.assertIn('help', words)
        self.assertIn('quit', words)
        self.assertIn('note', words)
        self.assertIn('link', words)
        self.assertIn('devices', words)

    def test_device_list(self):
        document = MockDocument('note ')
        words = [i.text for i in self.completer.get_completions(document, None)]
        devices = [i.name.lower() for i in self.pushbullet.devices]
        for d in devices:
            self.assertIn(d, words)
        self.assertIn('all', words)

    def test_device_list_partial_match(self):
        document = MockDocument('note al')
        words = [i.text for i in self.completer.get_completions(document, None)]
        self.assertIn('all', words)
        self.assertLess(len(words), len(self.pushbullet.devices))

    def test_note_message(self):
        document = MockDocument('note all dsfewfg')
        words = [i.display for i in self.completer.get_completions(document, None)]
        self.assertEqual(['Message to push'], words)

    def test_link_url_message(self):
        document = MockDocument('link all http://xkcd')
        words = [i.display for i in self.completer.get_completions(document, None)]
        self.assertEqual(['URL to push'], words)

    def test_link_url_optional_body(self):
        document = MockDocument('link all http://xkcd.com ')
        words = [i.display for i in self.completer.get_completions(document, None)]
        self.assertEqual(['[Optional] Message to push'], words)
Пример #3
0
    def _create_cli(self):
        """Creates a new cli"""
        history = FileHistory('.history')

        def toolbar_handler(_):
            """Returns bottom menu items.
            Args:
                * _: An instance of prompt_toolkit's Cli (not used).
            Returns:
                A list of Token.Toolbar.
            """
            return [(Token.Toolbar, ' [F9] Docs '),
                    (Token.Toolbar, ' [F10] Exit ')]

        def url_handler(_):
            if self.service.last_request is not None:
                method = ' ' + self.service.last_request['method']
                url = ' ' + self.service.last_request['url']
                headers = ''
                if self.service.last_request['headers'] is not None:
                    headers = ' ' + '; '.join([
                        key + ': ' + value for key, value in
                        self.service.last_request['headers'].items()
                    ])
                return [(Token.Method, method), (Token.Url, url),
                        (Token.Headers, headers)]
            return [(Token.Method, ''), (Token.Url, ''), (Token.Headers, '')]

        layout = self._create_layout(message='atomix> ',
                                     reserve_space_for_menu=8,
                                     lexer=CommandLexer,
                                     get_bottom_toolbar_tokens=toolbar_handler,
                                     get_url_tokens=url_handler)

        buffer = Buffer(history=history,
                        auto_suggest=CommandAutoSuggest(self.commands),
                        enable_history_search=True,
                        completer=CommandCompleter(self.commands),
                        complete_while_typing=Always(),
                        accept_action=AcceptAction.RETURN_DOCUMENT)

        key_manager = KeyBindingManager(enable_search=True,
                                        enable_abort_and_exit_bindings=True,
                                        enable_system_bindings=True,
                                        enable_auto_suggest_bindings=True)

        @key_manager.registry.add_binding(Keys.F9)
        def handle_f9(_):
            """Inputs the "docs" command when the `F9` key is pressed.
            Args:
                * _: An instance of prompt_toolkit's Event (not used).
            Returns:
                None.
            """
            webbrowser.open('http://atomix.io')

        @key_manager.registry.add_binding(Keys.F10)
        def handle_f10(_):
            """Quits when the `F10` key is pressed."""
            raise EOFError

        @key_manager.registry.add_binding(Keys.ControlSpace)
        def handle_ctrl_space(event):
            """Initializes autocompletion at the cursor.
            If the autocompletion menu is not showing, display it with the
            appropriate completions for the context.
            If the menu is showing, select the next completion.
            Args:
                * event: An instance of prompt_toolkit's Event.
            Returns:
                None.
            """
            b = event.cli.current_buffer
            if b.complete_state:
                b.complete_next()
            else:
                event.cli.start_completion(select_first=False)

        application = Application(mouse_support=False,
                                  style=get_style(self.theme),
                                  layout=layout,
                                  buffer=buffer,
                                  key_bindings_registry=key_manager.registry,
                                  on_exit=AbortAction.RAISE_EXCEPTION,
                                  on_abort=AbortAction.RETRY,
                                  ignore_case=True)

        eventloop = create_eventloop()

        return CommandLineInterface(application=application,
                                    eventloop=eventloop)
Пример #4
0
 def setUp(self):
     self.pushbullet = PushBullet()
     self.completer = CommandCompleter(self.pushbullet)