Exemplo n.º 1
0
 def _path_completer(self):
     if self._path_completer_cache is None:
         self._path_completer_cache = GrammarCompleter(
             self._path_completer_grammar,
             {'var1': PathCompleter(expanduser=True),
              'var2': PathCompleter(expanduser=True),})
     return self._path_completer_cache
Exemplo n.º 2
0
 def __init__(self):
     namespace = q(r'\d')
     res = q('.Q.res')
     dot_q = q('1_key .q')
     self.path_completer = PathCompleter()
     self.words_info = [(list(res), 'k'), (list(dot_q), 'q'),
                        (list(q.key(namespace)), str(namespace))]
Exemplo n.º 3
0
def create_completer(get_globals, get_locals, magics_manager, alias_manager):
    g = create_ipython_grammar()

    return GrammarCompleter(
        g, {
            'python':
            PythonCompleter(get_globals, get_locals),
            'magic':
            MagicsCompleter(magics_manager),
            'alias_name':
            AliasCompleter(alias_manager),
            'pdb_arg':
            WordCompleter(['on', 'off'], ignore_case=True),
            'autocall_arg':
            WordCompleter(['0', '1', '2'], ignore_case=True),
            'py_filename':
            PathCompleter(only_directories=False,
                          file_filter=lambda name: name.endswith('.py')),
            'filename':
            PathCompleter(only_directories=False),
            'directory':
            PathCompleter(only_directories=True),
            'system':
            SystemCompleter(),
        })
Exemplo n.º 4
0
    def _create_path_completer(self):
        def unwrapper(text):
            return re.sub(r'\\(.)', r'\1', text)

        def single_quoted_wrapper(text):
            return text.replace('\\', '\\\\').replace("'", "\\'")

        def double_quoted_wrapper(text):
            return text.replace('\\', '\\\\').replace('"', '\\"')

        grammar = r"""
                # Text before the current string.
                (
                    [^'"#]                             |  # Not quoted characters.
                    '''  ([^']|'[^']|''[^']|\\.)*  ''' |  # Inside single quoted triple strings
                    "" " ([^"]|"[^"]|""[^"]|\\.)* "" " |  # Inside double quoted triple strings

                    \#[^\n]*(\n|$)           |  # Comment.
                    "(?!"") ([^"\\]|\\.)*"   |  # Inside double quoted strings.
                    '(?!'') ([^'\\]|\\.)*'      # Inside single quoted strings.

                        # Warning: The negative lookahead in the above two
                        #          statements is important. If we drop that,
                        #          then the regex will try to interpret every
                        #          triple quoted string also as a single quoted
                        #          string, making this exponentially expensive to
                        #          execute!
                )*
                # The current string that we're completing.
                (
                    ' (?P<var1>([^\n'\\]|\\.)*) |  # Inside a single quoted string.
                    " (?P<var2>([^\n"\\]|\\.)*)    # Inside a double quoted string.
                )
        """

        g = compile_grammar(grammar,
                            escape_funcs={
                                'var1': single_quoted_wrapper,
                                'var2': double_quoted_wrapper,
                            },
                            unescape_funcs={
                                'var1': unwrapper,
                                'var2': unwrapper,
                            })
        return g, GrammarCompleter(
            g, {
                'var1': PathCompleter(expanduser=True),
                'var2': PathCompleter(expanduser=True),
            })
Exemplo n.º 5
0
class QCompleter(Completer):
    """Completer for the q language"""
    def __init__(self):
        namespace = q(r'\d')
        res = q('.Q.res')
        dot_q = q('1_key .q')
        self.path_completer = PathCompleter()
        self.words_info = [(list(res), 'k'), (list(dot_q), 'q'),
                           (list(q.key(namespace)), str(namespace))]

    def get_completions(self, document, complete_event):
        """Yield completions"""
        # Detect a file handle
        m = HSYM_RE.match(document.text_before_cursor)
        if m:
            text = m.group(1)
            doc = Document(text, len(text))
            for c in self.path_completer.get_completions(doc, complete_event):
                yield c
        else:
            # Get word/text before cursor.
            word_before_cursor = document.get_word_before_cursor(False)
            for words, meta in self.words_info:
                for a in words:
                    if a.startswith(word_before_cursor):
                        yield Completion(a,
                                         -len(word_before_cursor),
                                         display_meta=meta)
Exemplo n.º 6
0
def prompt_spec_exec_dict(run_dict: dict) -> dict:
    """
    Prompt for the config of the spec exec runner.

    :param run_dict: run config dict (without the runner part)
    :return: runner config
    """
    runner_dict = {}

    runner_dict["file"] = default_prompt("SPEC like result file to use: ",
                                         validator=TypeValidator(FileName()),
                                         completer=PathCompleter())

    runner_dict["base_path"] = prompt("Property base path: ")

    runner_dict["path_regexp"] = prompt("Regexp matching the property path for each measured property: ",
                                        validator=NonEmptyValidator())

    def get(sub_path: str = ""): # just a mock
        """
        Get the value of the property with the given path.
        :param sub_path: given path relative to the base path
        :return: value of the property
        """
    print("The python code is entered via a multiline input. ")
    print("Press [Meta+Enter] or [Esc] followed by [Enter] to accept input.")
    print("You can click with the mouse in order to select text.")
    print("Use the get(sub_path: str) -> str function to obtain a properties value.")
    locs = locals()
    runner_dict["code"] = prompt_python("The python is executed for each measured property: \n", lambda: {}, lambda: {"get": locs["get"]})

    return runner_dict
Exemplo n.º 7
0
def prompt_dir(msg: str) -> str:
    """
    Prompt a directory path. Default is ".".

    :param msg: shown message
    :return: user input
    """
    return default_prompt(msg, default=".", validator=TypeValidator(DirName()),
                          completer=PathCompleter(only_directories=True))
Exemplo n.º 8
0
    def __init__(self,
                 vi_mode=False,
                 style=None,
                 search_text=None,
                 titlebar_tokens=None):
        assert isinstance(vi_mode, bool)
        assert style is None or isinstance(style, Style)

        self.sources = []
        self.current_source = 0  # Index in `self.sources`.
        self.vi_mode = vi_mode
        self.highlight_search = True
        self.in_colon_mode = False
        self.message = None
        self.displaying_help = False
        self.search_text = search_text
        self.display_titlebar = bool(titlebar_tokens)
        self.titlebar_tokens = titlebar_tokens or []

        # When this is True, always make sure that the cursor goes to the
        # bottom of the visible content. This is similar to 'tail -f'.
        self.forward_forever = False

        # Status information for all sources. Source -> _SourceInfo.
        # (Remember this info as long as the Source object exists.)
        self.source_info = weakref.WeakKeyDictionary()

        # Create prompt_toolkit stuff.
        self.buffers = BufferMapping({})

        def open_file(cli, buff):
            # Open file.
            self.open_file(buff.text)

            # Focus main buffer again.
            self.buffers.focus(cli, self.source_info[self.source].buffer_name)
            buff.reset()

        self.buffers['EXAMINE'] = Buffer(
            # Buffer for the 'Examine:' input.
            completer=PathCompleter(expanduser=True),
            accept_action=AcceptAction(open_file))

        self.layout = Layout(self)

        registry = create_key_bindings(self)
        self.application = Application(layout=self.layout.container,
                                       buffers=self.buffers,
                                       key_bindings_registry=registry,
                                       style=style or create_style(),
                                       mouse_support=True,
                                       on_render=self._on_render,
                                       use_alternate_screen=True,
                                       on_initialize=self._on_cli_initialize)

        self.cli = None
        self.eventloop = None
Exemplo n.º 9
0
def _prompt(message,
            default='',
            path=False,
            list_=None,
            required=True,
            validate=None,
            allow_invalid=False,
            password=False,
            help=None):
    def _get_prompt_tokens(cli):
        rv = [
            (Token.PROMPT, message),
            (Token.COLON, ': '),
        ]
        if first and help:
            rv.insert(0, (Token.HELP, wrap_text(help) + '\n'))
        return rv

    completer = None
    if path:
        completer = PathCompleter(only_directories=True, expanduser=True)
    elif list_:
        completer = WordCompleter(
            sorted(list_),
            ignore_case=True,
            sentence=True,
            meta_dict=(list_ if isinstance(list_, dict) else None))
        if validate is None:
            validate = list_.__contains__

    first = True
    while True:
        try:
            rv = prompt(get_prompt_tokens=_get_prompt_tokens,
                        default=default,
                        is_password=password,
                        completer=completer,
                        lexer=SimpleLexer(Token.INPUT),
                        style=PROMPT_TOOLKIT_STYLE)
        except (EOFError, KeyboardInterrupt):
            sys.exit(1)
        # pasting a multiline string works even with multiline disabled :(
        rv = rv.replace('\n', ' ').strip()
        if not rv:
            if not required:
                break
        else:
            if path:
                rv = os.path.abspath(os.path.expanduser(rv))
            if validate is None or validate(rv):
                break
            if allow_invalid and _confirm('Keep this value anyway?'):
                break
            default = rv
        first = False
    return rv
Exemplo n.º 10
0
    def _create_path_completer(self):
        def unwrapper(text):
            return re.sub(r'\\(.)', r'\1', text)

        def single_quoted_wrapper(text):
            return text.replace('\\', '\\\\').replace("'", "\\'")

        def double_quoted_wrapper(text):
            return text.replace('\\', '\\\\').replace('"', '\\"')

        grammar = r"""
                # Text before the current string.
                (
                    [^'"#]            |  # Not quoted characters.
                    '''.*'''          |  # Inside single quoted triple strings
                    "" ".*"" "        |  # Inside double quoted triple strings
                    \#[^\n]*          |  # Comment.
                    "([^"\\]|\\.)*"   |  # Inside double quoted strings.
                    '([^'\\]|\\.)*'      # Inside single quoted strings.
                )*
                # The current string that we're completing.
                (
                    ' (?P<var1>([^\n'\\]|\\.)*) |  # Inside a single quoted string.
                    " (?P<var2>([^\n"\\]|\\.)*)    # Inside a double quoted string.
                )
        """

        g = compile_grammar(grammar,
                            escape_funcs={
                                'var1': single_quoted_wrapper,
                                'var2': double_quoted_wrapper,
                            },
                            unescape_funcs={
                                'var1': unwrapper,
                                'var2': unwrapper,
                            })
        return g, GrammarCompleter(g, {
            'var1': PathCompleter(),
            'var2': PathCompleter(),
        })
Exemplo n.º 11
0
    def coroutine():
        global current_path
        open_dialog = TextInputDialog(title='Open file',
                                      label_text='Enter the path of a file:',
                                      completer=PathCompleter())

        path = yield From(show_dialog_as_float(open_dialog))
        current_path = path

        if path is not None:
            try:
                with open(path, 'rb') as f:
                    text_field.text = f.read().decode('utf-8', errors='ignore')
            except IOError as e:
                show_message('Error', '{}'.format(e))
Exemplo n.º 12
0
def askDir(msg, default=''):
    from prompt_toolkit import prompt
    try:
        # prompt_toolkit 1
        from prompt_toolkit.contrib.completers import PathCompleter
    except Exception:
        # prompt_toolkit 2
        from prompt_toolkit.completion import PathCompleter

    from ..utils import mkdirs

    is_cygwin = isCygwin()

    completer = PathCompleter(only_directories=True, expanduser=True)
    msg = six.u(msg) + u' '
    default = six.u(default)
    path = None

    while not path:
        # prompt_toolkit doesn't work in cygwin terminal or in PyCharm debugger
        # path = askString(msg, default) if is_cygwin else prompt(msg, default=default, completer=completer)
        if is_cygwin:
            path = askString(msg, default)
        else:
            try:
                path = prompt(msg, default=default, completer=completer)
            except AssertionError:  # stdout.isatty() fails in PyCharm debugger
                path = askString(msg, default)

        path = expandTilde(path)

        if path and not os.path.isdir(path):
            if os.path.lexists(path):
                print('Path %s exists, but is not a directory. Try again.' %
                      path)
                path = ''
                continue

            create = askYesNo("Path %s does not exist. Create it" % path,
                              default='y')
            if not create:
                path = ''
                continue

            mkdirs(path)
            print('Created %s' % path)

    return path
Exemplo n.º 13
0
def prompt_config(name: str, prompt_dict_func: t.Callable[[], dict]):
    """
    Prompt for the whole config file.

    :param name: description of the config (i.e. "run config")
    :param prompt_dict_func: function to get a single config dict
    """
    blocks = []
    file = prompt("YAML file to store the {name} in: ".format(name=name),
                                     validator=TypeValidator(ValidYamlFileName(allow_non_existent=True)),
                                     completer=PathCompleter())

    fd = None # type: io.IOBase
    if os.path.exists(file):
        actions = {
            "append": "Append to the file",
            "overwrite": "Overwrite the file"
        }
        res = prompt("The file already exists. What should be done? ",
                  completer=WordCompleter(sorted(list(actions.keys())), meta_dict=actions, ignore_case=True),
                  validator=WordValidator(list(actions.keys()) + ["a", "o"], error_msg="Not a valid action"))
        if res.startswith("a"):
            fd = open(file, "a+")
        elif res.startswith("o"):
            fd = open(file, "w+")
    else:
        fd = open(file, "w+")

    blocks.append(prompt_dict_func())

    def store_in_file():
        #print(blocks)
        yaml.dump(blocks, fd)
        fd.flush()
        fd.close()

    while prompt_yesno("Add another {name}? ".format(name=name)):
        try:
            blocks.append(prompt_dict_func())
        except KeyboardInterrupt:
            store_in_file()
            return
        except BaseException as ex:
            store_in_file()
            raise ex
    store_in_file()
Exemplo n.º 14
0
 def get_path_matches(self, _, word_before_cursor):
     completer = PathCompleter(expanduser=True)
     document = Document(text=word_before_cursor,
                         cursor_position=len(word_before_cursor))
     for c in completer.get_completions(document, None):
         yield Match(completion=c, priority=(0,))
Exemplo n.º 15
0
 def get_path():
     path = prompt('> enter path: ',
                   completer=PathCompleter(only_directories=True,
                                           expanduser=True))
     return (os.path.expanduser(path), ), {}
Exemplo n.º 16
0
# !/usr/bin/env python
# -*- coding:utf-8 -*-
from __future__ import unicode_literals
__author__ = 'bit4'
__github__ = 'https://github.com/bit4woo'
"""
Autocompletion example that displays the autocompletions like readline does by
binding a custom handler to the Tab key.
"""

from prompt_toolkit.shortcuts import prompt
from prompt_toolkit.shortcuts import confirm
from prompt_toolkit.contrib.completers import WordCompleter, PathCompleter
import os

animal_completer = PathCompleter("C:\\")


def main():
    text = prompt('Give some animals: ', completer=animal_completer)
    print('You said: %s' % text)


if __name__ == '__main__':
    answer = confirm('Should we do that? (Y/n) ')
    print('You said: %s' % answer)
Exemplo n.º 17
0
 def get_path_matches(self, _, word_before_cursor):
     completer = PathCompleter(expanduser=True)
     document = Document(text=word_before_cursor,
                         cursor_position=len(word_before_cursor))
     for c in completer.get_completions(document, None):
         yield Match(completion=c, priority=(0, ))
Exemplo n.º 18
0
def interactive():
    print color.G + "\n\nWelcome to interactive mode!\n\n"

    task_home_dir = os.path.join(os.path.dirname(__file__), "task")
    while True:
        # print already existed task
        tasks = os.listdir(task_home_dir)
        for task in tasks:
            if os.path.isfile(task):
                tasks.remove(task)
        print "{0}[{1}]{2} tasks existed:".format(color.R, len(tasks), color.G)
        for item in tasks:
            print item

        print(
            color.Y + "\n\n"
            "*.Input a existed task name to operate it or Input a new task name to create.\n"
            "*.Input q to query vuln from wvs.\n"
            "*.Input x to exit Ashe.\n"
            "\n" + color.W)
        task_completer = WordCompleter(tasks, ignore_case=True)
        task_name = prompt(u"==>", completer=task_completer)
        if task_name.lower() == "q":
            #QueryFromWVS()
            pass
        elif task_name.lower() in ['x', 'back']:
            break
        elif task_name == "":
            continue
        else:
            task_dir = os.path.join(task_home_dir, task_name)

            if os.path.isdir(task_dir):
                choice = prompt(
                    u"the task already exist, operate this task? (Y/n)", )
                if choice.lower() not in ["y", "yes", ""]:
                    continue
            else:
                os.mkdir(task_dir)
                print "task {0} created, chose what to do:".format(task_name)

            urls_file = os.path.join(task_dir,
                                     "{0}_urls_by_ashe.txt".format(task_name))
            urls_scanned_file = os.path.join(
                task_dir, "{0}_urls_scanned_by_ashe.txt".format(task_name))
            while True:
                index = taskDealIndex.format(task_name)
                choice = prompt(unicode(index))
                if choice == "1":
                    delete = prompt(u"Are you sure to DELETE this task?(y/N)")
                    if delete.lower() in ["y", "yes"]:
                        shutil.rmtree(task_dir)
                        break
                    else:
                        continue
                elif choice == "2":
                    path_completer = PathCompleter()
                    xmlfile = prompt(
                        u"parse xml, please input the xml file==>",
                        completer=path_completer,
                        history=FileHistory('history.txt'),
                        auto_suggest=AutoSuggestFromHistory(),
                    )
                    xmlfile = xmlfile.strip()
                    if os.path.isfile(xmlfile):
                        des_xml_file = os.path.join(task_dir,
                                                    os.path.basename(xmlfile))
                        if os.path.abspath(xmlfile) == os.path.abspath(
                                des_xml_file):  # same file
                            pass
                        elif os.path.exists(des_xml_file):
                            copy_choice = prompt(
                                u"The file already exist,Overwirte or keep Two(O/t)?"
                            )
                            if copy_choice.lower() in ["", "o"]:
                                shutil.copyfile(xmlfile,
                                                des_xml_file)  # overwrite
                            elif copy_choice.lower() == "t":
                                des_xml_file = os.path.join(
                                    task_dir,
                                    os.path.basename(xmlfile).split(".")[0] +
                                    "_1" +
                                    os.path.basename(xmlfile).split(".")[1])
                                shutil.copy(xmlfile, des_xml_file)
                            else:
                                continue
                        else:
                            shutil.copy(xmlfile, des_xml_file)
                        url_list = GetHttp(xmlfile)
                        print(url_list)
                        fp = open(urls_file, "a+")
                        if len(fp.readlines()) == 0:
                            pass
                        else:
                            fp.write("\n")
                        fp.writelines("\n".join(url_list))
                        fp.close()
                    else:
                        print "File do not exist!"
                        continue
                elif choice == "3":
                    IP_domain_file = prompt(
                        u"Input the file that contains domain and IP relationship(Teemo Result File)\n==>"
                    )
                    IP_domain_file = IP_domain_file.strip()
                    if os.path.isfile(IP_domain_file):
                        des_IP_Domain_file = os.path.join(
                            task_dir,
                            "Teemo-" + os.path.basename(IP_domain_file))
                        if os.path.abspath(IP_domain_file) == os.path.abspath(
                                des_IP_Domain_file):  # same file
                            pass
                        elif os.path.exists(des_IP_Domain_file):
                            shutil.copyfile(IP_domain_file,
                                            des_IP_Domain_file)  # overwrite
                        else:
                            shutil.copy(IP_domain_file, des_IP_Domain_file)
                        IP2domain(urls_file, des_IP_Domain_file)
                    else:
                        print "File do not exist!"
                        continue

                elif choice == "4":
                    if os.path.isfile(urls_file):
                        fp = open(urls_file, "r")
                        urls = fp.readlines()
                        fp.close()
                        end_index = -1
                        if SCANNER.lower() == "wvs11":
                            end_index = AddScans(urls)
                        elif SCANNER.lower() == "wvs10":
                            end_index = AddToWVS(urls)
                        print "{0} urls added".format(end_index + 1)
                        if end_index >= 0:
                            urls_left = urls[end_index + 1:-1]
                            urls_scanned = urls[0:end_index]
                        fp = open(urls_file, "w")
                        fp.writelines(urls_left)
                        fp.close()

                        fp = open(urls_scanned_file, "a")
                        fp.writelines(urls_scanned)
                        fp.write("____above urls added to scan at {0}______\n".
                                 format(datetime.datetime.now().strftime(
                                     "%m/%d/%Y %H%M")))
                        fp.close()
                        break
                    else:
                        print "{0} not found!".format(urls_file)
                elif choice.lower() in ["5", 'back', 'exit']:
                    break
                else:
                    continue