예제 #1
0
 def write_console_ex(buf, otype):
     if otype == 0:
         if not SUPPRESS_STDOUT:
             buf = buf.replace("\r\n", "\n")
             sbuf = buf.split("\r")
             for i, b in enumerate(sbuf):
                 print_formatted_text(ANSI(b),
                                      end="",
                                      output=output)
                 if i < len(sbuf) - 1:
                     output.write("\r")
             output.flush()
             TERMINAL_CURSOR_AT_BEGINNING[0] = buf.endswith("\n")
     else:
         if not SUPPRESS_STDERR:
             buf = buf.replace("\r\n", "\n")
             sbuf = buf.split("\r")
             for i, b in enumerate(sbuf):
                 print_formatted_text(ANSI(stderr_format.format(b)),
                                      end="",
                                      output=output)
                 if i < len(sbuf) - 1:
                     output.write("\r")
             output.flush()
             TERMINAL_CURSOR_AT_BEGINNING[0] = buf.endswith("\n")
예제 #2
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")
예제 #3
0
def patched_handle_exception(self, e):
    """
    a new handler for ptpython repl exceptions
    it will call excepthook after ommitting all this framework's calls from traceback

    for the original, see ptpython.repl.PythonInput._handle_exception
    """
    output = self.app.output

    t, v, tb = sys.exc_info()

    # Required for pdb.post_mortem() to work.
    sys.last_type, sys.last_value, sys.last_traceback = t, v, tb

    # loop until getting actual traceback
    last_stdin_tb = tb
    while tb:
        if tb.tb_frame.f_code.co_filename == "<stdin>":
            last_stdin_tb = tb
        tb = tb.tb_next

    # except hook does not work as expected
    sys.excepthook(t, v, last_stdin_tb)
    # just print formatted exception for now
    formatted = better_exceptions.format_exception(t, v, last_stdin_tb)
    print_formatted_text(ANSI(formatted))

    output.write("%s\n" % e)
    output.flush()
예제 #4
0
 def show_mem(self):
     process = psutil.Process(os.getpid())
     total = process.memory_info().rss
     totalmb = total / (1024 * 1024)
     out = "Total: %s MB\n" % totalmb
     out += "Total buffers: %s\n" % StreamManager.TotalBuffers()
     print_formatted_text(FormattedText([("class:number", out)]), style=self.token_style)
예제 #5
0
    def show_state(self):
        height = Blockchain.Default().Height
        headers = Blockchain.Default().HeaderHeight

        diff = height - self.start_height
        now = datetime.datetime.utcnow()
        difftime = now - self.start_dt

        mins = difftime / datetime.timedelta(minutes=1)
        secs = mins * 60

        bpm = 0
        tps = 0
        if diff > 0 and mins > 0:
            bpm = diff / mins
            tps = Blockchain.Default().TXProcessed / secs

        out = "Progress: %s / %s\n" % (height, headers)
        out += "Block-cache length %s\n" % Blockchain.Default().BlockCacheCount
        out += "Blocks since program start %s\n" % diff
        out += "Time elapsed %s mins\n" % mins
        out += "Blocks per min %s \n" % bpm
        out += "TPS: %s \n" % tps
        tokens = [("class:number", out)]
        print_formatted_text(FormattedText(tokens), style=self.token_style)
예제 #6
0
def patched_handle_exception(self, e):
    j = KosmosShellConfig.j

    # Instead of just calling ``traceback.format_exc``, we take the
    # traceback and skip the bottom calls of this framework.
    t, v, tb = sys.exc_info()

    output = self.app.output
    # Required for pdb.post_mortem() to work.
    sys.last_type, sys.last_value, sys.last_traceback = t, v, tb

    # loop until getting actual traceback (without internal ptpython part)
    last_stdin_tb = tb
    while tb:
        if tb.tb_frame.f_code.co_filename == "<stdin>":
            last_stdin_tb = tb
        tb = tb.tb_next

    logdict = j.core.tools.log(tb=last_stdin_tb,
                               level=50,
                               exception=e,
                               stdout=False)
    formatted_tb = j.core.tools.log2str(logdict, data_show=True, replace=True)
    print_formatted_text(ANSI(formatted_tb))

    output.write("%s\n" % e)
    output.flush()
예제 #7
0
    def show_asset_state(self, args):
        item = get_arg(args)

        if item is not None:

            if item == 'search':
                query = get_arg(args, 1)
                results = Blockchain.Default().SearchAssetState(query)
                print("Found %s results for %s" % (len(results), query))
                for asset in results:
                    bjson = json.dumps(asset.ToJson(), indent=4)
                    tokens = [("class:number", bjson)]
                    print_formatted_text(FormattedText(tokens),
                                         style=self.token_style)
                    print('\n')

                return

            asset = Blockchain.Default().GetAssetState(item)

            if asset is not None:
                bjson = json.dumps(asset.ToJson(), indent=4)
                tokens = [("class:number", bjson)]
                print_formatted_text(FormattedText(tokens),
                                     style=self.token_style)
                print('\n')
            else:
                print("Asset %s not found" % item)
        else:
            print("Please specify an asset hash")
예제 #8
0
def get_config_and_history_file(
        namespace: argparse.Namespace) -> Tuple[str, str]:
    """
    Check which config/history files to use, ensure that the directories for
    these files exist, and return the config and history path.
    """
    config_dir = os.environ.get(
        "PTPYTHON_CONFIG_HOME",
        appdirs.user_config_dir("ptpython", "prompt_toolkit"),
    )
    data_dir = appdirs.user_data_dir("ptpython", "prompt_toolkit")

    # Create directories.
    for d in (config_dir, data_dir):
        pathlib.Path(d).mkdir(parents=True, exist_ok=True)

    # Determine config file to be used.
    config_file = os.path.join(config_dir, "config.py")
    legacy_config_file = os.path.join(os.path.expanduser("~/.ptpython"),
                                      "config.py")

    warnings = []

    # Config file
    if namespace.config_file:
        # Override config_file.
        config_file = os.path.expanduser(namespace.config_file)

    elif os.path.isfile(legacy_config_file):
        # Warn about the legacy configuration file.
        warnings.append(
            HTML(
                "    <i>~/.ptpython/config.py</i> is deprecated, move your configuration to <i>%s</i>\n"
            ) % config_file)
        config_file = legacy_config_file

    # Determine history file to be used.
    history_file = os.path.join(data_dir, "history")
    legacy_history_file = os.path.join(os.path.expanduser("~/.ptpython"),
                                       "history")

    if namespace.history_file:
        # Override history_file.
        history_file = os.path.expanduser(namespace.history_file)

    elif os.path.isfile(legacy_history_file):
        # Warn about the legacy history file.
        warnings.append(
            HTML(
                "    <i>~/.ptpython/history</i> is deprecated, move your history to <i>%s</i>\n"
            ) % history_file)
        history_file = legacy_history_file

    # Print warnings.
    if warnings:
        print_formatted_text(HTML("<u>Warning:</u>"))
        for w in warnings:
            print_formatted_text(w)

    return config_file, history_file
예제 #9
0
def stop_timer(timer):
    if timer:
        timer.stop()
        print_formatted_text('Stopped')
        timer = None
    else:
        print_formatted_text('No active timer')
    return timer
예제 #10
0
 def show_nodes(self):
     if len(NodeLeader.Instance().Peers) > 0:
         out = "Total Connected: %s\n" % len(NodeLeader.Instance().Peers)
         for peer in NodeLeader.Instance().Peers:
             out += "Peer %s - IO: %s\n" % (peer.Name(), peer.IOStats())
         print_formatted_text(FormattedText([("class:number", out)]), style=self.token_style)
     else:
         print("Not connected yet\n")
예제 #11
0
    def show_result(self, result: object) -> None:
        """
        Show __repr__ for an `eval` result.
        """
        out_prompt = to_formatted_text(self.get_output_prompt())

        # If the repr is valid Python code, use the Pygments lexer.
        result_repr = repr(result)
        try:
            compile(result_repr, "", "eval")
        except SyntaxError:
            formatted_result_repr = to_formatted_text(result_repr)
        else:
            formatted_result_repr = to_formatted_text(
                PygmentsTokens(list(_lex_python_result(result_repr))))

        # If __pt_repr__ is present, take this. This can return
        # prompt_toolkit formatted text.
        if hasattr(result, "__pt_repr__"):
            try:
                formatted_result_repr = to_formatted_text(
                    getattr(result, "__pt_repr__")())
                if isinstance(formatted_result_repr, list):
                    formatted_result_repr = FormattedText(
                        formatted_result_repr)
            except:
                pass

        # Align every line to the prompt.
        line_sep = "\n" + " " * fragment_list_width(out_prompt)
        indented_repr: StyleAndTextTuples = []

        lines = list(split_lines(formatted_result_repr))

        for i, fragment in enumerate(lines):
            indented_repr.extend(fragment)

            # Add indentation separator between lines, not after the last line.
            if i != len(lines) - 1:
                indented_repr.append(("", line_sep))

        # Write output tokens.
        if self.enable_syntax_highlighting:
            formatted_output = merge_formatted_text(
                [out_prompt, indented_repr])
        else:
            formatted_output = FormattedText(out_prompt + [(
                "", fragment_list_to_text(formatted_result_repr))])

        print_formatted_text(
            formatted_output,
            style=self._current_style,
            style_transformation=self.style_transformation,
            include_default_pygments_style=False,
            output=self.app.output,
        )
        self.app.output.flush()
예제 #12
0
def list_tasks(api_map, range_):
    if range_ == 'today':
        today = datetime.date.today()
        range_ = [today, today]
    elif range_ == 'week':
        today = datetime.date.today()
        start = today - datetime.timedelta(days=today.weekday())
        end = start + datetime.timedelta(days=6)
        range_ = [start, end]
    elif range_ == 'month':
        today = datetime.date.today()
        range_ = [
            today.replace(day=1),
            today.replace(day=1, month=today.month + 1) -
            datetime.timedelta(days=1)
        ]

    table = set()
    total = 0
    for account, api in api_map.items():
        records = api.users.time()
        me_id = str(api.users.me()['id'])

        record_map = {}
        record_names = {}
        for record in records:
            # 2018-06-18 04:44:33
            record_date = datetime.datetime.strptime(record['date'],
                                                     '%Y-%m-%d').date()
            if range_[1] >= record_date >= range_[0]:
                total += record['time']
                record_id = record['task']['id']

                if record_id not in record_map:
                    record_map[record_id] = TimeRecord(
                        name=record['task']['name'],
                        id=record['task']['id'],
                        time=record['time'])
                else:
                    record_map[record_id] = record_map[record_id]._replace(
                        time=record_map[record_id].time + record['time'])
        for k, task in record_map.items():
            task_time = _strfttime(task.time)
            row = (account, task.id, '\n'.join(textwrap.wrap(task.name,
                                                             50)), task_time)
            table.add(row)

    table = sorted(table, key=lambda i: i[0])
    total_time = _strfttime(total)
    table.append(('total', '', 'Total', total_time))
    print_formatted_text(
        tabulate.tabulate(
            table,
            ['account', 'id', 'name', 'time'],
            # floatfmt='.2f',
            tablefmt='grid'))
예제 #13
0
def render(output):
    dump = json.dumps(output, indent=4)
    tokens = list(json_lexer.get_tokens(dump))

    with pager(options="-FRSX") as less:
        if is_flat(output):
            table = tabulate(*tabularize(output), tablefmt="psql").encode("utf-8")
            less.write(table)
        else:
            print_formatted_text(PygmentsTokens(tokens), style=style, file=less)
예제 #14
0
    def _render_sdl(self, sdl: str) -> None:
        desc_doc = pt_document.Document(sdl)
        lexer = pt_lexers.PygmentsLexer(eql_pygments.EdgeQLLexer)
        formatter = lexer.lex_document(desc_doc)

        for line in range(desc_doc.line_count):
            pt_shortcuts.print_formatted_text(pt_formatted_text.FormattedText(
                formatter(line)),
                                              style=self.style)
        print()
예제 #15
0
    def _get_user_input(self):
        """
        Display appropriate label and collect user input.

        This private method displays the appropriate prompt label
        for the field using the appropriate display function
        and collect the user input.

        Returns
        -------
        user_input : list or str
            A string for fields that accepts a single input
            or a list of strings for fields that accept multiple
            inputs, e.g., subgroups.
        """
        # if we are dealing with a field that accepts multiple inputs
        if self.count == 'multiple':

            # instantiate a blank list to hold the multiple values
            values = []

            # show the name of the field as a heading but do not
            # ask for input yet
            print_formatted_text(HTML(f" <b>{self.label}</b>"))

            # ask the user how many of the multiple inputs they
            # intend to provide; this must be non-zero
            num_entries = prompt("  How many do you want to specify: ",
                                 validator=self._make_integer_validator())
            num_entries = int(num_entries)

            # display secondary prompts, one for each of the inputs
            # with the appropriate completer, validator, and style
            for i in range(num_entries):
                value = prompt(f"   Enter #{i+1}: ",
                               completer=self.completer,
                               validator=self.validator,
                               complete_style=self.complete_style)
                # save the value in the list
                values.append(value)

            # this is what we will return
            user_input = values

        # if we are dealing with a simple single-input field
        else:
            # nothing fancy, just display the label, attach
            # the appropriate completer, validator, and style,
            # and get the user input
            user_input = prompt(HTML(f" <b>{self.label}</b>: "),
                                completer=self.completer,
                                validator=self.validator,
                                complete_style=self.complete_style)

        return user_input
예제 #16
0
파일: repl.py 프로젝트: roee30/ptpython
 def print_formatted_text(self,
                          formatted_text: StyleAndTextTuples,
                          end: str = "\n") -> None:
     print_formatted_text(
         FormattedText(formatted_text),
         style=self._current_style,
         style_transformation=self.style_transformation,
         include_default_pygments_style=False,
         output=self.app.output,
         end=end,
     )
    def auto_rewrite_input(self, cmd):
        """Overridden from the parent class to use fancy rewriting prompt"""
        if not self.show_rewritten_input:
            return

        tokens = self.prompts.rewrite_prompt_tokens()
        if self.pt_app:
            print_formatted_text(PygmentsTokens(tokens), end='',
                                 style=self.pt_app.app.style)
            print(cmd)
        else:
            prompt = ''.join(s for t, s in tokens)
            print(prompt, cmd, sep='')
예제 #18
0
    def auto_rewrite_input(self, cmd):
        """Overridden from the parent class to use fancy rewriting prompt"""
        if not self.show_rewritten_input:
            return

        tokens = self.prompts.rewrite_prompt_tokens()
        if self.pt_app:
            print_formatted_text(PygmentsTokens(tokens), end='',
                                 style=self.pt_app.app.style)
            print(cmd)
        else:
            prompt = ''.join(s for t, s in tokens)
            print(prompt, cmd, sep='')
예제 #19
0
 def apply_validators(self):
     validators = self._question.get('validators', [])
     error_messages = []
     for validator in validators:
         try:
             validator.validate(self.get_value(), self._context)
         except ValidationError as ve:
             error_messages.append(ve.message)
             if self._mode == Mode.PROMPT:
                 print_formatted_text(
                     FormattedText([('class:prompt.error', ve.message)]),
                     style=get_theme_manager().get_current_style())
     return error_messages
예제 #20
0
    def _handle_exception(self, e: BaseException) -> None:
        output = self.app.output

        tokens = self._format_exception_output(e)

        print_formatted_text(
            tokens,
            style=self._current_style,
            style_transformation=self.style_transformation,
            include_default_pygments_style=False,
            output=output,
        )

        output.write("%s\n" % e)
        output.flush()
예제 #21
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")
예제 #22
0
 def write_console_ex(buf, otype):
     if otype == 0:
         if sys.stdout:
             sys.stdout.write(buf)
             sys.stdout.flush()
             TERMINAL_CURSOR_AT_BEGINNING[0] = buf.endswith("\n")
     else:
         if sys.stderr:
             buf = buf.replace("\r\n", "\n")
             sbuf = buf.split("\r")
             for i, b in enumerate(sbuf):
                 print_formatted_text(ANSI(stderr_format.format(b)), end="", file=sys.stderr)
                 if i < len(sbuf) - 1:
                     sys.stderr.write("\r")
             sys.stderr.flush()
             TERMINAL_CURSOR_AT_BEGINNING[0] = buf.endswith("\n")
예제 #23
0
파일: repl.py 프로젝트: mullikine/ptpython
    def _handle_exception(self, e):
        output = self.app.output

        # Instead of just calling ``traceback.format_exc``, we take the
        # traceback and skip the bottom calls of this framework.
        t, v, tb = sys.exc_info()

        # Required for pdb.post_mortem() to work.
        sys.last_type, sys.last_value, sys.last_traceback = t, v, tb

        tblist = traceback.extract_tb(tb)

        for line_nr, tb_tuple in enumerate(tblist):
            if tb_tuple[0] == '<stdin>':
                tblist = tblist[line_nr:]
                break

        l = traceback.format_list(tblist)
        if l:
            l.insert(0, "Traceback (most recent call last):\n")
        l.extend(traceback.format_exception_only(t, v))

        # For Python2: `format_list` and `format_exception_only` return
        # non-unicode strings. Ensure that everything is unicode.
        if six.PY2:
            l = [
                i.decode('utf-8') if isinstance(i, six.binary_type) else i
                for i in l
            ]

        tb = ''.join(l)

        # Format exception and write to output.
        # (We use the default style. Most other styles result
        # in unreadable colors for the traceback.)
        if self.enable_syntax_highlighting:
            tokens = list(_lex_python_traceback(tb))
        else:
            tokens = [(Token, tb)]

        print_formatted_text(PygmentsTokens(tokens),
                             style=self._current_style,
                             style_transformation=self.style_transformation,
                             include_default_pygments_style=False)

        output.write('%s\n' % e)
        output.flush()
예제 #24
0
 def show_tx(self, args):
     if len(args):
         try:
             txid = UInt256.ParseString(get_arg(args))
             tx, height = Blockchain.Default().GetTransaction(txid)
             if height > -1:
                 jsn = tx.ToJson()
                 jsn['height'] = height
                 jsn['unspents'] = [uns.ToJson(tx.outputs.index(uns)) for uns in
                                    Blockchain.Default().GetAllUnspent(txid)]
                 tokens = [("class:command", json.dumps(jsn, indent=4))]
                 print_formatted_text(FormattedText(tokens), style=self.token_style)
                 print('\n')
         except Exception as e:
             print("Could not find transaction from args: %s (%s)" % (e, args))
     else:
         print("Please specify a TX hash")
예제 #25
0
    def _handle_exception(self, e):
        output = self.app.output

        # Instead of just calling ``traceback.format_exc``, we take the
        # traceback and skip the bottom calls of this framework.
        t, v, tb = sys.exc_info()

        # Required for pdb.post_mortem() to work.
        sys.last_type, sys.last_value, sys.last_traceback = t, v, tb

        tblist = traceback.extract_tb(tb)

        for line_nr, tb_tuple in enumerate(tblist):
            if tb_tuple[0] == '<stdin>':
                tblist = tblist[line_nr:]
                break

        l = traceback.format_list(tblist)
        if l:
            l.insert(0, "Traceback (most recent call last):\n")
        l.extend(traceback.format_exception_only(t, v))

        # For Python2: `format_list` and `format_exception_only` return
        # non-unicode strings. Ensure that everything is unicode.
        if six.PY2:
            l = [i.decode('utf-8') if isinstance(i, six.binary_type) else i for i in l]

        tb = ''.join(l)

        # Format exception and write to output.
        # (We use the default style. Most other styles result
        # in unreadable colors for the traceback.)
        if self.enable_syntax_highlighting:
            tokens = list(_lex_python_traceback(tb))
        else:
            tokens = [(Token, tb)]

        print_formatted_text(
            PygmentsTokens(tokens), style=self._current_style,
            style_transformation=self.style_transformation,
            include_default_pygments_style=False)

        output.write('%s\n' % e)
        output.flush()
예제 #26
0
    def write_output_prompt(self):
        sys.stdout.write(self.shell.separate_out)
        # If we're not displaying a prompt, it effectively ends with a newline,
        # because the output will be left-aligned.
        self.prompt_end_newline = True

        if self.do_full_cache:
            tokens = self.shell.prompts.out_prompt_tokens()
            prompt_txt = ''.join(s for t, s in tokens)
            if prompt_txt and not prompt_txt.endswith('\n'):
                # Ask for a newline before multiline output
                self.prompt_end_newline = False

            if self.shell.pt_app:
                print_formatted_text(PygmentsTokens(tokens),
                    style=self.shell.pt_app.app.style, end='',
                )
            else:
                sys.stdout.write(prompt_txt)
예제 #27
0
    def write_output_prompt(self):
        sys.stdout.write(self.shell.separate_out)
        # If we're not displaying a prompt, it effectively ends with a newline,
        # because the output will be left-aligned.
        self.prompt_end_newline = True

        if self.do_full_cache:
            tokens = self.shell.prompts.out_prompt_tokens()
            prompt_txt = ''.join(s for t, s in tokens)
            if prompt_txt and not prompt_txt.endswith('\n'):
                # Ask for a newline before multiline output
                self.prompt_end_newline = False

            if self.shell.pt_app:
                print_formatted_text(PygmentsTokens(tokens),
                    style=self.shell.pt_app.app.style, end='',
                )
            else:
                sys.stdout.write(prompt_txt)
예제 #28
0
파일: repl.py 프로젝트: roee30/ptpython
    def _handle_exception(self, e: BaseException) -> None:
        output = self.app.output

        # Instead of just calling ``traceback.format_exc``, we take the
        # traceback and skip the bottom calls of this framework.
        t, v, tb = sys.exc_info()

        # Required for pdb.post_mortem() to work.
        sys.last_type, sys.last_value, sys.last_traceback = t, v, tb

        tblist = list(traceback.extract_tb(tb))

        for line_nr, tb_tuple in enumerate(tblist):
            if tb_tuple[0] == "<stdin>":
                tblist = tblist[line_nr:]
                break

        l = traceback.format_list(tblist)
        if l:
            l.insert(0, "Traceback (most recent call last):\n")
        l.extend(traceback.format_exception_only(t, v))

        tb_str = "".join(l)

        # Format exception and write to output.
        # (We use the default style. Most other styles result
        # in unreadable colors for the traceback.)
        if self.enable_syntax_highlighting:
            tokens = list(_lex_python_traceback(tb_str))
        else:
            tokens = [(Token, tb_str)]

        print_formatted_text(
            PygmentsTokens(tokens),
            style=self._current_style,
            style_transformation=self.style_transformation,
            include_default_pygments_style=False,
            output=output,
        )

        output.write("%s\n" % e)
        output.flush()
예제 #29
0
    def show_block(self, args):
        item = get_arg(args)
        txarg = get_arg(args, 1)
        if item is not None:
            block = Blockchain.Default().GetBlock(item)

            if block is not None:

                bjson = json.dumps(block.ToJson(), indent=4)
                tokens = [("class:number", bjson)]
                print_formatted_text(FormattedText(tokens), style=self.token_style)
                print('\n')
                if txarg and 'tx' in txarg:

                    for tx in block.FullTransactions:
                        print(json.dumps(tx.ToJson(), indent=4))

            else:
                print("Could not locate block %s" % item)
        else:
            print("please specify a block")
예제 #30
0
    def resolve_file_conversion(remote_file: GoogleDriveFile) -> str:
        """
        A function to take in a remote file and return to the caller a string that represents the file extension to use
        for this file. This exists to let users who may not know what conversion are available see all options that are
        available to them given a document type so they can download the file as the one best suited to their needs.

        Parameters:
            remote_file (GoogleDriveFile): The remote file who we are attempting to get the conversion for

        Returns:
            conversion_opts[user_input] (str): The file extension we are converting this file to
        """

        while 1:

            # Print the helpful prompt on what the user is choosing and cache the supported conversions list for this
            # file
            print_formatted_text(ANSI(f"\x1b[36mWhat file type would you like to convert \"{remote_file['title']}\" to?"))
            conversion_opts = [ext for ext, link in SUPPORTED_FILE_TYPES.items() if link in remote_file['exportLinks']]

            # Print out all of the possible conversion's for this document and their associated number
            for choice, conversion in enumerate(conversion_opts):
                print_formatted_text(f"[{choice + 1}]: {conversion}")

            try:
                # Prompt the user for their choice of the file types printed out above
                user_input = int(prompt(ANSI(f'\x1b[36mChoose [1-{len(conversion_opts)}]: '))) - 1

                # If the user input a valid index then return the conversion extension they desire
                if 0 <= user_input < len(conversion_opts):
                    return conversion_opts[user_input]

            # If the user input a non integer cast-able value then inform them to use the numbers
            except ValueError:
                print_formatted_text(ANSI('\x1b[31mPlease input the integer that corresponds to your desired file type'))
예제 #31
0
    def resolve_mnemonic_conflict(matching_filenames: List[GoogleDriveFile]) -> GoogleDriveFile:
        """
        A function to ask the user to resolve any mnemonic conflicts that can arise because of how Google Drive
        works. Since Google Drive has display names that are not unique and since we want to use traditional file
        pathing as much as possible it is possible that a filename may correspond to many different files. In that case
        we need to ask the user which one they meant to reference with their query

        Parameters:
            matching_filenames (List[GoogleDriveFile]): A list of all google drive files matched the query by the user

        Returns:
            file_ids[response] (GoogleDriveFile): The GoogleDriveFile whose ID was entered by the user when prompted
        """

        # Cache a dictionary linking all file ids to their corresponding file objects
        file_ids = {file['id']: file for file in matching_filenames}

        while 1:

            # Let the user know what is going wrong before anything else
            print_formatted_text(ANSI("\x1b[31mThere are multiple files with the same filename given!\n"))

            # Until the user provides the info we want keep printing the matching files
            for file in matching_filenames:
                pretty_date = file['modifiedDate'][:file['modifiedDate'].index('.')].replace('T', ' ')
                print_formatted_text(ANSI(f"\x1b[36mDisplay Name: \x1b[37m{file['title']} \x1b[36mLast Modified: "
                                          f"\x1b[37m{pretty_date} \x1b[36mFile ID: \x1b[37m{file['id']}"))

            # Newline for terminal readability and prompt the user to resolve the conflict
            print_formatted_text("")
            response = prompt(ANSI('\x1b[31mPlease copy/paste the ID of the file to which you were referring: '))

            # If the user's response is a valid key then return the associated file
            if response in file_ids.keys():
                return file_ids[response]
예제 #32
0
    def _execute(self, line):
        """
        Evaluate the line and print the result.
        """
        output = self.app.output

        # WORKAROUND: Due to a bug in Jedi, the current directory is removed
        # from sys.path. See: https://github.com/davidhalter/jedi/issues/1148
        if '' not in sys.path:
            sys.path.insert(0, '')

        def compile_with_flags(code, mode):
            " Compile code with the right compiler flags. "
            return compile(code, '<stdin>', mode,
                           flags=self.get_compiler_flags(),
                           dont_inherit=True)

        if line.lstrip().startswith('\x1a'):
            # When the input starts with Ctrl-Z, quit the REPL.
            self.app.exit()

        elif line.lstrip().startswith('!'):
            # Run as shell command
            os.system(line[1:])
        else:
            # Try eval first
            try:
                code = compile_with_flags(line, 'eval')
                result = eval(code, self.get_globals(), self.get_locals())

                locals = self.get_locals()
                locals['_'] = locals['_%i' % self.current_statement_index] = result

                if result is not None:
                    out_prompt = self.get_output_prompt()

                    try:
                        result_str = '%r\n' % (result, )
                    except UnicodeDecodeError:
                        # In Python 2: `__repr__` should return a bytestring,
                        # so to put it in a unicode context could raise an
                        # exception that the 'ascii' codec can't decode certain
                        # characters. Decode as utf-8 in that case.
                        result_str = '%s\n' % repr(result).decode('utf-8')

                    # Align every line to the first one.
                    line_sep = '\n' + ' ' * fragment_list_width(out_prompt)
                    result_str = line_sep.join(result_str.splitlines()) + '\n'

                    # Write output tokens.
                    if self.enable_syntax_highlighting:
                        formatted_output = merge_formatted_text([
                            out_prompt,
                            PygmentsTokens(list(_lex_python_result(result_str))),
                        ])
                    else:
                        formatted_output = FormattedText(
                                out_prompt + [('', result_str)])

                    print_formatted_text(
                        formatted_output, style=self._current_style,
                        style_transformation=self.style_transformation,
                        include_default_pygments_style=False)

            # If not a valid `eval` expression, run using `exec` instead.
            except SyntaxError:
                code = compile_with_flags(line, 'exec')
                six.exec_(code, self.get_globals(), self.get_locals())

            output.flush()
예제 #33
0
 def print_remote_prompt(self, ec=None):
     tokens = self.get_remote_prompt_tokens() + self.get_prompt_tokens(
         ec=ec)
     print_formatted_text(PygmentsTokens(tokens),
                          end="",
                          style=self.pt_cli.app.style)
예제 #34
0
 def print_out_prompt(self):
     tokens = self.get_out_prompt_tokens()
     print_formatted_text(PygmentsTokens(tokens), end='',
                          style = self.pt_cli.app.style)
예제 #35
0
def patched_execute(self, line):
    """
    Evaluate the line and print the result.
    """
    output = self.app.output

    # WORKAROUND: Due to a bug in Jedi, the current directory is removed
    # from sys.path. See: https://github.com/davidhalter/jedi/issues/1148
    if "" not in sys.path:
        sys.path.insert(0, "")

    def compile_with_flags(code, mode):
        " Compile code with the right compiler flags. "
        return compile(code, "<stdin>", mode, flags=self.get_compiler_flags(), dont_inherit=True)

    if line.lstrip().startswith("\x1a"):
        # When the input starts with Ctrl-Z, quit the REPL.
        self.app.exit()

    elif line.lstrip().startswith("!"):
        # Run as shell command
        os.system(line[1:])
    else:
        # Try eval first
        try:
            code = compile_with_flags(line, "eval")
            result = eval(code, self.get_globals(), self.get_locals())

            locals = self.get_locals()
            locals["_"] = locals["_%i" % self.current_statement_index] = result

            if result is not None:
                out_prompt = self.get_output_prompt()

                try:
                    result_str = "%r\n" % (result,)
                except UnicodeDecodeError:
                    # In Python 2: `__repr__` should return a bytestring,
                    # so to put it in a unicode context could raise an
                    # exception that the 'ascii' codec can't decode certain
                    # characters. Decode as utf-8 in that case.
                    result_str = "%s\n" % repr(result).decode("utf-8")

                # Align every line to the first one.
                line_sep = "\n" + " " * fragment_list_width(out_prompt)
                result_str = line_sep.join(result_str.splitlines()) + "\n"

                # Support ansi formatting (removed syntax higlighting)
                ansi_formatted = ANSI(result_str)._formatted_text
                formatted_output = merge_formatted_text([FormattedText(out_prompt) + ansi_formatted])

                print_formatted_text(
                    formatted_output,
                    style=self._current_style,
                    style_transformation=self.style_transformation,
                    include_default_pygments_style=False,
                )

        # If not a valid `eval` expression, run using `exec` instead.
        except SyntaxError:
            code = compile_with_flags(line, "exec")
            six.exec_(code, self.get_globals(), self.get_locals())

        output.flush()