|
| 1 | +#!/usr/bin/env bash |
| 2 | + |
| 3 | +# Same as in https://github.com/mikkoi/keychain-bash-completion |
| 4 | + |
| 5 | +__keychain_init_completion() { |
| 6 | + COMPREPLY=() |
| 7 | + _get_comp_words_by_ref cur prev words cword |
| 8 | +} |
| 9 | +# Get ssh key file names. Find all files with .pub suffix and remove the suffix |
| 10 | +__keychain_ssh_keys() { |
| 11 | + if [[ -d ~/.ssh ]]; then |
| 12 | + keys=() |
| 13 | + while IFS= read -r -d '' file; do |
| 14 | + key="$(basename -s .pub "$file")" |
| 15 | + keys+=( "$key" ) |
| 16 | + done < <(\find "${HOME}/.ssh" -type f -name \*.pub -print0) |
| 17 | + echo "${keys[*]}" |
| 18 | + fi |
| 19 | +} |
| 20 | +# Get gpg keys and their UIDs when they are email addresses |
| 21 | +__keychain_gpg_keys() { |
| 22 | + keys=() |
| 23 | + while IFS= read -r row; do |
| 24 | + if [[ "$row" =~ ^sec:[a-z]:[[:digit:]]{0,}:[[:alnum:]]{0,}:([[:alnum:]]{0,}): ]]; then |
| 25 | + key="$(echo "${BASH_REMATCH[1]}" | cut -b 9-16)" |
| 26 | + keys+=( "$key" ) |
| 27 | + fi |
| 28 | + done < <(\gpg --list-secret-keys --with-colons) |
| 29 | + echo "${keys[*]}" |
| 30 | +} |
| 31 | +__keychain_command_line_options() { |
| 32 | + opts=() |
| 33 | + while IFS= read -r row; do |
| 34 | + if [[ "$row" =~ ^[[:space:]]{4}([-]{1}[[:alpha:]]{1})[[:space:]]{1,}([-]{2}[[:alnum:]]{1,})[[:space:]]{0,} ]] |
| 35 | + then |
| 36 | + opt1="${BASH_REMATCH[1]}" |
| 37 | + opts+=( "$opt1" ) |
| 38 | + opt2="${BASH_REMATCH[2]}" |
| 39 | + opts+=( "$opt2" ) |
| 40 | + elif [[ "$row" =~ ^[[:space:]]{4}([-]{2}[[:alnum:]]{1,})[[:space:]]{1,} ]] |
| 41 | + then |
| 42 | + opt="${BASH_REMATCH[1]}" |
| 43 | + opts+=( "$opt" ) |
| 44 | + fi |
| 45 | + done < <(\keychain --help 2>/dev/null) |
| 46 | + echo "${opts[*]}" |
| 47 | +} |
| 48 | + |
| 49 | +_keychain() { |
| 50 | + local cur |
| 51 | + if declare -F _init_completion >/dev/null 2>&1; then |
| 52 | + _init_completion |
| 53 | + else |
| 54 | + __keychain_init_completion |
| 55 | + fi |
| 56 | + |
| 57 | + COMPREPLY=() # Array variable storing the possible completions. |
| 58 | + cur=${COMP_WORDS[COMP_CWORD]} |
| 59 | + |
| 60 | + keys=( ) |
| 61 | + keys+=( "$(__keychain_command_line_options)" ) |
| 62 | + keys+=( "$(__keychain_ssh_keys)" ) |
| 63 | + keys+=( "$(__keychain_gpg_keys)" ) |
| 64 | + # shellcheck disable=SC2207 |
| 65 | + COMPREPLY=( $( compgen -W "${keys[*]}" -- "$cur" ) ) |
| 66 | + return 0 |
| 67 | +} |
| 68 | + |
| 69 | +complete -F _keychain keychain |
0 commit comments