fish_completions.go 7.4 KB

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