|
| 1 | +#!/usr/bin/env bash |
| 2 | +#==============================================================# |
| 3 | +# File : pg_completion |
| 4 | +# Desc : auto-completion for pg commands |
| 5 | +# Path : /etc/bash_completion.d/pg |
| 6 | +# License : MIT |
| 7 | +# Author : waitingsong |
| 8 | +#==============================================================# |
| 9 | + |
| 10 | +# subcommands |
| 11 | +# - edit-config: Edit cluster configuration |
| 12 | +# - list: List the Patroni members for a given Patroni |
| 13 | + |
| 14 | + |
| 15 | +cache_duration=30 # seconds |
| 16 | +cache_timestamp=0 |
| 17 | +cache_pg_cls="" |
| 18 | +pg_subcommands="list edit-config" # from patronictl |
| 19 | + |
| 20 | +if ! command -v ansible-inventory &> /dev/null; then |
| 21 | + echo "ansible-inventory not found, skip auto-completion" |
| 22 | + return |
| 23 | +fi |
| 24 | + |
| 25 | +if ! command -v jq &> /dev/null; then |
| 26 | + echo "jq not found, skip auto-completion" |
| 27 | + return |
| 28 | +fi |
| 29 | + |
| 30 | +INVENTORY_FILE='' |
| 31 | +if [[ -f /home/dba/pigsty/pigsty.yml ]]; then |
| 32 | + INVENTORY_FILE="/home/dba/pigsty/pigsty.yml" |
| 33 | +fi |
| 34 | + |
| 35 | + |
| 36 | +# Pick up pg* clusters from inventory file |
| 37 | +_get_pg_cls() { |
| 38 | + ansible-inventory -i "$1" --list 2>/dev/null | jq -r '.all.children | map(select(type == "string" and startswith("pg"))) | .[] ' |
| 39 | +} |
| 40 | + |
| 41 | +_pg_completions() { |
| 42 | + local subcommands="$2" |
| 43 | + local cur prev words cword |
| 44 | + _get_comp_words_by_ref -n : cur prev words cword |
| 45 | + # echo "command: $command, subcommands: $subcommands, cur: $cur, prev: $prev, words: $words, cword: $cword" |
| 46 | + |
| 47 | + if [[ $cword -eq 1 ]]; then |
| 48 | + COMPREPLY=($(compgen -W "$pg_subcommands" -- "$cur")) |
| 49 | + return |
| 50 | + fi |
| 51 | + |
| 52 | + if [[ -n $prev ]] && [[ ! " $pg_subcommands " =~ " $prev " ]]; then |
| 53 | + echo $subcommands |
| 54 | + return |
| 55 | + fi |
| 56 | + |
| 57 | + local FILE="${INVENTORY_FILE:-'./pigsty.yml'}" |
| 58 | + if [[ $cword -eq 2 ]] && [[ -f "$FILE" ]]; then |
| 59 | + local current_time=$(date +%s) |
| 60 | + if [[ $cache_timestamp -eq 0 ]] || (( current_time - cache_timestamp > cache_duration )); then |
| 61 | + # echo "refresh cache" |
| 62 | + cache_pg_cls=$(_get_pg_cls $FILE) |
| 63 | + cache_timestamp=$current_time |
| 64 | + fi |
| 65 | + |
| 66 | + if [[ -n "$cache_pg_cls" ]]; then |
| 67 | + COMPREPLY=($(compgen -W "$cache_pg_cls" -- "$cur")) |
| 68 | + fi |
| 69 | + fi |
| 70 | +} |
| 71 | + |
| 72 | +complete -F _pg_completions pg |
| 73 | + |
0 commit comments