Debian Codegraph @

examples/completion/completion.py

raw
1 import os
2
3 import click
4 from click.shell_completion import CompletionItem
5
6
7 @click.group()
8 def cli():
9 pass
10
11
12 @cli.command()
13 @click.option("--dir", type=click.Path(file_okay=False))
14 def ls(dir):
15 click.echo("\n".join(os.listdir(dir)))
16
17
18 def get_env_vars(ctx, param, incomplete):
19 # Returning a list of values is a shortcut to returning a list of
20 # CompletionItem(value).
21 return [k for k in os.environ if incomplete in k]
22
23
24 @cli.command(help="A command to print environment variables")
25 @click.argument("envvar", shell_complete=get_env_vars)
26 def show_env(envvar):
27 click.echo(f"Environment variable: {envvar}")
28 click.echo(f"Value: {os.environ[envvar]}")
29
30
31 @cli.group(help="A group that holds a subcommand")
32 def group():
33 pass
34
35
36 def list_users(ctx, param, incomplete):
37 # You can generate completions with help strings by returning a list
38 # of CompletionItem. You can match on whatever you want, including
39 # the help.
40 items = [("bob", "butcher"), ("alice", "baker"), ("jerry", "candlestick maker")]
41 out = []
42
43 for value, help in items:
44 if incomplete in value or incomplete in help:
45 out.append(CompletionItem(value, help=help))
46
47 return out
48
49
50 @group.command(help="Choose a user")
51 @click.argument("user", shell_complete=list_users)
52 def select_user(user):
53 click.echo(f"Chosen user is {user}")
54
55
56 cli.add_command(group)