1package cobra
2
3import (
4	"bytes"
5	"fmt"
6	"io"
7	"os"
8	"strings"
9)
10
11func genFishComp(buf io.StringWriter, name string, includeDesc bool) {
12	// Variables should not contain a '-' or ':' character
13	nameForVar := name
14	nameForVar = strings.Replace(nameForVar, "-", "_", -1)
15	nameForVar = strings.Replace(nameForVar, ":", "_", -1)
16
17	compCmd := ShellCompRequestCmd
18	if !includeDesc {
19		compCmd = ShellCompNoDescRequestCmd
20	}
21	WriteStringAndCheck(buf, fmt.Sprintf("# fish completion for %-36s -*- shell-script -*-\n", name))
22	WriteStringAndCheck(buf, fmt.Sprintf(`
23function __%[1]s_debug
24    set file "$BASH_COMP_DEBUG_FILE"
25    if test -n "$file"
26        echo "$argv" >> $file
27    end
28end
29
30function __%[1]s_perform_completion
31    __%[1]s_debug "Starting __%[1]s_perform_completion with: $argv"
32
33    set args (string split -- " " "$argv")
34    set lastArg "$args[-1]"
35
36    __%[1]s_debug "args: $args"
37    __%[1]s_debug "last arg: $lastArg"
38
39    set emptyArg ""
40    if test -z "$lastArg"
41        __%[1]s_debug "Setting emptyArg"
42        set emptyArg \"\"
43    end
44    __%[1]s_debug "emptyArg: $emptyArg"
45
46    if not type -q "$args[1]"
47        # This can happen when "complete --do-complete %[2]s" is called when running this script.
48        __%[1]s_debug "Cannot find $args[1]. No completions."
49        return
50    end
51
52    set requestComp "$args[1] %[3]s $args[2..-1] $emptyArg"
53    __%[1]s_debug "Calling $requestComp"
54
55    set results (eval $requestComp 2> /dev/null)
56    set comps $results[1..-2]
57    set directiveLine $results[-1]
58
59    # For Fish, when completing a flag with an = (e.g., <program> -n=<TAB>)
60    # completions must be prefixed with the flag
61    set flagPrefix (string match -r -- '-.*=' "$lastArg")
62
63    __%[1]s_debug "Comps: $comps"
64    __%[1]s_debug "DirectiveLine: $directiveLine"
65    __%[1]s_debug "flagPrefix: $flagPrefix"
66
67    for comp in $comps
68        printf "%%s%%s\n" "$flagPrefix" "$comp"
69    end
70
71    printf "%%s\n" "$directiveLine"
72end
73
74# This function does three things:
75# 1- Obtain the completions and store them in the global __%[1]s_comp_results
76# 2- Set the __%[1]s_comp_do_file_comp flag if file completion should be performed
77#    and unset it otherwise
78# 3- Return true if the completion results are not empty
79function __%[1]s_prepare_completions
80    # Start fresh
81    set --erase __%[1]s_comp_do_file_comp
82    set --erase __%[1]s_comp_results
83
84    # Check if the command-line is already provided.  This is useful for testing.
85    if not set --query __%[1]s_comp_commandLine
86        # Use the -c flag to allow for completion in the middle of the line
87        set __%[1]s_comp_commandLine (commandline -c)
88    end
89    __%[1]s_debug "commandLine is: $__%[1]s_comp_commandLine"
90
91    set results (__%[1]s_perform_completion "$__%[1]s_comp_commandLine")
92    set --erase __%[1]s_comp_commandLine
93    __%[1]s_debug "Completion results: $results"
94
95    if test -z "$results"
96        __%[1]s_debug "No completion, probably due to a failure"
97        # Might as well do file completion, in case it helps
98        set --global __%[1]s_comp_do_file_comp 1
99        return 1
100    end
101
102    set directive (string sub --start 2 $results[-1])
103    set --global __%[1]s_comp_results $results[1..-2]
104
105    __%[1]s_debug "Completions are: $__%[1]s_comp_results"
106    __%[1]s_debug "Directive is: $directive"
107
108    set shellCompDirectiveError %[4]d
109    set shellCompDirectiveNoSpace %[5]d
110    set shellCompDirectiveNoFileComp %[6]d
111    set shellCompDirectiveFilterFileExt %[7]d
112    set shellCompDirectiveFilterDirs %[8]d
113
114    if test -z "$directive"
115        set directive 0
116    end
117
118    set compErr (math (math --scale 0 $directive / $shellCompDirectiveError) %% 2)
119    if test $compErr -eq 1
120        __%[1]s_debug "Received error directive: aborting."
121        # Might as well do file completion, in case it helps
122        set --global __%[1]s_comp_do_file_comp 1
123        return 1
124    end
125
126    set filefilter (math (math --scale 0 $directive / $shellCompDirectiveFilterFileExt) %% 2)
127    set dirfilter (math (math --scale 0 $directive / $shellCompDirectiveFilterDirs) %% 2)
128    if test $filefilter -eq 1; or test $dirfilter -eq 1
129        __%[1]s_debug "File extension filtering or directory filtering not supported"
130        # Do full file completion instead
131        set --global __%[1]s_comp_do_file_comp 1
132        return 1
133    end
134
135    set nospace (math (math --scale 0 $directive / $shellCompDirectiveNoSpace) %% 2)
136    set nofiles (math (math --scale 0 $directive / $shellCompDirectiveNoFileComp) %% 2)
137
138    __%[1]s_debug "nospace: $nospace, nofiles: $nofiles"
139
140    # Important not to quote the variable for count to work
141    set numComps (count $__%[1]s_comp_results)
142    __%[1]s_debug "numComps: $numComps"
143
144    if test $numComps -eq 1; and test $nospace -ne 0
145        # To support the "nospace" directive we trick the shell
146        # by outputting an extra, longer completion.
147        __%[1]s_debug "Adding second completion to perform nospace directive"
148        set --append __%[1]s_comp_results $__%[1]s_comp_results[1].
149    end
150
151    if test $numComps -eq 0; and test $nofiles -eq 0
152        __%[1]s_debug "Requesting file completion"
153        set --global __%[1]s_comp_do_file_comp 1
154    end
155
156    # If we don't want file completion, we must return true even if there
157    # are no completions found.  This is because fish will perform the last
158    # completion command, even if its condition is false, if no other
159    # completion command was triggered
160    return (not set --query __%[1]s_comp_do_file_comp)
161end
162
163# Since Fish completions are only loaded once the user triggers them, we trigger them ourselves
164# so we can properly delete any completions provided by another script.
165# The space after the the program name is essential to trigger completion for the program
166# and not completion of the program name itself.
167complete --do-complete "%[2]s " > /dev/null 2>&1
168# Using '> /dev/null 2>&1' since '&>' is not supported in older versions of fish.
169
170# Remove any pre-existing completions for the program since we will be handling all of them.
171complete -c %[2]s -e
172
173# The order in which the below two lines are defined is very important so that __%[1]s_prepare_completions
174# is called first.  It is __%[1]s_prepare_completions that sets up the __%[1]s_comp_do_file_comp variable.
175#
176# This completion will be run second as complete commands are added FILO.
177# It triggers file completion choices when __%[1]s_comp_do_file_comp is set.
178complete -c %[2]s -n 'set --query __%[1]s_comp_do_file_comp'
179
180# This completion will be run first as complete commands are added FILO.
181# The call to __%[1]s_prepare_completions will setup both __%[1]s_comp_results and __%[1]s_comp_do_file_comp.
182# It provides the program's completion choices.
183complete -c %[2]s -n '__%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results'
184
185`, nameForVar, name, compCmd,
186		ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
187		ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs))
188}
189
190// GenFishCompletion generates fish completion file and writes to the passed writer.
191func (c *Command) GenFishCompletion(w io.Writer, includeDesc bool) error {
192	buf := new(bytes.Buffer)
193	genFishComp(buf, c.Name(), includeDesc)
194	_, err := buf.WriteTo(w)
195	return err
196}
197
198// GenFishCompletionFile generates fish completion file.
199func (c *Command) GenFishCompletionFile(filename string, includeDesc bool) error {
200	outFile, err := os.Create(filename)
201	if err != nil {
202		return err
203	}
204	defer outFile.Close()
205
206	return c.GenFishCompletion(outFile, includeDesc)
207}
208