Example #1
0
def test_render_nested_pairs():
    text = [
        b"peak.allocated",
        10160336,
        b"lua.caches",
        0,
        b"db.0",
        [b"overhead.hashtable.main", 648, b"overhead.hashtable.expires", 32],
        b"db.1",
        [b"overhead.hashtable.main", 112, b"overhead.hashtable.expires", 32],
        b"fragmentation",
        b"0.062980629503726959",
        b"fragmentation.bytes",
        -9445680,
    ]

    assert renders.OutputRender.render_raw(text) == (
        b"peak.allocated\n10160336\nlua.caches\n0\ndb.0\noverhead.hashtable.main\n64"
        b"8\noverhead.hashtable.expires\n32\ndb.1\noverhead.hashtable.main\n112\nove"
        b"rhead.hashtable.expires\n32\nfragmentation\n0.062980629503726959\nfragmentat"
        b"ion.bytes\n-9445680")

    assert renders.OutputRender.render_nested_pair(text) == FormattedText([
        ("class:string", "peak.allocated: "),
        ("class:value", "10160336"),
        ("", "\n"),
        ("class:string", "lua.caches: "),
        ("class:value", "0"),
        ("", "\n"),
        ("class:string", "db.0: "),
        ("", "\n"),
        ("class:string", "    overhead.hashtable.main: "),
        ("class:value", "648"),
        ("", "\n"),
        ("class:string", "    overhead.hashtable.expires: "),
        ("class:value", "32"),
        ("", "\n"),
        ("class:string", "db.1: "),
        ("", "\n"),
        ("class:string", "    overhead.hashtable.main: "),
        ("class:value", "112"),
        ("", "\n"),
        ("class:string", "    overhead.hashtable.expires: "),
        ("class:value", "32"),
        ("", "\n"),
        ("class:string", "fragmentation: "),
        ("class:value", "0.062980629503726959"),
        ("", "\n"),
        ("class:string", "fragmentation.bytes: "),
        ("class:value", "-9445680"),
    ])
Example #2
0
def test_render_list_or_string():
    config.raw = False
    assert renders.OutputRender.render_list_or_string("") == '""'
    assert renders.OutputRender.render_list_or_string("foo") == '"foo"'
    assert renders.OutputRender.render_list_or_string(
        [b"foo", b"bar"]) == FormattedText([
            ("", "1)"),
            ("", " "),
            ("class:string", '"foo"'),
            ("", "\n"),
            ("", "2)"),
            ("", " "),
            ("class:string", '"bar"'),
        ])
Example #3
0
def show_help(extra= None):
    help_command = '''
    Core commands
    =============

        Command                    Description
        -------                    -----------
        help                       Help menu
        load <module>              Load module
        modules  [category]        List all modules or a certain category
        find <info>                Search modules with concret info
        exit|quit                  Exit application
        banner                     Show banner
        export                     Save global options  
        import                     Load global options (previously exported)
        tasks <show/kill> [id]     Show tasks running or kill a task
        theme dark|light|default   Change the theme of the tool
        # <command>                Grant terminal commands        
    '''
    help_command += '''
    Module commands
    ===============

        Command                    Description
        -------                    -----------
        set <option> <value>       Set value for module's option
        unset <option>             Unset value for module's option
        run                        Run module
        back                       Unload module                                        
        show [options|info]        Show either options or info 
        global <option> <value>    Set global option
    '''

    if extra:
        help_command += f"""
    Additional feature
    ==================

        Command                    Description
        -------                    -----------"""

        for k, v in extra.items():
            if len(k) > 26:
                k = k[:22] + "..."
            help_command += f"""
        {str(k).ljust(26)} {v}"""
        print("\n")
    
    text = FormattedText([(f'{ColorSelected().theme.text}', help_command)])
    print_formatted_text(text)
Example #4
0
def test_timestamp_completer_datetime_format_time_completion():
    c = TimestampCompleter()
    fake_document = MagicMock()
    fake_document.text = fake_document.text_before_cursor = "2020-02-07"
    completions = list(c.get_completions(fake_document, None))

    assert completions == [
        Completion(
            text="1581033600000",
            start_position=-10,
            display=FormattedText([("", "1581033600000")]),
            display_meta="2020-02-07T00:00:00+00:00",
        )
    ]
Example #5
0
 def error(self, source, header_text=''):
     if source is None:
         return
     if not self.app.batch_mode:
         self._tee_print(
             merge_formatted_text([
                 HTML('<ansired>--- </ansired>').formatted_text,
                 FormattedText([(PeekStyle.styles[TipsMinor], header_text)])
             ]),
             plain_source=f'--- {header_text}')
     if isinstance(source, FormattedText):
         self._tee_print(source)
     else:
         self._tee_print(source, plain_source=source)
Example #6
0
def command_syntax(command, command_info):
    """
    Get command syntax based on redis-doc/commands.json

    :param command: Command name in uppercase
    :param command_info: dict loaded from commands.json, only for
        this command.
    """
    comamnd_group = command_info["group"]
    bottoms = [
        ("class:bottom-toolbar.group", f"({comamnd_group}) "),
        ("class:bottom-toolbar.command", f"{command}"),
    ]  # final display FormattedText

    if command_info.get("arguments"):
        for argument in command_info["arguments"]:
            if argument.get("command"):
                # command [
                bottoms.append(
                    (f"class:bottom-toolbar.command", " [" + argument["command"])
                )
                if argument.get("enum"):
                    enums = "|".join(argument["enum"])
                    bottoms.append((f"class:bottom-toolbar.const", f" [{enums}]"))
                elif argument.get("name"):
                    bottoms.extend(
                        parse_argument_to_formatted_text(
                            argument["name"], argument["type"], argument.get("optional")
                        )
                    )
                # ]
                bottoms.append((f"class:bottom-toolbar.command", "]"))
            elif argument.get("enum"):
                enums = "|".join(argument["enum"])
                bottoms.append((f"class:bottom-toolbar.const", f" [{enums}]"))

            else:
                bottoms.extend(
                    parse_argument_to_formatted_text(
                        argument["name"], argument["type"], argument.get("optional")
                    )
                )
    if "since" in command_info:
        since = command_info["since"]
        bottoms.append(("class:bottom-toolbar.since", f"   since: {since}"))
    if "complexity" in command_info:
        complexity = command_info["complexity"]
        bottoms.append(("class:bottom-toolbar.complexity", f" complexity:{complexity}"))

    return FormattedText(bottoms)
def main():
    tokens = FormattedText([("fg:" + name, name + "  ")
                            for name in NAMED_COLORS])

    print(HTML("\n<u>Named colors, using 16 color output.</u>"))
    print("(Note that it doesn't really make sense to use named colors ")
    print("with only 16 color output.)")
    print(tokens, color_depth=ColorDepth.DEPTH_4_BIT)

    print(HTML("\n<u>Named colors, use 256 colors.</u>"))
    print(tokens)

    print(HTML("\n<u>Named colors, using True color output.</u>"))
    print(tokens, color_depth=ColorDepth.TRUE_COLOR)
Example #8
0
def test_newbie_mode_complete_with_meta_dict():
    config.newbie_mode = True
    session = prompt_session()
    fake_document = MagicMock()
    fake_document.text_before_cursor = "get"
    completions = list(session.completer.get_completions(fake_document, None))

    assert completions[:2] == [
        Completion(
            text="get",
            start_position=-3,
            display=FormattedText([("", "get")]),
            display_meta=FormattedText([("", "Get the value of a key")]),
        ),
        Completion(
            text="getset",
            start_position=-3,
            display=FormattedText([("", "getset")]),
            display_meta=FormattedText(
                [("", "Set the string value of a key and return its old value")]
            ),
        ),
    ]
Example #9
0
def test_render_unixtime_config_raw():
    # fake the timezone and reload
    os.environ["TZ"] = "Asia/Shanghai"
    time.tzset()
    rendered = renders.OutputRender.render_unixtime(1570469891)

    assert rendered == FormattedText([
        ("class:type", "(integer) "),
        ("", "1570469891"),
        ("", "\n"),
        ("class:type", "(local time)"),
        ("", " "),
        ("", "2019-10-08 01:38:11"),
    ])
def main():
    tokens = FormattedText([('fg:' + name, name + '  ')
                            for name in NAMED_COLORS])

    print(HTML('\n<u>Named colors, using 16 color output.</u>'))
    print('(Note that it doesn\'t really make sense to use named colors ')
    print('with only 16 color output.)')
    print(tokens, color_depth=ColorDepth.DEPTH_4_BIT)

    print(HTML('\n<u>Named colors, use 256 colors.</u>'))
    print(tokens)

    print(HTML('\n<u>Named colors, using True color output.</u>'))
    print(tokens, color_depth=ColorDepth.TRUE_COLOR)
Example #11
0
def test_render_time():
    value = [b"1571305643", b"765481"]
    assert renders.OutputRender.render_time(value) == FormattedText([
        ("class:type", "(unix timestamp) "),
        ("", "1571305643"),
        ("", "\n"),
        ("class:type", "(millisecond) "),
        ("", "765481"),
        ("", "\n"),
        ("class:type", "(convert to local timezone) "),
        ("", "2019-10-17 17:47:23.765481"),
    ])

    assert renders.OutputRender.render_raw(value) == b"1571305643\n765481"
Example #12
0
def render_list(byte_items, str_items, style=None):
    if config.raw:
        return b"\n".join(byte_items)
    index_width = len(str(len(str_items)))
    rendered = []
    for index, item in enumerate(str_items):
        index_const_width = f"{index+1:{index_width}})"
        rendered.append(("", index_const_width))
        if index + 1 < len(str_items):
            text = f" {item}\n"
        else:  # last one don't have \n
            text = f" {item}"
        rendered.append((style, text))
    return FormattedText(rendered)
Example #13
0
    def _internal_prompt_print(self, *args, **kwargs):

        kwargs['sep'] = kwargs.pop('sep', ' ')
        kwargs['end'] = kwargs.pop('end', '\n')
        kwargs['file'] = kwargs.pop('file', sys.stdout)
        kwargs['style'] = token_style
        frags = []
        for a in args:
            if isinstance(a, FormattedText):
                frags.append(a)
            else:
                frags.append(FormattedText([("class:command", str(a))]))

        print_formatted_text(*frags, **kwargs)
Example #14
0
def test_peek_list_fetch_all(iredis_client, clean_redis):
    clean_redis.lpush("mylist", *[f"hello-{index}" for index in range(5)])
    peek_result = list(iredis_client.do_peek("mylist"))

    assert peek_result == [
        FormattedText(
            [
                ("class:dockey", "key: "),
                ("", "list (quicklist)  mem: 176 bytes, ttl: -1"),
            ]
        ),
        FormattedText([("class:dockey", "llen: "), ("", "5")]),
        FormattedText([("class:dockey", "elements: ")]),
        FormattedText(
            [
                ("", "1)"),
                ("", " "),
                ("class:string", '"hello-4"'),
                ("", "\n"),
                ("", "2)"),
                ("", " "),
                ("class:string", '"hello-3"'),
                ("", "\n"),
                ("", "3)"),
                ("", " "),
                ("class:string", '"hello-2"'),
                ("", "\n"),
                ("", "4)"),
                ("", " "),
                ("class:string", '"hello-1"'),
                ("", "\n"),
                ("", "5)"),
                ("", " "),
                ("class:string", '"hello-0"'),
            ]
        ),
    ]
Example #15
0
def test_peek_hash_fetch_all(iredis_client, clean_redis):
    for key, value in zip(
        [f"hello-{index}" for index in range(3)], [f"hi-{index}" for index in range(3)]
    ):
        clean_redis.hset("myhash", key, value)
    peek_result = list(iredis_client.do_peek("myhash"))
    assert peek_result == [
        FormattedText(
            [("class:dockey", "key: "), ("", "hash (ziplist)  mem: 104 bytes, ttl: -1")]
        ),
        FormattedText([("class:dockey", "hlen: "), ("", "3")]),
        FormattedText([("class:dockey", "fields: ")]),
        FormattedText(
            [
                ("", "1)"),
                ("", " "),
                ("class:field", '"hello-0"'),
                ("", "\n"),
                ("", "   "),
                ("class:string", '"hi-0"'),
                ("", "\n"),
                ("", "2)"),
                ("", " "),
                ("class:field", '"hello-1"'),
                ("", "\n"),
                ("", "   "),
                ("class:string", '"hi-1"'),
                ("", "\n"),
                ("", "3)"),
                ("", " "),
                ("class:field", '"hello-2"'),
                ("", "\n"),
                ("", "   "),
                ("class:string", '"hi-2"'),
            ]
        ),
    ]
Example #16
0
    def get_clock(self):
        """make clock text"""
        if self.sec:
            clock = np.array([[background_char] * 124] * 14)
        else:
            clock = np.array([[background_char] * 80] * 14)
        now = dt.now()
        clock[1:13, 1:16] = self.get_number(now.hour // 10)
        clock[1:13, 20:35] = self.get_number(now.hour % 10)
        clock[1:13, 36:43] = self.get_coron()
        clock[1:13, 45:60] = self.get_number(now.minute // 10)
        clock[1:13, 64:79] = self.get_number(now.minute % 10)
        if self.sec:
            clock[1:13, 80:87] = self.get_coron()
            clock[1:13, 89:104] = self.get_number(now.second // 10)
            clock[1:13, 108:123] = self.get_number(now.second % 10)

        t = '\n'.join([''.join(x) for x in clock])
        # 5 min bofore, 15 min after events
        if self.color:
            b_event = []
            a_event = []
            for x in self.gcalender.events:
                if x['month'] == now.month and x['day'] == now.day and x[
                        'hour'] is not None:
                    d = (x['hour'] * 60 + x['minute']) - (now.hour * 60 +
                                                          now.minute)
                    if d <= 5 and d > 0:
                        b_event.append(x)
                    if d <= 0 and d >= -15:
                        a_event.append(x)

            if b_event:
                return FormattedText([('#FF0000', t)])
            if a_event:
                return FormattedText([('#008000', t)])
        return t
Example #17
0
def showwarning(message:Warning, category, filename, lineno, file=None, line=None):
    
    if category == UserWarning:
        if session.has_instance():
            ldi, tokens = session.get_vm().pc
            print_error_formatted(
                message, LineDebugInfo(ldi.filename, ldi.lineid, ldi.token_pos[max(-len(tokens)-1, -len(ldi.token_pos))]), 
                    session.is_interactive(), extra_indent=6 if session.is_interactive() else 0)
        else:
            print_formatted_text(FormattedText([
                ('magenta', 'Warning: '),
                ('', str(message))
            ]))
    else:
        return showwarning_default(message, category, filename, lineno, file, line)
Example #18
0
    def show_account_state(self, args):
        item = get_arg(args)

        if item is not None:
            account = Blockchain.Default().GetAccountState(item, print_all_accounts=True)

            if account is not None:
                bjson = json.dumps(account.ToJson(), indent=4)
                tokens = [("class:number", bjson)]
                print_formatted_text(FormattedText(tokens), style=self.token_style)
                print('\n')
            else:
                print("Account %s not found" % item)
        else:
            print("Please specify an account address")
Example #19
0
 def render_time(value):
     unix_timestamp, millisecond = value[0].decode(), value[1].decode()
     explained_date = time.strftime("%Y-%m-%d %H:%M:%S",
                                    time.localtime(int(unix_timestamp)))
     rendered = [
         ("class:type", "(unix timestamp) "),
         ("", unix_timestamp),
         NEWLINE_TUPLE,
         ("class:type", "(millisecond) "),
         ("", millisecond),
         NEWLINE_TUPLE,
         ("class:type", "(convert to local timezone) "),
         ("", f"{explained_date}.{millisecond}"),
     ]
     return FormattedText(rendered)
Example #20
0
def _CommandRun(command):
    line = FormattedText([('', '['), ('#ff0000', 'Out'), ('', ']')])

    process = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE)

    while True:
        output = process.stdout.readline()

        if output == b'' and process.poll() is not None:
            break
        if output:
            print_formatted_text(line, end="")
            print(">> " + output.strip().decode('utf-8'))
    rc = process.poll()
    return rc
Example #21
0
 def render_list(text, style="class:string"):
     """
     Render callback for redis Array Reply
     Note: Cloud be null in it.
     """
     str_items = []
     for item in text:
         if item is None:
             str_items.append(None)
         else:
             str_item = ensure_str(item)
             double_quoted = double_quotes(str_item)
             str_items.append(double_quoted)
     rendered = _render_list(text, str_items, style)
     return FormattedText(rendered)
Example #22
0
def test_peek_zset_fetch_part(iredis_client, clean_redis):
    clean_redis.zadd(
        "myzset",
        dict(zip([f"hello-{index}" for index in range(40)], range(40))))
    peek_result = list(iredis_client.do_peek("myzset"))
    assert peek_result[0][0:8] == FormattedText([
        ("class:dockey", "key: "),
        ("", "zset (ziplist)  mem: 556 bytes, ttl: -1"),
        ("", "\n"),
        ("class:dockey", "zcount: "),
        ("", "40"),
        ("", "\n"),
        ("class:dockey", "members (first 40): "),
        ("", "\n"),
    ])
Example #23
0
 def info(self, source, header_text=''):
     if source is None:
         return
     if not self.app.batch_mode:
         self._tee_print(
             FormattedText([
                 (PeekStyle.styles[Heading], '=== '),
                 (PeekStyle.styles[TipsMinor], header_text)
             ]),
             plain_source=f'=== {header_text}')
     if isinstance(source, FormattedText):
         self._tee_print(source)
     else:
         source, plain_source = self._try_jsonify(source)  # TODO: try more types
         self._tee_print(source, plain_source=plain_source)
Example #24
0
def test_newbie_mode_complete_with_meta_dict_command_is_lowercase():
    fake_document = MagicMock()
    fake_document.text_before_cursor = fake_document.text = "geor"
    completer = IRedisCompleter(hint=True)
    completions = list(completer.get_completions(fake_document, None))

    assert sorted([completion.display_meta for completion in completions]) == [
        FormattedText(
            [
                (
                    "",
                    "Query a sorted set representing a geospatial index to fetch members matching a given maximum distance from a member",  # noqa
                )
            ]
        ),
        FormattedText(
            [
                (
                    "",
                    "Query a sorted set representing a geospatial index to fetch members matching a given maximum distance from a point",  # noqa
                )
            ]
        ),
    ]
Example #25
0
    async def input_loop(self) -> None:
        while True:
            with patch_stdout():
                prompt_task = asyncio.create_task(
                    self.session.prompt_async(
                        FormattedText([('#ffffff', '> ')])))
                await asyncio.wait({prompt_task, self.shutdown},
                                   return_when=FIRST_COMPLETED)

                if self.shutdown.done():
                    break

                if prompt_task.done():
                    text = prompt_task.result()
                    self.publish(TextInput(text=text))
Example #26
0
    def show_contract_state(self, args):
        item = get_arg(args)

        if item is not None:

            if item.lower() == 'all':
                contracts = Blockchain.Default().ShowAllContracts()
                print("Contracts: %s" % contracts)
            elif item.lower() == 'search':
                query = get_arg(args, 1)
                if query:

                    contracts = Blockchain.Default().SearchContracts(
                        query=query)
                    print("Found %s results for %s" % (len(contracts), query))
                    for contract in contracts:
                        bjson = json.dumps(contract.ToJson(), indent=4)
                        tokens = [("class:number", bjson)]
                        print_formatted_text(FormattedText(tokens),
                                             style=self.token_style)
                        print('\n')
                else:
                    print("Please specify a search query")
            else:
                contract = Blockchain.Default().GetContract(item)

                if contract is not None:
                    contract.DetermineIsNEP5()
                    jsn = contract.ToJson()
                    bjson = json.dumps(jsn, indent=4)
                    tokens = [("class:number", bjson)]
                    print_formatted_text(FormattedText(tokens),
                                         style=self.token_style)
                    print('\n')
        else:
            print("Please specify a contract")
Example #27
0
def test_group_completer():
    fake_document = MagicMock()
    previous_commands = [
        "xgroup create abc world 123", "xgroup setid abc hello 123"
    ]
    fake_document.text = fake_document.text_before_cursor = "XGROUP DESTROY key "
    completer = IRedisCompleter()
    for command in previous_commands:
        completer.update_completer_for_input(command)
    completions = list(completer.get_completions(fake_document, None))
    assert completions == [
        Completion(
            text="hello",
            start_position=0,
            display=FormattedText([("", "hello")]),
            display_meta=FormattedText([("", "")]),
        ),
        Completion(
            text="world",
            start_position=0,
            display=FormattedText([("", "world")]),
            display_meta=FormattedText([("", "")]),
        ),
    ]
Example #28
0
def test_peek_string(iredis_client, clean_redis):
    clean_redis.set("foo", "bar")
    peek_result = list(iredis_client.do_peek("foo"))

    assert peek_result == [
        FormattedText([
            ("class:dockey", "key: "),
            ("", "string (embstr)  mem: 50 bytes, ttl: -1"),
            ("", "\n"),
            ("class:dockey", "strlen: "),
            ("", "3"),
            ("", "\n"),
            ("class:dockey", "value: "),
            ("", '"bar"'),
        ])
    ]
Example #29
0
def test_peek_zset_fetch_all(iredis_client, clean_redis):
    clean_redis.zadd(
        "myzset", dict(zip([f"hello-{index}" for index in range(3)],
                           range(3))))
    peek_result = list(iredis_client.do_peek("myzset"))
    assert peek_result[0][0:9] == FormattedText([
        ("class:dockey", "key: "),
        ("", "zset (ziplist)  mem: 92 bytes, ttl: -1"),
        ("", "\n"),
        ("class:dockey", "zcount: "),
        ("", "3"),
        ("", "\n"),
        ("class:dockey", "members: "),
        ("", "\n"),
        ("", "1)"),
    ])
Example #30
0
 def prompt(self) -> FormattedText:
     """Generate the Command Prompt as a FormattedText. This format is mostly
         only useful for things in PTK.
     """
     return FormattedText(
         [
             ("class:etc", self.prefix),
             (
                 "class:hostname" if self.namestyle is None else self.namestyle,
                 f"{self.username}@{self.hostname}",
             ),
             ("class:etc", ":"),
             ("class:path", str(self.path)),
             ("class:etc", self.char),
         ]
     )