Example #1
0
 def complete_domain(self, args, prefix):
     super(InconsistentUsersCommand, self).__call__(args)
     json_obj = self.ls.domains.list()
     debug(str(json_obj))
     RESOURCE_IDENTIFIER = "identifier"
     return (v.get(RESOURCE_IDENTIFIER)
             for v in json_obj if v.get(RESOURCE_IDENTIFIER).startswith(prefix))
Example #2
0
 def complete_domain(self, args, prefix):
     """TODO"""
     super(InconsistentUsersCommand, self).__call__(args)
     json_obj = self.ls.domains.list()
     debug(str(json_obj))
     resource_identifier = "identifier"
     return (v.get(resource_identifier) for v in json_obj
             if v.get(resource_identifier).startswith(prefix))
Example #3
0
 def complete_nodes(self, args, prefix):
     """TODO"""
     from argcomplete import debug
     super(WgNodesCommand, self).__call__(args)
     cli = self.ls.workgroup_nodes
     debug("nodes : ", args.nodes)
     if args.nodes:
         debug("len nodes : ", len(args.nodes))
     debug("prefix : ", prefix)
     debug("len prefix : ", len(prefix))
     if args.nodes:
         parent = get_uuid_from(args.nodes[-1])
         if len(parent) >= 36:
             json_obj = cli.list(args.wg_uuid, parent)
             return convert_to_list_nodes(json_obj)
         else:
             if len(args.nodes) >= 2:
                 parent = get_uuid_from(args.nodes[-2])
             else:
                 parent = None
             json_obj = cli.list(args.wg_uuid, parent)
             return convert_to_list_nodes(json_obj)
     else:
         parent = None
         json_obj = cli.list(args.wg_uuid)
         return convert_to_list_nodes(json_obj)
Example #4
0
 def complete_nodes(self, args, prefix):
     """TODO"""
     from argcomplete import debug
     super(WgNodesCommand, self).__call__(args)
     cli = self.ls.workgroup_nodes
     debug("nodes : ", args.nodes)
     if args.nodes:
         debug("len nodes : ", len(args.nodes))
     debug("prefix : ", prefix)
     debug("len prefix : ", len(prefix))
     if args.nodes:
         parent = get_uuid_from(args.nodes[-1])
         if len(parent) >= 36:
             json_obj = cli.list(args.wg_uuid, parent)
             return convert_to_list_nodes(json_obj)
         else:
             if len(args.nodes) >= 2:
                 parent = get_uuid_from(args.nodes[-2])
             else:
                 parent = None
             json_obj = cli.list(args.wg_uuid, parent)
             return convert_to_list_nodes(json_obj)
     else:
         parent = None
         json_obj = cli.list(args.wg_uuid)
         return convert_to_list_nodes(json_obj)
Example #5
0
def convert_to_list(json_obj, parent, prefix):
    """Convert json_obj to a list ready to use for completion"""
    from argcomplete import debug
    debug("\n>----------- convert_to_list - 1  -----------------")
    debug("parent: ", parent)
    debug("prefix: ", prefix)
    debug("RAW", json_obj)
    json_obj = list(
        format_record_for_autocomplete(row) for row in json_obj
        if row.get('type') == "FOLDER")
    debug("UUIDS", json_obj)
    debug("------------ convert_to_list - 1 ----------------<\n")
    return json_obj
Example #6
0
 def __call__(self, prefix, **kwargs):
     from argcomplete import debug
     try:
         debug("\n------------ ThreadCompleter -----------------")
         debug("Kwargs content :")
         for i, j in kwargs.items():
             debug("key : " + str(i))
             debug("\t - " + str(j))
         debug("\n------------ ThreadCompleter -----------------\n")
         args = kwargs.get('parsed_args')
         # FIXME
         wg_cmd = WgNodeContentListCommand(self.config)
         return wg_cmd.complete_workgroups(args, prefix)
     # pylint: disable=broad-except
     except Exception as ex:
         debug("\nERROR:An exception was caught :" + str(ex) + "\n")
         import traceback
         traceback.print_exc()
         debug("\n------\n")
         return ["comlete-error"]
        def __call__(self,
                     argument_parser,
                     completer=None,
                     always_complete_options=True,
                     exit_method=os._exit,
                     output_stream=None,
                     exclude=None,
                     validator=None,
                     print_suppressed=False,
                     append_space=None,
                     default_completer=DEFAULT_COMPLETER):
            """
            :param argument_parser: The argument parser to autocomplete on
            :type argument_parser: :class:`argparse.ArgumentParser`
            :param always_complete_options:
                Controls the autocompletion of option strings if an option string opening character (normally ``-``) has
                not been entered. If ``True`` (default), both short (``-x``) and long (``--x``) option strings will be
                suggested. If ``False``, no option strings will be suggested. If ``long``, long options and short
                options with no long variant will be suggested. If ``short``, short options and long options with no
                short variant will be suggested.
            :type always_complete_options: boolean or string
            :param exit_method:
                Method used to stop the program after printing completions. Defaults to :meth:`os._exit`. If you want to
                perform a normal exit that calls exit handlers, use :meth:`sys.exit`.
            :type exit_method: callable
            :param exclude: List of strings representing options to be omitted from autocompletion
            :type exclude: iterable
            :param validator:
                Function to filter all completions through before returning (called with two string arguments,
                completion and prefix; return value is evaluated as a boolean)
            :type validator: callable
            :param print_suppressed:
                Whether or not to autocomplete options that have the ``help=argparse.SUPPRESS`` keyword argument set.
            :type print_suppressed: boolean
            :param append_space:
                Whether to append a space to unique matches. The default is ``True``.
            :type append_space: boolean

            .. note::
                If you are not subclassing CompletionFinder to override its behaviors,
                use ``argcomplete.autocomplete()`` directly. It has the same signature as this method.

            Produces tab completions for ``argument_parser``. See module docs for more info.

            Argcomplete only executes actions if their class is known not to have side effects. Custom action classes
            can be added to argcomplete.safe_actions, if their values are wanted in the ``parsed_args`` completer
            argument, or their execution is otherwise desirable.
            """
            # Older versions of argcomplete have fewer keyword arguments
            if sys.version_info >= (3, 5):
                self.__init__(argument_parser,
                              always_complete_options=always_complete_options,
                              exclude=exclude,
                              validator=validator,
                              print_suppressed=print_suppressed,
                              append_space=append_space,
                              default_completer=default_completer)
            else:
                self.__init__(argument_parser,
                              always_complete_options=always_complete_options,
                              exclude=exclude,
                              validator=validator,
                              print_suppressed=print_suppressed)

            if "_ARGCOMPLETE" not in os.environ:
                # not an argument completion invocation
                return

            try:
                argcomplete.debug_stream = os.fdopen(9, "w")
            except IOError:
                argcomplete.debug_stream = sys.stderr

            if output_stream is None:
                try:
                    output_stream = os.fdopen(8, "wb")
                except IOError:
                    argcomplete.debug(
                        "Unable to open fd 8 for writing, quitting")
                    exit_method(1)

            ifs = os.environ.get("_ARGCOMPLETE_IFS", "\013")
            if len(ifs) != 1:
                argcomplete.debug(
                    "Invalid value for IFS, quitting [{v}]".format(v=ifs))
                exit_method(1)

            comp_line = os.environ["COMP_LINE"]
            comp_point = int(os.environ["COMP_POINT"])

            comp_line = argcomplete.ensure_str(comp_line)

            ##############################
            # SWAPPED FOR AUTOCOMPLETER
            #
            # Replaced with our own tokenizer function
            ##############################
            tokens, _, begidx, endidx = tokens_for_completion(
                comp_line, comp_point)

            # _ARGCOMPLETE is set by the shell script to tell us where comp_words
            # should start, based on what we're completing.
            # 1: <script> [args]
            # 2: python <script> [args]
            # 3: python -m <module> [args]
            start = int(os.environ["_ARGCOMPLETE"]) - 1
            ##############################
            # SWAPPED FOR AUTOCOMPLETER
            #
            # Applying the same token dropping to our tokens
            ##############################
            # comp_words = comp_words[start:]
            tokens = tokens[start:]

            # debug("\nLINE: {!r}".format(comp_line),
            #       "\nPOINT: {!r}".format(comp_point),
            #       "\nPREQUOTE: {!r}".format(cword_prequote),
            #       "\nPREFIX: {!r}".format(cword_prefix),
            #       "\nSUFFIX: {!r}".format(cword_suffix),
            #       "\nWORDS:", comp_words)

            ##############################
            # SWAPPED FOR AUTOCOMPLETER
            #
            # Replaced with our own completion function and customizing the returned values
            ##############################
            # completions = self._get_completions(comp_words, cword_prefix, cword_prequote, last_wordbreak_pos)

            # capture stdout from the autocompleter
            result = StringIO()
            with redirect_stdout(result):
                completions = completer.complete_command(
                    tokens, tokens[-1], comp_line, begidx, endidx)
            outstr = result.getvalue()

            if completions:
                # If any completion has a space in it, then quote all completions
                # this improves the user experience so they don't nede to go back and add a quote
                if ' ' in ''.join(completions):
                    completions = [
                        '"{}"'.format(entry) for entry in completions
                    ]

                argcomplete.debug("\nReturning completions:", completions)

                output_stream.write(
                    ifs.join(completions).encode(argcomplete.sys_encoding))
            elif outstr:
                # if there are no completions, but we got something from stdout, try to print help
                # trick the bash completion into thinking there are 2 completions that are unlikely
                # to ever match.

                comp_type = int(os.environ["COMP_TYPE"])
                if comp_type == 63:  # type is 63 for second tab press
                    print(outstr.rstrip(),
                          file=argcomplete.debug_stream,
                          end='')

                if completions is not None:
                    output_stream.write(
                        ifs.join([ifs, ' ']).encode(argcomplete.sys_encoding))
                else:
                    output_stream.write(
                        ifs.join([]).encode(argcomplete.sys_encoding))
            else:
                # if completions is None we assume we don't know how to handle it so let bash
                # go forward with normal filesystem completion
                output_stream.write(
                    ifs.join([]).encode(argcomplete.sys_encoding))
            output_stream.flush()
            argcomplete.debug_stream.flush()
            exit_method(0)
 def __call__(self, prefix, **kwargs):
     from argcomplete import debug
     try:
         debug("\n------------ SharedSpaceCompleter -----------------")
         debug("Kwargs content :")
         for i, j in kwargs.items():
             debug("key : " + str(i))
             debug("\t - " + str(j))
         debug("\n------------ SharedSpaceCompleter -----------------\n")
         args = kwargs.get('parsed_args')
         cmd = DefaultCommand(self.config)
         return cmd.complete_shared_spaces(args, prefix)
     # pylint: disable=broad-except
     except Exception as ex:
         debug("\nERROR:An exception was caught :" + str(ex) + "\n")
         import traceback
         traceback.print_exc()
         debug("\n------\n")
         return ["comlete-error"]
Example #9
0
 def __call__(self, prefix, **kwargs):
     from argcomplete import debug
     try:
         debug("\n------------ ContactListsCompleter -----------------")
         debug("Kwargs content :")
         for i, j in kwargs.items():
             debug("key : " + str(i))
             debug("\t - " + str(j))
         debug("\n------------ ContactListsCompleter -----------------\n")
         args = kwargs.get('parsed_args')
         thread_cmd = DefaultCommand(self.config)
         return thread_cmd.complete_lists(args, prefix)
     # pylint: disable=broad-except
     except Exception as ex:
         debug("\nERROR:An exception was caught :" + str(ex) + "\n")
Example #10
0
def convert_to_list(json_obj, parent, prefix):
    """Convert json_obj to a list ready to use for completion"""
    from argcomplete import debug
    debug("\n>----------- convert_to_list - 1  -----------------")
    debug("parent: ", parent)
    debug("prefix: ", prefix)
    debug("RAW", json_obj)
    json_obj = list(
        format_record_for_autocomplete(row)
        for row in json_obj if row.get('type') == "FOLDER"
    )
    debug("UUIDS", json_obj)
    debug("------------ convert_to_list - 1 ----------------<\n")
    return json_obj
Example #11
0
 def __call__(self, prefix, **kwargs):
     from argcomplete import debug
     try:
         debug("\n------------ ThreadCompleter -----------------")
         debug("Kwargs content :")
         for i, j in kwargs.items():
             debug("key : " + str(i))
             debug("\t - " + str(j))
         debug("\n------------ ThreadCompleter -----------------\n")
         args = kwargs.get('parsed_args')
         # FIXME
         wg_cmd = WgNodeContentListCommand(self.config)
         return wg_cmd.complete_workgroups(args, prefix)
     # pylint: disable-msg=W0703
     except Exception as ex:
         debug("\nERROR:An exception was caught :" + str(ex) + "\n")
         import traceback
         traceback.print_exc()
         debug("\n------\n")
         return ["comlete-error"]
 def __call__(self, prefix, **kwargs):
     from argcomplete import debug
     try:
         debug("\n------------ ContactListsCompleter -----------------")
         debug("Kwargs content :")
         for i, j in kwargs.items():
             debug("key : " + str(i))
             debug("\t - " + str(j))
         debug("\n------------ ContactListsCompleter -----------------\n")
         args = kwargs.get('parsed_args')
         thread_cmd = DefaultCommand(self.config)
         return thread_cmd.complete_lists(args, prefix)
     # pylint: disable-msg=W0703
     except Exception as ex:
         debug("\nERROR:An exception was caught :" + str(ex) + "\n")
Example #13
0
    def __call__(self, prefix, **kwargs):
        from argcomplete import debug
        try:
            debug("\n------------ DefaultCompleter -----------------")
            debug("Kwargs content :")
            for i, j in kwargs.items():
                debug("key : " + str(i))
                debug("\t - " + str(j))
            debug("\n------------ DefaultCompleter -----------------\n")

            args = kwargs.get('parsed_args')
            # pylint: disable-msg=W0612
            parser = kwargs.get('parser')
            #a = parser.parse_known_args()

            # getting form args the current Command and looking for a method
            # called by default 'complete'. See __init__ method. The method
            # name is store in the class member called self.func_name
            fn = getattr(args.__func__, self.func_name, None)
            if fn:
                return fn(args, prefix)

        # pylint: disable-msg=W0703
        except Exception as e:
            from argcomplete import warn
            warn("\nERROR::COMPLETE:An exception was caught :" + str(e) + "\n")
            import traceback
            traceback.print_exc()
            debug("\n------\n")
            return ["comlete-error"]