Example #1
0
 def __setitem__(self, index, value):
     '''
     Set the history event at ``index``.
     '''
     if hasattr(readline, 'replace_history_item'):
         index = self.normalize_index(index)
         readline.replace_history_item(index, value)  # pylint: disable=no-member
Example #2
0
    def _t_add(self, cmd, line):
        """Code shared by t_add, bug_add and n_add."""
        parser = self._parser_t_add(cmd)
        args = parser.parse_args(line)

        line = " ".join(args.cmd)
        if not line:
            raise BadUsageException("Missing parameters")
        projectName, title, keywordDict = parseutils.parseLine(line)
        projectName = self._realProjectName(projectName)
        if not title:
            raise BadUsageException("Missing title")

        if args.crypt:
            # Obfuscate line in history
            length = readline.get_current_history_length()
            if length > 0:  # Ensure history is positive to avoid crash with bad readline setup
                readline.replace_history_item(
                    length - 1,
                    "%s %s " % (cmd, line.replace(title, "<...encrypted...>")))
            # Encrypt title
            title = self.cryptoMgr.encrypt(title)

        task = dbutils.addTask(projectName, title, keywordDict)
        if not task:
            tui.reinjectInRawInput(u"%s %s" % (cmd, line))
            return None
        self.lastTaskId = task.id

        if args.describe:
            self.do_t_describe(self.lastTaskId)

        return task
Example #3
0
    def _t_add(self, cmd, line):
        """Code shared by t_add, bug_add and n_add."""
        parser = self._parser_t_add(cmd)
        args = parser.parse_args(line)

        line = " ".join(args.cmd)
        if not line:
            raise BadUsageException("Missing parameters")
        projectName, title, keywordDict = parseutils.parseLine(line)
        projectName = self._realProjectName(projectName)
        if not title:
            raise BadUsageException("Missing title")

        if args.crypt:
            # Obfuscate line in history
            length = readline.get_current_history_length()
            if length > 0:  # Ensure history is positive to avoid crash with bad readline setup
                readline.replace_history_item(length - 1, "%s %s " % (cmd,
                                                                  line.replace(title, "<...encrypted...>")))
            # Encrypt title
            title = self.cryptoMgr.encrypt(title)

        task = dbutils.addTask(projectName, title, keywordDict)
        if not task:
            tui.reinjectInRawInput("%s %s" % (cmd, line))
            return None
        self.lastTaskId = task.id

        if args.describe:
            self.do_t_describe(self.lastTaskId)
        return task
Example #4
0
 def __setitem__(self, index, value):
     '''
     Set the history event at ``index``.
     '''
     if hasattr(readline, 'replace_history_item'):
         index = self.normalize_index(index)
         readline.replace_history_item(index, value)  # pylint: disable=no-member
Example #5
0
 def rewrite_history(history):
     for index in range(readline.get_current_history_length()):
         text = readline.get_history_item(index + 1)
         if '\n' in text:
             readline.replace_history_item(
                 index, text.replace('\n', '\\r\\n'))
     readline.write_history_file(history)
Example #6
0
    def onecmd(self, line: str) -> bool:
        """Override the default Cmd.onecmd()."""
        if isinstance(line, list):
            # List of str is pushed back onto cmdqueue in self.split()
            args = line
        else:  # line is a string
            if self.multi_cmd_mode:  # Discard leading '%' in multi-cmd mode
                if line and line.startswith('%') and not line.startswith('%%'):
                    line = line[1:]
                    readline.replace_history_item(1, line)
            readline.write_history_file(self.history_file)

            # A command line read from the input
            cmd, arg, line = self.parseline(line)
            if not line:
                return self.emptyline()
            if not cmd:
                return self.default(line)

            # Split the command line into a list of args
            args = list(self.split(line))

        args = self.process_args(args)  # Expand aliases, macros and globs
        cmd, *args = args or ['']
        self.lastcmd = ''
        func = getattr(self, 'do_' + cmd, None)
        if func:
            ret: bool = func(args)
        else:
            ret = self.default(' '.join([cmd, *args]))
        return ret
Example #7
0
 def push(self, line):
     try:
         cls_, method = line[:line.index("(")].split(".")
         method = getattr(self.locals[cls_], method)
         if hasattr(method, "_private"):
             readline.replace_history_item(
                 readline.get_current_history_length() - 1,
                 line[:line.index("(")] + "()")
     except (ValueError, AttributeError, KeyError):
         pass
     return super().push(line)
Example #8
0
def compact_history():
    if hasattr(readline, "replace_history_item"):
        unique_history = utils.unique_list()
        for index in reversed(list(range(1, readline.get_current_history_length()))):
            hist_item = readline.get_history_item(index)
            if hist_item:  # some history items are None (usually at index 0)
                unique_history.append(readline.get_history_item(index))
        unique_history.reverse()
        for index in range(len(unique_history)):
            readline.replace_history_item(index + 1, unique_history[index])
        for index in reversed(list(range(len(unique_history) + 1, readline.get_current_history_length()))):
            readline.remove_history_item(index)
def compact_history():
    if hasattr(readline, "replace_history_item"):
        unique_history = utils.unique_list()
        for index in reversed(list(range(1, readline.get_current_history_length()))):
            hist_item = readline.get_history_item(index)
            if hist_item:  # some history items are None (usually at index 0)
                unique_history.append(readline.get_history_item(index))
        unique_history.reverse()
        for index in range(len(unique_history)):
            readline.replace_history_item(index + 1, unique_history[index])
        for index in reversed(list(range(len(unique_history) + 1, readline.get_current_history_length()))):
            readline.remove_history_item(index)
Example #10
0
    def execute(self, index):

        command = readline.get_history_item(index)
        if command is not None:
            print "executing command: '%s'" % command

            exec(command, self.globals)

            # add the  executed command in the history by replacing maestro.history.execute()
            pos = readline.get_current_history_length() - 1
            readline.replace_history_item(pos, command)
        else:
            print "history: Index '%i' is out of range" % index
    def test_do_history(self):
        self.exeCmd("history")
        self.assertFalse(self.capturedStdout.gotPsyqlException())

        if READLINE:
            # This will match the "help" command position
            position = int(readline.get_current_history_length())
            readline.replace_history_item(position - 1, "help")
            self.exeCmd("history")
            self.assertFalse(self.capturedStdout.gotPsyqlException())

        for cmd in ("history a", "history -1", "history 10.5", "history 10,5", "history 2 4"):
            self.exeCmd(cmd)
            self.assertTrue(self.capturedStdout.gotPsyqlException())
Example #12
0
    def test_do_history(self):
        self.exeCmd("history")
        self.assertFalse(self.capturedStdout.gotPsyqlException())

        if READLINE:
            # This will match the "help" command position
            position = int(readline.get_current_history_length())
            readline.replace_history_item(position - 1, "help")
            self.exeCmd("history")
            self.assertFalse(self.capturedStdout.gotPsyqlException())

        for cmd in ("history a", "history -1", "history 10.5", "history 10,5",
                    "history 2 4"):
            self.exeCmd(cmd)
            self.assertTrue(self.capturedStdout.gotPsyqlException())
Example #13
0
 def _input(self, prompt):
     response = input(prompt)
     try:
         cls_, method = response[:response.index("(")].split(".")
         cls_ = getattr(self, cls_)
         method = getattr(cls_, method)
         if hasattr(method, "_private"):
             readline.replace_history_item(
                 readline.get_current_history_length() - 1,
                 response[:response.index("(")] + "()"
             )
     except (ValueError, AttributeError):
         pass
     readline.append_history_file(1, "build/.history")
     return response
Example #14
0
 def exec_hist(self, *args):
     """
     Execute a command from the history. If the user typed '!!' then
     repeat the last command, if '!int' find that command in the list and
     execute it.
     TODO: implement '!prefix'
     """
     length = readline.get_current_history_length()
     if(args[0] == "last" and length > 2):
         val = length - 2  # last cmd
     else:
         val = int(args[0].value)
     cmd = readline.get_history_item(val)
     if cmd:
         length = readline.get_current_history_length() - 1
         readline.replace_history_item(length, cmd)
         return self.run(cmd)
     else:
         raise SyntaxError("Unknown history command %s" % val)
    def test_nonascii_history(self):
        import os, readline
        TESTFN = "{}_{}_tmp".format("@test", os.getpid())

        is_editline = readline.__doc__ and "libedit" in readline.__doc__

        readline.clear_history()
        try:
            readline.add_history("entrée 1")
        except UnicodeEncodeError as err:
            skip("Locale cannot encode test data: " + format(err))
        readline.add_history("entrée 2")
        readline.replace_history_item(1, "entrée 22")
        readline.write_history_file(TESTFN)
        readline.clear_history()
        readline.read_history_file(TESTFN)
        if is_editline:
            # An add_history() call seems to be required for get_history_
            # item() to register items from the file
            readline.add_history("dummy")
        assert readline.get_history_item(1) == "entrée 1"
        assert readline.get_history_item(2) == "entrée 22"
Example #16
0
    def testHistoryUpdates(self):
        readline.clear_history()

        readline.add_history("first line")
        readline.add_history("second line")

        self.assertEqual(readline.get_history_item(0), None)
        self.assertEqual(readline.get_history_item(1), "first line")
        self.assertEqual(readline.get_history_item(2), "second line")

        readline.replace_history_item(0, "replaced line")
        self.assertEqual(readline.get_history_item(0), None)
        self.assertEqual(readline.get_history_item(1), "replaced line")
        self.assertEqual(readline.get_history_item(2), "second line")

        self.assertEqual(readline.get_current_history_length(), 2)

        readline.remove_history_item(0)
        self.assertEqual(readline.get_history_item(0), None)
        self.assertEqual(readline.get_history_item(1), "second line")

        self.assertEqual(readline.get_current_history_length(), 1)
Example #17
0
    def execute(self, cmdline):

        # Check for history recall
        if cmdline == "!!" and self.history:
            cmdline = self.history[-1]
            print cmdline
            if readline.get_current_history_length():
                readline.replace_history_item(
                    readline.get_current_history_length() - 1, cmdline)
        elif cmdline.startswith("!"):
            try:
                index = int(cmdline[1:])
                if index > 0 and index <= len(self.history):
                    cmdline = self.history[index - 1]
                    print cmdline
                    if readline.get_current_history_length():
                        readline.replace_history_item(
                            readline.get_current_history_length() - 1, cmdline)
                else:
                    raise ValueError()
            except ValueError:
                print "%s: event not found" % (cmdline, )
                return

        # split the command line into command and options
        splits = cmdline.split(" ", 1)
        cmd = splits[0]
        options = splits[1] if len(splits) == 2 else ""

        # Find matching command
        try:
            if cmd not in self.commands:
                self.history.append(cmdline)
                raise UnknownCommand(cmd)
            else:
                self.commands[cmd].execute(cmd, options)
        finally:
            # Store in history
            self.history.append(cmdline)
Example #18
0
    def testHistoryUpdates(self):
        readline.clear_history()

        readline.add_history("first line")
        readline.add_history("second line")

        self.assertEqual(readline.get_history_item(0), None)
        self.assertEqual(readline.get_history_item(1), "first line")
        self.assertEqual(readline.get_history_item(2), "second line")

        readline.replace_history_item(0, "replaced line")
        self.assertEqual(readline.get_history_item(0), None)
        self.assertEqual(readline.get_history_item(1), "replaced line")
        self.assertEqual(readline.get_history_item(2), "second line")

        self.assertEqual(readline.get_current_history_length(), 2)

        readline.remove_history_item(0)
        self.assertEqual(readline.get_history_item(0), None)
        self.assertEqual(readline.get_history_item(1), "second line")

        self.assertEqual(readline.get_current_history_length(), 1)
 def _getline(self, name):
     c = self.rls[name]
     if c['preprompt']: print(c['preprompt'])
     line = self.input(name)
     line = line.strip()
     # handle substitution
     rlline = line.replace(' ', c['sub'])
     line = rlline.replace(c['sub'], ' ')
     # handle constraints
     if c['constrain']:
         if rlline not in c['options']:
             print("\nSorry, {} is not an allowed option. Please enter a new value.\n".format(line))
             raise BadInputError
     if not c['nullok'] and line == '':
         print("\nSorry, blank lines are not allowed. Please enter a new value.\n".format(line))
         raise BadInputError
     # and history munging
     if readline.get_current_history_length() > 0:
         readline.replace_history_item(readline.get_current_history_length() - 1, rlline)
     if rlline not in self.options and rlline != '':
         self.options.append(rlline)
         self.options = sorted(self.options)
     return line
Example #20
0
    def execute(self, cmdline):

        # Check for history recall
        if cmdline == "!!" and self.history:
            cmdline = self.history[-1]
            print cmdline
            if readline.get_current_history_length():
                readline.replace_history_item(readline.get_current_history_length() - 1, cmdline)
        elif cmdline.startswith("!"):
            try:
                index = int(cmdline[1:])
                if index > 0 and index <= len(self.history):
                    cmdline = self.history[index - 1]
                    print cmdline
                    if readline.get_current_history_length():
                        readline.replace_history_item(readline.get_current_history_length() - 1, cmdline)
                else:
                    raise ValueError()
            except ValueError:
                print "%s: event not found" % (cmdline,)
                return

        # split the command line into command and options
        splits = cmdline.split(" ", 1)
        cmd = splits[0]
        options = splits[1] if len(splits) == 2 else ""

        # Find matching command
        try:
            if cmd not in self.commands:
                self.history.append(cmdline)
                raise UnknownCommand(cmd)
            else:
                self.commands[cmd].execute(cmd, options)
        finally:
            # Store in history
            self.history.append(cmdline)
Example #21
0
def readline_inject(args):
    # Inject into readline to use the injected command.
    history_len = readline.get_current_history_length()
    last_item = readline.get_history_item(history_len)
    cmd = ' '.join([last_item.split()[0]] + args)
    readline.replace_history_item(history_len - 1, cmd)
Example #22
0
    def run_cmd(self, cmd_line, show_results=False):
        cmd_line = str(cmd_line)
        cmd_line = cmd_line.strip()
        if cmd_line == '':
            return
        args = shlex.split(cmd_line)
        if args[0] == 'store':
            save_to_buffer = 'CB'
            args.pop(0)
        elif args[0] == 'storeto':
            args.pop(0)
            save_to_buffer = args.pop(0)
        else:
            save_to_buffer = False
        cmd = full_cmd(args.pop(0))
        params = args
        if cmd == 'quit':
            self.p("Finished")
            exit()
        elif cmd == 'info':
            self.printStuff()
        elif cmd == 'cmds':
            c = valid_cmds.keys()
            c.sort()
            c2 = []
            for c3 in c:
                if reverse_abbrevs.has_key(c3):
                    c2.append("%s(%s)" % (c3, reverse_abbrevs[c3]))
                else:
                    c2.append(c3)
            for i in range(0, len(c), 6):
                c4 = '  '.join(c2[i:i + 6])
                self.p(c4, True)
        elif cmd == 'set':
            if len(args) != 2:
                self.p("Incorrect args. Need 2, name and value")
            else:
                name = args[0]
                val = args[1]
                if val[0] == '#':
                    val2 = val[1:]
                    try:
                        val = self.buffer_val(val2)
                    except Exception:
                        self.p("Invalid reference ({})".format(val))
                        return
                else:
                    try:
                        val = int(val)
                    except ValueError:
                        pass
                self.buffers[name] = val
        elif cmd == 'showcurl':
            self.print_api_cmd = not self.print_api_cmd
            self.p("SHOW CURL: " + str(self.print_api_cmd), True)
        elif cmd == 'buffers':
            self.p(self.buffers)
        elif cmd == 'info':
            self.printStuff()
        elif cmd[0] == '#':
            name = cmd[1:]
            if len(params) == 0:
                try:
                    val = self.buffer_val(cmd[1:])
                    pval = pprint.pformat(val, width=40) + "\n"
                    self.p("{} = {}".format(cmd, pval))
                except Exception:
                    self.p("{} not found".format(cmd))
            else:
                try:
                    newval = self.buffer_val(params[0][1:])
                    self.buffers[name] = newval
                    self.p("{} = {}".format(name, newval))
                except Exception:
                    self.p("Invalid value")

        elif cmd == 'history':
            if len(args) > 0:
                try:
                    show_num = int(args[0])
                except ValueError:
                    self.p("Invalid history length (must be integer)")
                    return
            else:
                show_num = 20
            h_len = readline.get_current_history_length()
            if h_len < show_num:
                show_num = h_len
            print "XX {} {}".format(show_num, h_len)
            for n in range(h_len - show_num, h_len):
                self.p("{}: {}".format(n + 1,
                                       readline.get_history_item(n + 1)))
        elif cmd == 'sh':
            if len(params) == 0:
                self.p("sh <search arg>")
                return
            search_arg = params[0]
            cnt = 0
            found = []
            h_len = readline.get_current_history_length()
            self.p("History search for {}".format(search_arg))
            for n in range(1, h_len):
                c = readline.get_history_item(n)
                if re.search(search_arg, c):
                    self.p("{}: {}".format(n, c))

        elif cmd[0] == '!':
            h_num = cmd[1:]
            self.p("HN {}".format(h_num))
            h_num = int(h_num)
            h_len = readline.get_current_history_length()
            if h_num >= h_len:
                self.p("{} {}".format(h_num, h_len))
                raise ValueError
            cmd_line = readline.get_history_item(h_num)
            readline.replace_history_item(h_len - 1, cmd_line)
            self.p("History Cmd: {}".format(cmd_line))
            self.run_cmd(cmd_line, True)

        else:
            if not valid_cmds.has_key(cmd):
                self.p("Invalid command (%s)\n" % cmd, True)
                return
            if len(params) == 0:
                key = None
            else:
                # if first param is a digit, and command takes an account, then the digit is the account number
                md = re.match('^(\d+)$', params[0])
                if md:
                    cmd_params = valid_cmds[cmd]
                    if re.search('account', cmd_params[0]):
                        params[0] = "ACC%s" % md.group(1)

                for i in range(len(params)):
                    if params[i] == '_':
                        params[i] = ''
                    elif params[i] == 'None':
                        params[i] = ''
                    elif params[i][0] == '#':
                        try:
                            params[i] = self.buffer_val(params[i][1:])
                        except Exception:
                            self.p("Invalid reference ({})".format(params[i]))
                    elif re.match('[\d.]+i$', params[i]):
                        try:
                            params[i] = int(params[i][:-1])
                        except ValueError:
                            self.p("Invalid integer value ({})".format(
                                params[i]))
                            return
                    elif re.match('[\d.]+f$', params[i]):
                        try:
                            params[i] = float(params[i][:-1])
                        except ValueError:
                            self.p("Invalid float value ({})".format(
                                params[i]))
                            return
                    else:
                        m = re.match('^ACC(\d+)$', params[i])
                        if m:
                            acc_num = int(m.group(1))
                            if acc_num > len(self.account_names):
                                self.p('Invalid account\n', True)
                                return
                            account_name = self.account_names[acc_num - 1]
                            params[i] = account_name
                            self.p("Account Name: {}".format(account_name))
                key = params[0]
            if cmd == 'signrawtransaction':
                hash = params[0]
                decoded = self.api_cmd("decoderawtransaction", [hash])
                self.p(decoded)
                txid = decoded['vin'][0]['txid']
                spk = decoded['vout'][0]['scriptPubKey']['hex']
                sign = [{'txid': txid, 'vout': 0, 'scriptPubKey': spk}]
                self.p(sign)
                params.append(sign)
            elif cmd == 'createrawtransaction':
                # orig_trans, to_addr, amount, change_addr
                if len(params) != 4:
                    self.p(
                        "createrawtransaction orig_trans to_addr amount change_addr"
                    )
                    return
                trans_info = self.api_cmd("gettransaction", [params[0]])
                orig_trans_amount = trans_info['amount']

                xfer_amount = float(params[2])
                fee = 0.0005
                # prevent floating point rounding error
                change = float(orig_trans_amount) - xfer_amount - fee
                change = round(change * 1e8) * 1e-8
                if change < 0:
                    self.p("Invalid amount")
                    return
                x3 = [{'txid': params[0], 'vout': 0}]
                xfer_to_addr = params[1]
                change_addr = params[3]
                trans_out = {xfer_to_addr: xfer_amount}
                if change > 0:
                    trans_out[change_addr] = change
                params = [x3, trans_out]
            elif cmd == 'listunspent' and len(params) == 3:
                params[2] = [params[2]]
            param = ' '.join(['"%s"' % x for x in params])
            try:
                cmd_result = self.api_cmd(cmd, params)
                self.buffers['LAST'] = cmd_result
                if show_results:
                    if cmd == 'getrawmempool':
                        self.p("NUM Trans: %d" % (len(cmd_result)), True)
                        return
                    elif cmd == 'help':
                        tmp = re.sub('\\\\n', "\n", cmd_result)
                        self.p(tmp, True)
                    else:
                        if cmd == 'listaddressgroupings':
                            split_lists = False
                        else:
                            split_lists = True
                        self.p(cmd_result, split_lists=split_lists)
                        if type(cmd_result) is list:
                            self.p("LIST SIZE: %d\n" % len(cmd_result), True)
                        elif type(cmd_result) is dict:
                            self.p("DICT SIZE: %d\n" % len(cmd_result), True)
                else:
                    try:
                        self.cmd_results[cmd][key] = cmd_result
                    except KeyError:
                        self.cmd_results[cmd] = {key: cmd_result}
                if save_to_buffer:
                    self.buffers[save_to_buffer] = cmd_result
                    self.p("Result was stored to #{}".format(save_to_buffer))
            except CmdError as e:
                self.p("ERROR: %s" % (e.error_value), True)
                self.p(
                    "ERROR: cmd='%s'\n param='%s'\n curl_cmd='%s'\n" %
                    (e.cmd, e.param, e.curl_cmd), True)
                pass
Example #23
0
    def main(self, sending):

        # Say hello!
        run.write(
            '%s%s>%s\n%s%s%s<%s\n'
            % (RULER, '-' * 70, NORMAL,
               documentation(
                   "Use Enter to start preparing a new AMI message."
                   " When prompted for a key value, use Enter without a"
                   " value to ignore that key" " (yet Action: may not be"
                   " ignored)."
                   " Once all fields have been prompted for, the ready"
                   " AMI message is echoed, and you get a last chance to"
                   " replace or add keys by typing lines in full."
                   " You then send the message by issuing Enter on an"
                   " empty line.\n"
                   '\n'
                   "When prompted for a value, use TAB once for completing"
                   " as much as possible and twice to see available choices."
                   " Typed values are often added to available completions."
                   " Also use arrows or C-p / C-n to navigate, and C-r to"
                   " search."),
                   RULER, '-' * 70, NORMAL))

        # Get back the history, and restore multi-lines.
        readline.parse_and_bind('tab: complete')
        history = os.path.expanduser('~/.pasty-history')
        if os.path.exists(history):
            readline.read_history_file(history)
        for index in range(0, readline.get_current_history_length()):
            text = readline.get_history_item(index + 1)
            if '\\r\\n' in text:
                readline.replace_history_item(
                    index, text.replace('\\r\\n', '\n'))

        # Make sure history is saved, while protecting multi-lines.

        def rewrite_history(history):
            for index in range(readline.get_current_history_length()):
                text = readline.get_history_item(index + 1)
                if '\n' in text:
                    readline.replace_history_item(
                        index, text.replace('\n', '\\r\\n'))
            readline.write_history_file(history)

        import atexit
        atexit.register(rewrite_history, history)

        try:
            while True:
                # Wait until the user is ready and types Enter.
                history_mark = readline.get_current_history_length()
                text = raw_input()
                if text:
                    # We assume that a previous action has been recalled.
                    run.write('\n')
                    sending.write(text.replace('\n', '\r\n') + '\r\n\r\n')
                    continue

                # Prompt for the action.
                ami_message = ami.AMI_Message()
                text = manager_keys['Action'].read(ami_message)
                text2 = ami.canonical_action.get(text.lower())

                # If action is known, prompt with all AMI message keys.
                if text2 is not None:
                    action = manager_actions.get(text2)
                    text = ('%s%s>%s\n%s'
                            % (RULER, '-' * 70, NORMAL,
                               documentation(action.summary)))
                    if action.description:
                        text += '\n' + documentation(action.description)
                    run.write(text)
                    for pair in action.keys:
                        if isinstance(pair, tuple):
                            key, docum = pair
                            run.write('\n' + documentation(docum))
                        else:
                            key = pair
                        key.read(ami_message)
                    run.write('%s%s<%s\n%s\n'
                              % (RULER, '-' * 70, NORMAL,
                                 ami_message.encode().rstrip()))

                # Give the user a last opportunity to edit the message.
                while True:
                    line = raw_input().strip()
                    if not line:
                        break
                    if ':' in line:
                        key, value = line.split(':', 1)
                        ami_message[key] = value
                    else:
                        run.moan("Missing colon in line.")

                # Send the AMI message.  Reply will display asynchronously.
                text = ami_message.encode()
                sending.write(text)

                # Only retain the full AMI message in the history.
                mark = readline.get_current_history_length()
                while mark > history_mark:
                    mark -= 1
                    readline.remove_history_item(mark)
                readline.add_history(text.replace('\r', '').rstrip())

        # Terminate the program.
        except KeyboardInterrupt:
            run.write('\n')
Example #24
0
File: iface.py Project: wlaub/pybld
 def replaceHistory(self, string):
     i = readline.get_current_history_length()
     readline.replace_history_item(i-1, string)
Example #25
0
	def run_cmd(self, cmd_line, show_results=False):
		cmd_line = str(cmd_line)
		cmd_line = cmd_line.strip()
		if cmd_line == '':
			return
		args = shlex.split(cmd_line)
		if args[0] == 'store':
			save_to_buffer = 'CB'
			args.pop(0)
		elif args[0] == 'storeto':
			args.pop(0)
			save_to_buffer = args.pop(0)
		else:
			save_to_buffer = False
		cmd = full_cmd(args.pop(0))
		params = args
		if cmd == 'quit':
			self.p("Finished")
			exit()
		elif cmd == 'info':
			self.printStuff()
		elif cmd == 'cmds':
			c = valid_cmds.keys()
			c.sort()
			c2 = []
			for c3 in c:
				if reverse_abbrevs.has_key(c3):
					c2.append("%s(%s)" % (c3, reverse_abbrevs[c3]))
				else:
					c2.append(c3)
			for i in range(0, len(c), 6):
				c4 = '  '.join(c2[i:i+6])
				self.p(c4, True)
		elif cmd == 'set':
			if len(args) != 2:
				self.p("Incorrect args. Need 2, name and value")
			else:
				name = args[0]
				val = args[1]
				if val[0] == '#':
					val2 = val[1:]
					try:
						val = self.buffer_val(val2)
					except Exception:
						self.p("Invalid reference ({})".format(val))
						return
				else:
					try:
						val = int(val)
					except ValueError:
						pass
				self.buffers[name] = val
		elif cmd == 'showcurl':
			self.print_api_cmd = not self.print_api_cmd
			self.p("SHOW CURL: " + str(self.print_api_cmd), True)
		elif cmd == 'buffers':
			self.p(self.buffers)
		elif cmd == 'info':
			self.printStuff()
		elif cmd[0] == '#':
			name = cmd[1:]
			if len(params) == 0:
				try:
					val = self.buffer_val(cmd[1:])
					pval = pprint.pformat(val, width=40) + "\n"
					self.p("{} = {}".format(cmd, pval))
				except Exception:
					self.p("{} not found".format(cmd))
			else:
				try:
					newval = self.buffer_val(params[0][1:])
					self.buffers[name] = newval
					self.p("{} = {}".format(name, newval))
				except Exception:
					self.p("Invalid value")

		elif cmd == 'history':
			if len(args) > 0:
				try:
					show_num = int(args[0])
				except ValueError:
					self.p("Invalid history length (must be integer)")
					return
			else:
				show_num = 20
			h_len = readline.get_current_history_length()
			if h_len < show_num:
				show_num = h_len
			print "XX {} {}".format(show_num, h_len)
			for n in range(h_len - show_num, h_len):
				self.p("{}: {}".format(n + 1, readline.get_history_item(n + 1)))
		elif cmd == 'sh':
			if len(params) == 0:
				self.p("sh <search arg>")
				return
			search_arg = params[0]
			cnt = 0
			found = []
			h_len = readline.get_current_history_length()
			self.p("History search for {}".format(search_arg))
			for n in range(1, h_len):
				c = readline.get_history_item(n)
				if re.search(search_arg, c):
					self.p("{}: {}".format(n, c))

		elif cmd[0] == '!':
			h_num = cmd[1:]
			self.p("HN {}".format(h_num))
			h_num = int(h_num)
			h_len = readline.get_current_history_length()
			if h_num >= h_len:
				self.p("{} {}".format(h_num, h_len))
				raise ValueError
			cmd_line = readline.get_history_item(h_num)
			readline.replace_history_item(h_len - 1, cmd_line)
			self.p("History Cmd: {}".format(cmd_line))
			self.run_cmd(cmd_line, True)

		else:
			if not valid_cmds.has_key(cmd):
				self.p("Invalid command (%s)\n" % cmd, True)
				return
			if len(params) == 0:
				key = None
			else:
				# if first param is a digit, and command takes an account, then the digit is the account number
				md = re.match('^(\d+)$', params[0])
				if md:
					cmd_params = valid_cmds[cmd]
					if re.search('account', cmd_params[0]):
						params[0] = "ACC%s" % md.group(1)

				for i in range(len(params)):
					if params[i] == '_':
						params[i] = ''
					elif params[i] == 'None':
						params[i] = ''
					elif params[i][0] == '#':
						try:
							params[i] = self.buffer_val(params[i][1:])
						except Exception:
							self.p("Invalid reference ({})".format(params[i]))
					elif re.match('[\d.]+i$', params[i]):
						try:
							params[i] = int(params[i][:-1])
						except ValueError:
							self.p("Invalid integer value ({})".format(params[i]))
							return
					elif re.match('[\d.]+f$', params[i]):
						try:
							params[i] = float(params[i][:-1])
						except ValueError:
							self.p("Invalid float value ({})".format(params[i]))
							return
					else:
						m = re.match('^ACC(\d+)$', params[i])
						if m:
							acc_num = int(m.group(1))
							if acc_num > len(self.account_names):
								self.p('Invalid account\n', True)
								return
							account_name = self.account_names[acc_num - 1]
							params[i] = account_name
							self.p("Account Name: {}".format(account_name))
				key = params[0]
			if cmd == 'signrawtransaction':
				hash = params[0]
				decoded = self.api_cmd("decoderawtransaction", [hash])
				self.p(decoded)
				txid = decoded['vin'][0]['txid']
				spk = decoded['vout'][0]['scriptPubKey']['hex']
				sign = [{ 'txid': txid, 'vout': 0, 'scriptPubKey': spk }]
				self.p(sign)
				params.append(sign)
			elif cmd == 'createrawtransaction':
# orig_trans, to_addr, amount, change_addr
				if len(params) != 4:
					self.p("createrawtransaction orig_trans to_addr amount change_addr")
					return
				trans_info = self.api_cmd("gettransaction", [params[0]])
				orig_trans_amount = trans_info['amount']

				xfer_amount = float(params[2])
				fee = 0.0005
				# prevent floating point rounding error
				change = float(orig_trans_amount) - xfer_amount - fee
				change = round(change * 1e8) * 1e-8
				if change < 0:
					self.p("Invalid amount")
					return
				x3 = [{'txid': params[0], 'vout': 0}]
				xfer_to_addr = params[1]
				change_addr = params[3]
				trans_out = {xfer_to_addr: xfer_amount}
				if change > 0:
					trans_out[change_addr] = change
				params = [x3, trans_out]
			elif cmd == 'listunspent' and len(params) == 3:
				params[2] = [params[2]]
			param = ' '.join(['"%s"' % x for x in params])
			try:
				cmd_result = self.api_cmd(cmd, params)
				self.buffers['LAST'] = cmd_result
				if show_results:
					if cmd == 'getrawmempool':
						self.p("NUM Trans: %d" % (len(cmd_result)), True)
						return
					elif cmd == 'help':
						tmp = re.sub('\\\\n', "\n", cmd_result)
						self.p(tmp, True)
					else:
						if cmd == 'listaddressgroupings':
							split_lists = False
						else:
							split_lists = True
						self.p(cmd_result, split_lists=split_lists)
						if type(cmd_result) is list:
							self.p("LIST SIZE: %d\n" % len(cmd_result), True)
						elif type(cmd_result) is dict:
							self.p("DICT SIZE: %d\n" % len(cmd_result), True)
				else:
					try:
						self.cmd_results[cmd][key] = cmd_result
					except KeyError:
						self.cmd_results[cmd] = {key: cmd_result}
				if save_to_buffer:
					self.buffers[save_to_buffer] = cmd_result
					self.p("Result was stored to #{}".format(save_to_buffer))
			except CmdError as e:
				self.p("ERROR: %s" % (e.error_value), True)
				self.p("ERROR: cmd='%s'\n param='%s'\n curl_cmd='%s'\n" % (e.cmd, e.param, e.curl_cmd), True)
				pass
Example #26
0
File: history.py Project: cfm/pypsi
 def __setitem__(self, index, value):
     """
     Set the history event at ``index``.
     """
     index = self.normalize_index(index)
     readline.replace_history_item(index, value)
Example #27
0
 def __setitem__(self, index, value):
     '''
     Set the history event at ``index``.
     '''
     index = self.normalize_index(index)
     readline.replace_history_item(index, value)