podman
396 строк · 13.2 Кб
1// Copyright 2013-2023 The Cobra Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package cobra
16
17import (
18"bytes"
19"fmt"
20"io"
21"os"
22)
23
24func (c *Command) genBashCompletion(w io.Writer, includeDesc bool) error {
25buf := new(bytes.Buffer)
26genBashComp(buf, c.Name(), includeDesc)
27_, err := buf.WriteTo(w)
28return err
29}
30
31func genBashComp(buf io.StringWriter, name string, includeDesc bool) {
32compCmd := ShellCompRequestCmd
33if !includeDesc {
34compCmd = ShellCompNoDescRequestCmd
35}
36
37WriteStringAndCheck(buf, fmt.Sprintf(`# bash completion V2 for %-36[1]s -*- shell-script -*-
38
39__%[1]s_debug()
40{
41if [[ -n ${BASH_COMP_DEBUG_FILE-} ]]; then
42echo "$*" >> "${BASH_COMP_DEBUG_FILE}"
43fi
44}
45
46# Macs have bash3 for which the bash-completion package doesn't include
47# _init_completion. This is a minimal version of that function.
48__%[1]s_init_completion()
49{
50COMPREPLY=()
51_get_comp_words_by_ref "$@" cur prev words cword
52}
53
54# This function calls the %[1]s program to obtain the completion
55# results and the directive. It fills the 'out' and 'directive' vars.
56__%[1]s_get_completion_results() {
57local requestComp lastParam lastChar args
58
59# Prepare the command to request completions for the program.
60# Calling ${words[0]} instead of directly %[1]s allows handling aliases
61args=("${words[@]:1}")
62requestComp="${words[0]} %[2]s ${args[*]}"
63
64lastParam=${words[$((${#words[@]}-1))]}
65lastChar=${lastParam:$((${#lastParam}-1)):1}
66__%[1]s_debug "lastParam ${lastParam}, lastChar ${lastChar}"
67
68if [[ -z ${cur} && ${lastChar} != = ]]; then
69# If the last parameter is complete (there is a space following it)
70# We add an extra empty parameter so we can indicate this to the go method.
71__%[1]s_debug "Adding extra empty parameter"
72requestComp="${requestComp} ''"
73fi
74
75# When completing a flag with an = (e.g., %[1]s -n=<TAB>)
76# bash focuses on the part after the =, so we need to remove
77# the flag part from $cur
78if [[ ${cur} == -*=* ]]; then
79cur="${cur#*=}"
80fi
81
82__%[1]s_debug "Calling ${requestComp}"
83# Use eval to handle any environment variables and such
84out=$(eval "${requestComp}" 2>/dev/null)
85
86# Extract the directive integer at the very end of the output following a colon (:)
87directive=${out##*:}
88# Remove the directive
89out=${out%%:*}
90if [[ ${directive} == "${out}" ]]; then
91# There is not directive specified
92directive=0
93fi
94__%[1]s_debug "The completion directive is: ${directive}"
95__%[1]s_debug "The completions are: ${out}"
96}
97
98__%[1]s_process_completion_results() {
99local shellCompDirectiveError=%[3]d
100local shellCompDirectiveNoSpace=%[4]d
101local shellCompDirectiveNoFileComp=%[5]d
102local shellCompDirectiveFilterFileExt=%[6]d
103local shellCompDirectiveFilterDirs=%[7]d
104local shellCompDirectiveKeepOrder=%[8]d
105
106if (((directive & shellCompDirectiveError) != 0)); then
107# Error code. No completion.
108__%[1]s_debug "Received error from custom completion go code"
109return
110else
111if (((directive & shellCompDirectiveNoSpace) != 0)); then
112if [[ $(type -t compopt) == builtin ]]; then
113__%[1]s_debug "Activating no space"
114compopt -o nospace
115else
116__%[1]s_debug "No space directive not supported in this version of bash"
117fi
118fi
119if (((directive & shellCompDirectiveKeepOrder) != 0)); then
120if [[ $(type -t compopt) == builtin ]]; then
121# no sort isn't supported for bash less than < 4.4
122if [[ ${BASH_VERSINFO[0]} -lt 4 || ( ${BASH_VERSINFO[0]} -eq 4 && ${BASH_VERSINFO[1]} -lt 4 ) ]]; then
123__%[1]s_debug "No sort directive not supported in this version of bash"
124else
125__%[1]s_debug "Activating keep order"
126compopt -o nosort
127fi
128else
129__%[1]s_debug "No sort directive not supported in this version of bash"
130fi
131fi
132if (((directive & shellCompDirectiveNoFileComp) != 0)); then
133if [[ $(type -t compopt) == builtin ]]; then
134__%[1]s_debug "Activating no file completion"
135compopt +o default
136else
137__%[1]s_debug "No file completion directive not supported in this version of bash"
138fi
139fi
140fi
141
142# Separate activeHelp from normal completions
143local completions=()
144local activeHelp=()
145__%[1]s_extract_activeHelp
146
147if (((directive & shellCompDirectiveFilterFileExt) != 0)); then
148# File extension filtering
149local fullFilter filter filteringCmd
150
151# Do not use quotes around the $completions variable or else newline
152# characters will be kept.
153for filter in ${completions[*]}; do
154fullFilter+="$filter|"
155done
156
157filteringCmd="_filedir $fullFilter"
158__%[1]s_debug "File filtering command: $filteringCmd"
159$filteringCmd
160elif (((directive & shellCompDirectiveFilterDirs) != 0)); then
161# File completion for directories only
162
163local subdir
164subdir=${completions[0]}
165if [[ -n $subdir ]]; then
166__%[1]s_debug "Listing directories in $subdir"
167pushd "$subdir" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return
168else
169__%[1]s_debug "Listing directories in ."
170_filedir -d
171fi
172else
173__%[1]s_handle_completion_types
174fi
175
176__%[1]s_handle_special_char "$cur" :
177__%[1]s_handle_special_char "$cur" =
178
179# Print the activeHelp statements before we finish
180if ((${#activeHelp[*]} != 0)); then
181printf "\n";
182printf "%%s\n" "${activeHelp[@]}"
183printf "\n"
184
185# The prompt format is only available from bash 4.4.
186# We test if it is available before using it.
187if (x=${PS1@P}) 2> /dev/null; then
188printf "%%s" "${PS1@P}${COMP_LINE[@]}"
189else
190# Can't print the prompt. Just print the
191# text the user had typed, it is workable enough.
192printf "%%s" "${COMP_LINE[@]}"
193fi
194fi
195}
196
197# Separate activeHelp lines from real completions.
198# Fills the $activeHelp and $completions arrays.
199__%[1]s_extract_activeHelp() {
200local activeHelpMarker="%[9]s"
201local endIndex=${#activeHelpMarker}
202
203while IFS='' read -r comp; do
204if [[ ${comp:0:endIndex} == $activeHelpMarker ]]; then
205comp=${comp:endIndex}
206__%[1]s_debug "ActiveHelp found: $comp"
207if [[ -n $comp ]]; then
208activeHelp+=("$comp")
209fi
210else
211# Not an activeHelp line but a normal completion
212completions+=("$comp")
213fi
214done <<<"${out}"
215}
216
217__%[1]s_handle_completion_types() {
218__%[1]s_debug "__%[1]s_handle_completion_types: COMP_TYPE is $COMP_TYPE"
219
220case $COMP_TYPE in
22137|42)
222# Type: menu-complete/menu-complete-backward and insert-completions
223# If the user requested inserting one completion at a time, or all
224# completions at once on the command-line we must remove the descriptions.
225# https://github.com/spf13/cobra/issues/1508
226local tab=$'\t' comp
227while IFS='' read -r comp; do
228[[ -z $comp ]] && continue
229# Strip any description
230comp=${comp%%%%$tab*}
231# Only consider the completions that match
232if [[ $comp == "$cur"* ]]; then
233COMPREPLY+=("$comp")
234fi
235done < <(printf "%%s\n" "${completions[@]}")
236;;
237
238*)
239# Type: complete (normal completion)
240__%[1]s_handle_standard_completion_case
241;;
242esac
243}
244
245__%[1]s_handle_standard_completion_case() {
246local tab=$'\t' comp
247
248# Short circuit to optimize if we don't have descriptions
249if [[ "${completions[*]}" != *$tab* ]]; then
250IFS=$'\n' read -ra COMPREPLY -d '' < <(compgen -W "${completions[*]}" -- "$cur")
251return 0
252fi
253
254local longest=0
255local compline
256# Look for the longest completion so that we can format things nicely
257while IFS='' read -r compline; do
258[[ -z $compline ]] && continue
259# Strip any description before checking the length
260comp=${compline%%%%$tab*}
261# Only consider the completions that match
262[[ $comp == "$cur"* ]] || continue
263COMPREPLY+=("$compline")
264if ((${#comp}>longest)); then
265longest=${#comp}
266fi
267done < <(printf "%%s\n" "${completions[@]}")
268
269# If there is a single completion left, remove the description text
270if ((${#COMPREPLY[*]} == 1)); then
271__%[1]s_debug "COMPREPLY[0]: ${COMPREPLY[0]}"
272comp="${COMPREPLY[0]%%%%$tab*}"
273__%[1]s_debug "Removed description from single completion, which is now: ${comp}"
274COMPREPLY[0]=$comp
275else # Format the descriptions
276__%[1]s_format_comp_descriptions $longest
277fi
278}
279
280__%[1]s_handle_special_char()
281{
282local comp="$1"
283local char=$2
284if [[ "$comp" == *${char}* && "$COMP_WORDBREAKS" == *${char}* ]]; then
285local word=${comp%%"${comp##*${char}}"}
286local idx=${#COMPREPLY[*]}
287while ((--idx >= 0)); do
288COMPREPLY[idx]=${COMPREPLY[idx]#"$word"}
289done
290fi
291}
292
293__%[1]s_format_comp_descriptions()
294{
295local tab=$'\t'
296local comp desc maxdesclength
297local longest=$1
298
299local i ci
300for ci in ${!COMPREPLY[*]}; do
301comp=${COMPREPLY[ci]}
302# Properly format the description string which follows a tab character if there is one
303if [[ "$comp" == *$tab* ]]; then
304__%[1]s_debug "Original comp: $comp"
305desc=${comp#*$tab}
306comp=${comp%%%%$tab*}
307
308# $COLUMNS stores the current shell width.
309# Remove an extra 4 because we add 2 spaces and 2 parentheses.
310maxdesclength=$(( COLUMNS - longest - 4 ))
311
312# Make sure we can fit a description of at least 8 characters
313# if we are to align the descriptions.
314if ((maxdesclength > 8)); then
315# Add the proper number of spaces to align the descriptions
316for ((i = ${#comp} ; i < longest ; i++)); do
317comp+=" "
318done
319else
320# Don't pad the descriptions so we can fit more text after the completion
321maxdesclength=$(( COLUMNS - ${#comp} - 4 ))
322fi
323
324# If there is enough space for any description text,
325# truncate the descriptions that are too long for the shell width
326if ((maxdesclength > 0)); then
327if ((${#desc} > maxdesclength)); then
328desc=${desc:0:$(( maxdesclength - 1 ))}
329desc+="…"
330fi
331comp+=" ($desc)"
332fi
333COMPREPLY[ci]=$comp
334__%[1]s_debug "Final comp: $comp"
335fi
336done
337}
338
339__start_%[1]s()
340{
341local cur prev words cword split
342
343COMPREPLY=()
344
345# Call _init_completion from the bash-completion package
346# to prepare the arguments properly
347if declare -F _init_completion >/dev/null 2>&1; then
348_init_completion -n =: || return
349else
350__%[1]s_init_completion -n =: || return
351fi
352
353__%[1]s_debug
354__%[1]s_debug "========= starting completion logic =========="
355__%[1]s_debug "cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}, cword is $cword"
356
357# The user could have moved the cursor backwards on the command-line.
358# We need to trigger completion from the $cword location, so we need
359# to truncate the command-line ($words) up to the $cword location.
360words=("${words[@]:0:$cword+1}")
361__%[1]s_debug "Truncated words[*]: ${words[*]},"
362
363local out directive
364__%[1]s_get_completion_results
365__%[1]s_process_completion_results
366}
367
368if [[ $(type -t compopt) = "builtin" ]]; then
369complete -o default -F __start_%[1]s %[1]s
370else
371complete -o default -o nospace -F __start_%[1]s %[1]s
372fi
373
374# ex: ts=4 sw=4 et filetype=sh
375`, name, compCmd,
376ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
377ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder,
378activeHelpMarker))
379}
380
381// GenBashCompletionFileV2 generates Bash completion version 2.
382func (c *Command) GenBashCompletionFileV2(filename string, includeDesc bool) error {
383outFile, err := os.Create(filename)
384if err != nil {
385return err
386}
387defer outFile.Close()
388
389return c.GenBashCompletionV2(outFile, includeDesc)
390}
391
392// GenBashCompletionV2 generates Bash completion file version 2
393// and writes it to the passed writer.
394func (c *Command) GenBashCompletionV2(w io.Writer, includeDesc bool) error {
395return c.genBashCompletion(w, includeDesc)
396}
397