Path: blob/main/vendor/github.com/spf13/cobra/fish_completions.go
2875 views
// Copyright 2013-2023 The Cobra Authors1//2// Licensed under the Apache License, Version 2.0 (the "License");3// you may not use this file except in compliance with the License.4// You may obtain a copy of the License at5//6// http://www.apache.org/licenses/LICENSE-2.07//8// Unless required by applicable law or agreed to in writing, software9// distributed under the License is distributed on an "AS IS" BASIS,10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11// See the License for the specific language governing permissions and12// limitations under the License.1314package cobra1516import (17"bytes"18"fmt"19"io"20"os"21"strings"22)2324func genFishComp(buf io.StringWriter, name string, includeDesc bool) {25// Variables should not contain a '-' or ':' character26nameForVar := name27nameForVar = strings.ReplaceAll(nameForVar, "-", "_")28nameForVar = strings.ReplaceAll(nameForVar, ":", "_")2930compCmd := ShellCompRequestCmd31if !includeDesc {32compCmd = ShellCompNoDescRequestCmd33}34WriteStringAndCheck(buf, fmt.Sprintf("# fish completion for %-36s -*- shell-script -*-\n", name))35WriteStringAndCheck(buf, fmt.Sprintf(`36function __%[1]s_debug37set -l file "$BASH_COMP_DEBUG_FILE"38if test -n "$file"39echo "$argv" >> $file40end41end4243function __%[1]s_perform_completion44__%[1]s_debug "Starting __%[1]s_perform_completion"4546# Extract all args except the last one47set -l args (commandline -opc)48# Extract the last arg and escape it in case it is a space49set -l lastArg (string escape -- (commandline -ct))5051__%[1]s_debug "args: $args"52__%[1]s_debug "last arg: $lastArg"5354# Disable ActiveHelp which is not supported for fish shell55set -l requestComp "%[10]s=0 $args[1] %[3]s $args[2..-1] $lastArg"5657__%[1]s_debug "Calling $requestComp"58set -l results (eval $requestComp 2> /dev/null)5960# Some programs may output extra empty lines after the directive.61# Let's ignore them or else it will break completion.62# Ref: https://github.com/spf13/cobra/issues/127963for line in $results[-1..1]64if test (string trim -- $line) = ""65# Found an empty line, remove it66set results $results[1..-2]67else68# Found non-empty line, we have our proper output69break70end71end7273set -l comps $results[1..-2]74set -l directiveLine $results[-1]7576# For Fish, when completing a flag with an = (e.g., <program> -n=<TAB>)77# completions must be prefixed with the flag78set -l flagPrefix (string match -r -- '-.*=' "$lastArg")7980__%[1]s_debug "Comps: $comps"81__%[1]s_debug "DirectiveLine: $directiveLine"82__%[1]s_debug "flagPrefix: $flagPrefix"8384for comp in $comps85printf "%%s%%s\n" "$flagPrefix" "$comp"86end8788printf "%%s\n" "$directiveLine"89end9091# this function limits calls to __%[1]s_perform_completion, by caching the result behind $__%[1]s_perform_completion_once_result92function __%[1]s_perform_completion_once93__%[1]s_debug "Starting __%[1]s_perform_completion_once"9495if test -n "$__%[1]s_perform_completion_once_result"96__%[1]s_debug "Seems like a valid result already exists, skipping __%[1]s_perform_completion"97return 098end99100set --global __%[1]s_perform_completion_once_result (__%[1]s_perform_completion)101if test -z "$__%[1]s_perform_completion_once_result"102__%[1]s_debug "No completions, probably due to a failure"103return 1104end105106__%[1]s_debug "Performed completions and set __%[1]s_perform_completion_once_result"107return 0108end109110# this function is used to clear the $__%[1]s_perform_completion_once_result variable after completions are run111function __%[1]s_clear_perform_completion_once_result112__%[1]s_debug ""113__%[1]s_debug "========= clearing previously set __%[1]s_perform_completion_once_result variable =========="114set --erase __%[1]s_perform_completion_once_result115__%[1]s_debug "Successfully erased the variable __%[1]s_perform_completion_once_result"116end117118function __%[1]s_requires_order_preservation119__%[1]s_debug ""120__%[1]s_debug "========= checking if order preservation is required =========="121122__%[1]s_perform_completion_once123if test -z "$__%[1]s_perform_completion_once_result"124__%[1]s_debug "Error determining if order preservation is required"125return 1126end127128set -l directive (string sub --start 2 $__%[1]s_perform_completion_once_result[-1])129__%[1]s_debug "Directive is: $directive"130131set -l shellCompDirectiveKeepOrder %[9]d132set -l keeporder (math (math --scale 0 $directive / $shellCompDirectiveKeepOrder) %% 2)133__%[1]s_debug "Keeporder is: $keeporder"134135if test $keeporder -ne 0136__%[1]s_debug "This does require order preservation"137return 0138end139140__%[1]s_debug "This doesn't require order preservation"141return 1142end143144145# This function does two things:146# - Obtain the completions and store them in the global __%[1]s_comp_results147# - Return false if file completion should be performed148function __%[1]s_prepare_completions149__%[1]s_debug ""150__%[1]s_debug "========= starting completion logic =========="151152# Start fresh153set --erase __%[1]s_comp_results154155__%[1]s_perform_completion_once156__%[1]s_debug "Completion results: $__%[1]s_perform_completion_once_result"157158if test -z "$__%[1]s_perform_completion_once_result"159__%[1]s_debug "No completion, probably due to a failure"160# Might as well do file completion, in case it helps161return 1162end163164set -l directive (string sub --start 2 $__%[1]s_perform_completion_once_result[-1])165set --global __%[1]s_comp_results $__%[1]s_perform_completion_once_result[1..-2]166167__%[1]s_debug "Completions are: $__%[1]s_comp_results"168__%[1]s_debug "Directive is: $directive"169170set -l shellCompDirectiveError %[4]d171set -l shellCompDirectiveNoSpace %[5]d172set -l shellCompDirectiveNoFileComp %[6]d173set -l shellCompDirectiveFilterFileExt %[7]d174set -l shellCompDirectiveFilterDirs %[8]d175176if test -z "$directive"177set directive 0178end179180set -l compErr (math (math --scale 0 $directive / $shellCompDirectiveError) %% 2)181if test $compErr -eq 1182__%[1]s_debug "Received error directive: aborting."183# Might as well do file completion, in case it helps184return 1185end186187set -l filefilter (math (math --scale 0 $directive / $shellCompDirectiveFilterFileExt) %% 2)188set -l dirfilter (math (math --scale 0 $directive / $shellCompDirectiveFilterDirs) %% 2)189if test $filefilter -eq 1; or test $dirfilter -eq 1190__%[1]s_debug "File extension filtering or directory filtering not supported"191# Do full file completion instead192return 1193end194195set -l nospace (math (math --scale 0 $directive / $shellCompDirectiveNoSpace) %% 2)196set -l nofiles (math (math --scale 0 $directive / $shellCompDirectiveNoFileComp) %% 2)197198__%[1]s_debug "nospace: $nospace, nofiles: $nofiles"199200# If we want to prevent a space, or if file completion is NOT disabled,201# we need to count the number of valid completions.202# To do so, we will filter on prefix as the completions we have received203# may not already be filtered so as to allow fish to match on different204# criteria than the prefix.205if test $nospace -ne 0; or test $nofiles -eq 0206set -l prefix (commandline -t | string escape --style=regex)207__%[1]s_debug "prefix: $prefix"208209set -l completions (string match -r -- "^$prefix.*" $__%[1]s_comp_results)210set --global __%[1]s_comp_results $completions211__%[1]s_debug "Filtered completions are: $__%[1]s_comp_results"212213# Important not to quote the variable for count to work214set -l numComps (count $__%[1]s_comp_results)215__%[1]s_debug "numComps: $numComps"216217if test $numComps -eq 1; and test $nospace -ne 0218# We must first split on \t to get rid of the descriptions to be219# able to check what the actual completion will be.220# We don't need descriptions anyway since there is only a single221# real completion which the shell will expand immediately.222set -l split (string split --max 1 \t $__%[1]s_comp_results[1])223224# Fish won't add a space if the completion ends with any225# of the following characters: @=/:.,226set -l lastChar (string sub -s -1 -- $split)227if not string match -r -q "[@=/:.,]" -- "$lastChar"228# In other cases, to support the "nospace" directive we trick the shell229# by outputting an extra, longer completion.230__%[1]s_debug "Adding second completion to perform nospace directive"231set --global __%[1]s_comp_results $split[1] $split[1].232__%[1]s_debug "Completions are now: $__%[1]s_comp_results"233end234end235236if test $numComps -eq 0; and test $nofiles -eq 0237# To be consistent with bash and zsh, we only trigger file238# completion when there are no other completions239__%[1]s_debug "Requesting file completion"240return 1241end242end243244return 0245end246247# Since Fish completions are only loaded once the user triggers them, we trigger them ourselves248# so we can properly delete any completions provided by another script.249# Only do this if the program can be found, or else fish may print some errors; besides,250# the existing completions will only be loaded if the program can be found.251if type -q "%[2]s"252# The space after the program name is essential to trigger completion for the program253# and not completion of the program name itself.254# Also, we use '> /dev/null 2>&1' since '&>' is not supported in older versions of fish.255complete --do-complete "%[2]s " > /dev/null 2>&1256end257258# Remove any pre-existing completions for the program since we will be handling all of them.259complete -c %[2]s -e260261# this will get called after the two calls below and clear the $__%[1]s_perform_completion_once_result global262complete -c %[2]s -n '__%[1]s_clear_perform_completion_once_result'263# The call to __%[1]s_prepare_completions will setup __%[1]s_comp_results264# which provides the program's completion choices.265# If this doesn't require order preservation, we don't use the -k flag266complete -c %[2]s -n 'not __%[1]s_requires_order_preservation && __%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results'267# otherwise we use the -k flag268complete -k -c %[2]s -n '__%[1]s_requires_order_preservation && __%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results'269`, nameForVar, name, compCmd,270ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,271ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, activeHelpEnvVar(name)))272}273274// GenFishCompletion generates fish completion file and writes to the passed writer.275func (c *Command) GenFishCompletion(w io.Writer, includeDesc bool) error {276buf := new(bytes.Buffer)277genFishComp(buf, c.Name(), includeDesc)278_, err := buf.WriteTo(w)279return err280}281282// GenFishCompletionFile generates fish completion file.283func (c *Command) GenFishCompletionFile(filename string, includeDesc bool) error {284outFile, err := os.Create(filename)285if err != nil {286return err287}288defer outFile.Close()289290return c.GenFishCompletion(outFile, includeDesc)291}292293294