iterative / shtab

↔️ Automagic shell tab completion for Python CLI applications
https://docs.iterative.ai/shtab
Other
375 stars 34 forks source link

Custom completion logic? #34

Open travis-bear opened 3 years ago

travis-bear commented 3 years ago

I didn't see any info on how to set up custom completion logic. E.g. generate a list of completions that are the result of a sql query, etc. It's unclear if this is simply not supported, or merely a gap in the current documentation.

skshetry commented 3 years ago

@travis-bear, you'd need to add a custom script for bash/zsh and then need to register it.

You can take an example of how we do in DVC: https://github.com/iterative/dvc/blob/master/dvc/command/completion.py

To go into steps, first you need to add custom scripts to generate completions, eg: https://github.com/iterative/dvc/blob/aa74712576855b82fc31364056cea9f8a6a1b37b/dvc/command/completion.py#L97

Then, you'd have to register the function that you'd want to call for that particular completion for zsh and bash.

https://github.com/iterative/dvc/blob/aa74712576855b82fc31364056cea9f8a6a1b37b/dvc/command/completion.py#L80-L82

At last, you just need to specify it for the particular option to autocomplete for. https://github.com/iterative/dvc/blob/e7686f90a695b327a81b16563d603238ee96cfcf/dvc/command/repro.py#L53

balta2ar commented 3 years ago

@skshetry @casperdcl what if I need custom actions that depend on other provided arguments? e.g. https://github.com/kislyuk/argcomplete has the following example in the README.md:

./describe_github_user.py --organization heroku --member <TAB>
def github_org_members(prefix, parsed_args, **kwargs):
    resource = "https://api.github.com/orgs/{org}/members".format(org=parsed_args.organization)
    return (member['login'] for member in requests.get(resource).json() if member['login'].startswith(prefix))

parser = argparse.ArgumentParser()
parser.add_argument("--organization", help="GitHub organization")
parser.add_argument("--member", help="GitHub member").completer = github_org_members

I need to know the value of organization when I complete member. This is not currently supported, right?

casperdcl commented 3 years ago

@balta2ar that level of inter-dependent completion (--member choices conditional on --org's value) isn't yet supported, no.