Skip to content

Commit

Permalink
Add a shortest_only option (#105)
Browse files Browse the repository at this point in the history
* add shortest_only option

* fix format
  • Loading branch information
ZanyMonk authored Jul 15, 2023
1 parent 79060f1 commit 0c32dce
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
11 changes: 10 additions & 1 deletion click_repl/_completer.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,14 @@ def text_type(text):
class ClickCompleter(Completer):
__slots__ = ("cli", "ctx", "parsed_args", "parsed_ctx", "ctx_command")

def __init__(self, cli, ctx, show_only_unused=False):
def __init__(self, cli, ctx, show_only_unused=False, shortest_only=False):
self.cli = cli
self.ctx = ctx
self.parsed_args = []
self.parsed_ctx = ctx
self.ctx_command = ctx.command
self.show_only_unused = show_only_unused
self.shortest_only = shortest_only

def _get_completion_from_autocompletion_functions(
self,
Expand Down Expand Up @@ -204,11 +205,19 @@ def _get_completion_for_cmd_args(
previous_args = args[: param.nargs * -1]
current_args = args[param.nargs * -1 :]

# Show only unused opts
already_present = any([
opt in previous_args for opt in opts
])
hide = self.show_only_unused and already_present and not param.multiple

# Show only shortest opt
if (self.shortest_only
and not incomplete # just typed a space
# not selecting a value for a longer version of this option
and args[-1] not in opts):
opts = [min(opts, key=len)]

for option in opts:
# We want to make sure if this parameter was called
# If we are inside a parameter that was called, we want to show only
Expand Down
25 changes: 25 additions & 0 deletions tests/test_completion/test_common_tests/test_option_completion.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,28 @@ def multiple_option(u):

completions = list(c.get_completions(Document("multiple-option -u t ")))
assert {x.text for x in completions} == {"-u"}


def test_shortest_only_mode():
@root_command.command()
@click.option("--foo", "-f", is_flag=True)
@click.option("-b", "--bar", is_flag=True)
@click.option("--foobar", is_flag=True)
def shortest_only(foo, bar, foobar):
pass

c.shortest_only = True

completions = list(c.get_completions(Document("shortest-only ")))
assert {x.text for x in completions} == {"-f", "-b", "--foobar"}

completions = list(c.get_completions(Document("shortest-only -")))
assert {x.text for x in completions} == {"-f", "--foo", "-b", "--bar", "--foobar"}

completions = list(c.get_completions(Document("shortest-only --f")))
assert {x.text for x in completions} == {"--foo", "--foobar"}

c.shortest_only = False

completions = list(c.get_completions(Document("shortest-only ")))
assert {x.text for x in completions} == {"-f", "--foo", "-b", "--bar", "--foobar"}

0 comments on commit 0c32dce

Please sign in to comment.