-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalias-completion-bash
executable file
·117 lines (88 loc) · 2.48 KB
/
alias-completion-bash
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#!/bin/bash
# run in sub-shell, to avoid altering environment
(
usage() {
cmd=$(basename "${BASH_SOURCE[0]}")
cat << _EOF_
usage: source $cmd <alias> <command>
outputs bash completion code for alias of command.
for example:
$ source $cmd k kubectl
to load the generated completion:
$ eval "\$(source $cmd k kubectl)"
you could use it in ~/.bashrc, or use it in completion files.
_EOF_
}
get_completion() {
# use the completion of the following command
cmd_upstream=$1
# get the name of this command
cmd_current=$2
# try to get upstream completion specification
completion_spec=$(complete -p "$cmd_upstream" 2>/dev/null)
# if that failed, load upstream completion
if [ "$completion_spec" = '' ]; then
_completion_loader "$cmd_upstream"
# try if it works now
completion_spec=$(complete -p "$cmd_upstream" 2>/dev/null)
# if failed again, bail out
if [ "$completion_spec" = '' ]; then
# (will never happen in current version of bash-completion,
# because it will always give `complete -F _minimal <command>` instead of failing)
return 1
fi
fi
# use upstream specification for our own purpose
#
# for example, if this is upstream:
#
# complete -o default -F _pacman pacman
#
# we want to turn that into this:
#
# complete -o default -F _pacman pacmatic
#
completion_spec=${completion_spec/ $cmd_upstream/ $cmd_current}
# output
echo "$completion_spec"
}
get_output() {
alias=$1
command=$2
# build output
output=''
# if upstream completion is not loaded, add loading to output
if [ "$(complete -p "$command" 2>/dev/null)" = '' ]; then
output+="_completion_loader $(printf '%q' "$command");"$'\n'
fi
# get completion, and add to output
completion=$(get_completion "$command" "$alias")
output+="$completion;"$'\n'
# output
echo "$output"
}
main() {
# handle options
case "$1" in
-h|--help|--usage) usage; return;;
esac
# this program must be sourced
if ! [ "${BASH_SOURCE[0]}" != "$0" ]; then
usage 1>&2
return 1
fi
# get arguments
alias=$1
command=$2
# validate arguments
if ! (command -v "$alias" && command -v "$command") >/dev/null 2>&1; then
usage 1>&2
return 1
fi
# get output
output=$(get_output "$alias" "$command")
# output
echo "$output"
}
main "$@"
)