|
| 1 | +import re |
| 2 | +from click.shell_completion import add_completion_class, BashComplete |
| 3 | +from gettext import gettext as _ |
| 4 | + |
| 5 | + |
| 6 | +# inspired by https://github.com/pallets-eco/click-bash4.2-completion |
| 7 | +_bash_42_source = """\ |
| 8 | +%(complete_func)s() { |
| 9 | + local IFS=$'\\n' |
| 10 | + local response |
| 11 | + response=$(env COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD \ |
| 12 | +%(complete_var)s=bash_complete $1) |
| 13 | + for completion in $response; do |
| 14 | + IFS=',' read type value <<< "$completion" |
| 15 | + if [[ $type == 'dir' ]]; then |
| 16 | + COMPREPLY=() |
| 17 | + compopt -o dirnames |
| 18 | + elif [[ $type == 'file' ]]; then |
| 19 | + COMPREPLY=() |
| 20 | + compopt -o default |
| 21 | + elif [[ $type == 'plain' ]]; then |
| 22 | + COMPREPLY+=($value) |
| 23 | + fi |
| 24 | + done |
| 25 | + return 0 |
| 26 | +} |
| 27 | +%(complete_func)s_setup() { |
| 28 | + local COMPLETION_OPTIONS="" |
| 29 | + local BASH_VERSION_ARR=(${BASH_VERSION//./ }) |
| 30 | + # Only BASH version 4.4 and later have the nosort option. |
| 31 | + if [ ${BASH_VERSION_ARR[0]} -gt 4 ] || ([ ${BASH_VERSION_ARR[0]} -eq 4 ] \ |
| 32 | +&& [ ${BASH_VERSION_ARR[1]} -ge 4 ]); then |
| 33 | + COMPLETION_OPTIONS="-o nosort" |
| 34 | + fi |
| 35 | + complete $COMPLETION_OPTIONS -F %(complete_func)s %(prog_name)s |
| 36 | +} |
| 37 | +%(complete_func)s_setup; |
| 38 | +""" |
| 39 | + |
| 40 | + |
| 41 | +@add_completion_class |
| 42 | +class _PatchedBashComplete(BashComplete): |
| 43 | + """ Patched Shell completion for Bash """ |
| 44 | + source_template = _bash_42_source |
| 45 | + name = 'bash' # this will override the default bash provided by click |
| 46 | + |
| 47 | + # change the original version check |
| 48 | + def _check_version(self) -> None: |
| 49 | + import subprocess |
| 50 | + |
| 51 | + output = subprocess.run( |
| 52 | + ["bash", "-c", "echo ${BASH_VERSION}"], stdout=subprocess.PIPE |
| 53 | + ) |
| 54 | + match = re.search(r"^(\d+)\.(\d+)\.\d+", output.stdout.decode()) |
| 55 | + |
| 56 | + if match is not None: |
| 57 | + major, minor = match.groups() |
| 58 | + |
| 59 | + if major < "4" or major == "4" and minor < "2": |
| 60 | + raise RuntimeError( |
| 61 | + _( |
| 62 | + "Shell completion is not supported for Bash" |
| 63 | + " versions older than 4.2." |
| 64 | + ) |
| 65 | + ) |
| 66 | + else: |
| 67 | + raise RuntimeError( |
| 68 | + _("Couldn't detect Bash version, shell completion is not supported.") |
| 69 | + ) |
0 commit comments