How to use the argcomplete.completers function in argcomplete

To help you get started, we’ve selected a few argcomplete examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github haaksmash / flowhub / flowhub / core.py View on Github external
feature_subs = feature.add_subparsers(dest='action')

    fstart = feature_subs.add_parser('start',
        help="start a new feature branch")
    fstart.add_argument('name', help="name of the feature")
    fstart.add_argument('--track', default=False, action='store_true',
        help="set up a tracking branch on your github immediately.")
    fstart.add_argument('-i', '--issue-number', type=int,
        action='store', default=None,
        help="prepend an issue number to the feature name")

    fwork = feature_subs.add_parser('work',
        help="switch to a different feature (by name)")
    fwork_name = fwork.add_argument('identifier', help="name of feature to switch to")
    if offline_engine is not None:
        fwork_name.completer = argcomplete.completers.ChoicesCompleter(
            [branch.name.split(FEATURE_PREFIX)[1] for branch in repo.branches
                if branch.name.startswith(FEATURE_PREFIX)],
        )
    fwork.add_argument('--issue', '-i',
        action='store_true', default=False,
        help='switch to a branch by issue number instead of by name')

    fpublish = feature_subs.add_parser('publish',
        help="send the current feature branch to origin and create a pull-request")
    fpublish_name = fpublish.add_argument('name', nargs='?',
        default=None,
        help='name of feature to publish. If not given, uses current feature',
    )
    if offline_engine is not None:
        fpublish_name.completer = argcomplete.completers.ChoicesCompleter(
            [branch.name.split(FEATURE_PREFIX)[1] for branch in repo.branches
github haaksmash / flowhub / flowhub / core.py View on Github external
help="name of the feature to abandon. If not given, uses current feature",
    )
    if offline_engine is not None:
        fabandon_name.completer = argcomplete.completers.ChoicesCompleter(
            [branch.name.split(FEATURE_PREFIX)[1] for branch in repo.branches
                if branch.name.startswith(FEATURE_PREFIX)],
        )

    faccepted = feature_subs.add_parser('accepted',
        help="declare that a feature was accepted into the trunk")
    faccepted_name = faccepted.add_argument('name', nargs='?',
        default=None,
        help="name of the accepted feature. If not given, assumes current feature",
    )
    if offline_engine is not None:
        faccepted_name.completer = argcomplete.completers.ChoicesCompleter(
            [branch.name.split(FEATURE_PREFIX)[1] for branch in repo.branches
                if branch.name.startswith(FEATURE_PREFIX)],
        )

    faccepted.add_argument('--no-delete', action='store_true', default=False,
        help="don't delete the accepted feature branch")
    feature_subs.add_parser('list',
        help='list the feature names on this repository')

    #
    # Hotfixes
    #
    hotfix_subs = hotfix.add_subparsers(dest='action')

    hstart = hotfix_subs.add_parser('start',
        help="start a new hotfix branch")
github CTSRD-CHERI / cheribuild / pycheribuild / jenkins.py View on Github external
def finalize_options(self, available_targets: list, **kwargs):
        target_option = self._parser.add_argument("targets", metavar="TARGET", nargs=argparse.OPTIONAL,
                                                  help="The target to build",
                                                  choices=available_targets + [EXTRACT_SDK_TARGET])
        if self._completing_arguments:
            try:
                import argcomplete
            except ImportError:
                sys.exit("argcomplete missing")
            target_completer = argcomplete.completers.ChoicesCompleter(available_targets)
            target_option.completer = target_completer
            argcomplete.autocomplete(
                self._parser,
                always_complete_options=None,  # don't print -/-- by default
                print_suppressed=True,  # also include target-specific options
                )
github haaksmash / flowhub / flowhub / cli.py View on Github external
def _setup_parser_completers(self, completers):
        for argument, completion_values in completers.items():
            argument.completer = argcomplete.completers.ChoicesCompleter(
                completion_values,
            )
github kislyuk / argcomplete / argcomplete / __init__.py View on Github external
completer = completers.ChoicesCompleter(active_action.choices)
                elif not isinstance(active_action, argparse._SubParsersAction):
                    completer = self.default_completer

            if completer:
                if isinstance(completer, SuppressCompleter) and completer.suppress():
                    continue

                if callable(completer):
                    completions_from_callable = [c for c in completer(
                        prefix=cword_prefix, action=active_action, parser=parser, parsed_args=parsed_args)
                        if self.validator(c, cword_prefix)]

                    if completions_from_callable:
                        completions += completions_from_callable
                        if isinstance(completer, completers.ChoicesCompleter):
                            self._display_completions.update(
                                [[(x,), active_action.help] for x in completions_from_callable])
                        else:
                            self._display_completions.update(
                                [[(x,), ""] for x in completions_from_callable])
                else:
                    debug("Completer is not callable, trying the readline completer protocol instead")
                    for i in range(9999):
                        next_completion = completer.complete(cword_prefix, i)
                        if next_completion is None:
                            break
                        if self.validator(next_completion, cword_prefix):
                            self._display_completions.update({(next_completion,): ""})
                            completions.append(next_completion)
                if optional_prefix:
                    completions = [optional_prefix + "=" + completion for completion in completions]
github microsoft / knack / knack / completion.py View on Github external
import os
import argcomplete

from .util import CtxTypeError

ARGCOMPLETE_ENV_NAME = '_ARGCOMPLETE'


class CaseInsensitiveChoicesCompleter(argcomplete.completers.ChoicesCompleter):
    def __call__(self, prefix, **kwargs):
        return (c for c in self.choices if c.lower().startswith(prefix.lower()))


# Override the choices completer with one that is case insensitive
argcomplete.completers.ChoicesCompleter = CaseInsensitiveChoicesCompleter


class CLICompletion(object):

    def __init__(self, cli_ctx=None):
        """ Sets up and gets completions for auto-complete

        :param cli_ctx: CLI Context
        :type cli_ctx: knack.cli.CLI
        """
        from .cli import CLI
        if cli_ctx is not None and not isinstance(cli_ctx, CLI):
            raise CtxTypeError(cli_ctx)
        self.cli_ctx = cli_ctx
        self.cli_ctx.data['completer_active'] = ARGCOMPLETE_ENV_NAME in os.environ
github kislyuk / argcomplete / argcomplete / __init__.py View on Github external
# so it is extremely difficult to tell which completers to run.
                    # Running all remaining completers will probably show more than the user wants
                    # but it also guarantees we won't miss anything.
                    complete_remaining_positionals = True
                if not complete_remaining_positionals:
                    if action_is_satisfied(active_action) and not action_is_open(active_action):
                        debug("Skipping", active_action)
                        continue

            debug("Activating completion for", active_action, active_action._orig_class)
            # completer = getattr(active_action, "completer", DefaultCompleter())
            completer = getattr(active_action, "completer", None)

            if completer is None:
                if active_action.choices is not None and not isinstance(active_action, argparse._SubParsersAction):
                    completer = completers.ChoicesCompleter(active_action.choices)
                elif not isinstance(active_action, argparse._SubParsersAction):
                    completer = self.default_completer

            if completer:
                if isinstance(completer, SuppressCompleter) and completer.suppress():
                    continue

                if callable(completer):
                    completions_from_callable = [c for c in completer(
                        prefix=cword_prefix, action=active_action, parser=parser, parsed_args=parsed_args)
                        if self.validator(c, cword_prefix)]

                    if completions_from_callable:
                        completions += completions_from_callable
                        if isinstance(completer, completers.ChoicesCompleter):
                            self._display_completions.update(
github python-cmd2 / cmd2 / cmd2 / argcomplete_bridge.py View on Github external
"""Hijack the ArgComplete's bash completion handler to return AutoCompleter results"""

try:
    # check if argcomplete is installed
    import argcomplete
except ImportError:  # pragma: no cover
    # not installed, skip the rest of the file
    DEFAULT_COMPLETER = None
else:
    # argcomplete is installed

    # Newer versions of argcomplete have FilesCompleter at top level, older versions only have it under completers
    try:
        DEFAULT_COMPLETER = argcomplete.FilesCompleter()
    except AttributeError:
        DEFAULT_COMPLETER = argcomplete.completers.FilesCompleter()

    from cmd2.argparse_completer import ACTION_ARG_CHOICES, ACTION_SUPPRESS_HINT
    from contextlib import redirect_stdout
    import copy
    from io import StringIO
    import os
    import shlex
    import sys
    from typing import List, Tuple, Union

    from . import constants
    from . import utils

    def tokens_for_completion(line: str, endidx: int) -> Union[Tuple[List[str], List[str], int, int],
                                                               Tuple[None, None, None, None]]:
        """