pip install with shell completion
Asked Answered
C

1

12

I am writing a command line tool in python and using pip to distribute it. I have written some scripts (one for bash and one for zsh) to allow the tool to have tab completion. Is there a way to get pip to install these scripts when someone does a pip install?

For example: I have a completion.bash file. When someone does

pip install mypackage

It will also source the bash file.

I'm pretty sure I can do this for linux and bash by putting the script in my data_files section in the setup.py script.

data_file=[
    ('/etc/bash_completion.d', ['bin/completion.bash'])
],  

But how can I do this so it is platform and shell independent? I need it to work for mac/linux in both bash and zsh. If possible, even support windows.

Is this possible? And if so, how?


In case it matters, here is my bash script:

_foo_complete() {
 COMPREPLY=()
 local words=( "${COMP_WORDS[@]}" )
 local word="${COMP_WORDS[COMP_CWORD]}"
 words=("${words[@]:1}")
 local completions="$(foo completer --cmplt=\""${words[*]}"\")"
 COMPREPLY=( $(compgen -W "$completions" -- "$word") )
}

complete -F _foo_complete foo

I am currently installing it by just running source completion.bash

Cindycine answered 22/9, 2014 at 18:34 Comment(0)
W
5

You are asking several different questions.

First, there's no cross-platform or cross-shell solution for defining custom shell-completions. The one you posted works for bash, but in tcsh, for example, you use tcsh's complete command, which works differently than bash's.

Second, sourcing the files which contain those completion-definitions at the time of pip install wouldn't do much good. The completions might work in that very session, but what you probably want is for them to take effect in future sessions (i.e. shell invocations) as well. For that, your files would have to be sourced each time the shell starts (e.g. from within user's .bashrc, in case of bash).

This measn that "installing" your files simply means placing them somewhere, and suggesting the users should source them from their respective dot-rc file. Even if you could, you shouldn't try to "force" it. Give your users the option to add that to their dot-rc file if they want.

The best approach would probably be to include in your package a completion-definitions file per supported shell, e.g. complete.bash, complete.tcsh, and god knows what for windows (sorry, I'm not a windows user).

Wescott answered 22/9, 2014 at 19:7 Comment(2)
Check out pip for an example reference of completions that work across a few shells. To see which, run python -m pip completion --help If you are using BASH, you'd append your profile/rc with python -m pip completion --bashBasipetal
Here is the reference: pip.pypa.io/en/stable/user_guide/#command-completionDesiccate

© 2022 - 2024 — McMap. All rights reserved.