File: completion.py

package info (click to toggle)
python-asyncclick 8.1.8.0%2Basync-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,444 kB
  • sloc: python: 11,700; makefile: 22; sh: 10
file content (56 lines) | stat: -rw-r--r-- 1,407 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import os

import asyncclick as click
from asyncclick.shell_completion import CompletionItem


@click.group()
def cli():
    pass


@cli.command()
@click.option("--dir", type=click.Path(file_okay=False))
def ls(dir):
    click.echo("\n".join(os.listdir(dir)))


def get_env_vars(ctx, param, incomplete):
    # Returning a list of values is a shortcut to returning a list of
    # CompletionItem(value).
    return [k for k in os.environ if incomplete in k]


@cli.command(help="A command to print environment variables")
@click.argument("envvar", shell_complete=get_env_vars)
def show_env(envvar):
    click.echo(f"Environment variable: {envvar}")
    click.echo(f"Value: {os.environ[envvar]}")


@cli.group(help="A group that holds a subcommand")
def group():
    pass


def list_users(ctx, param, incomplete):
    # You can generate completions with help strings by returning a list
    # of CompletionItem. You can match on whatever you want, including
    # the help.
    items = [("bob", "butcher"), ("alice", "baker"), ("jerry", "candlestick maker")]
    out = []

    for value, help in items:
        if incomplete in value or incomplete in help:
            out.append(CompletionItem(value, help=help))

    return out


@group.command(help="Choose a user")
@click.argument("user", shell_complete=list_users)
def select_user(user):
    click.echo(f"Chosen user is {user}")


cli.add_command(group)