Path: blob/main/vendor/github.com/spf13/cobra/zsh_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)2223// GenZshCompletionFile generates zsh completion file including descriptions.24func (c *Command) GenZshCompletionFile(filename string) error {25return c.genZshCompletionFile(filename, true)26}2728// GenZshCompletion generates zsh completion file including descriptions29// and writes it to the passed writer.30func (c *Command) GenZshCompletion(w io.Writer) error {31return c.genZshCompletion(w, true)32}3334// GenZshCompletionFileNoDesc generates zsh completion file without descriptions.35func (c *Command) GenZshCompletionFileNoDesc(filename string) error {36return c.genZshCompletionFile(filename, false)37}3839// GenZshCompletionNoDesc generates zsh completion file without descriptions40// and writes it to the passed writer.41func (c *Command) GenZshCompletionNoDesc(w io.Writer) error {42return c.genZshCompletion(w, false)43}4445// MarkZshCompPositionalArgumentFile only worked for zsh and its behavior was46// not consistent with Bash completion. It has therefore been disabled.47// Instead, when no other completion is specified, file completion is done by48// default for every argument. One can disable file completion on a per-argument49// basis by using ValidArgsFunction and ShellCompDirectiveNoFileComp.50// To achieve file extension filtering, one can use ValidArgsFunction and51// ShellCompDirectiveFilterFileExt.52//53// Deprecated54func (c *Command) MarkZshCompPositionalArgumentFile(argPosition int, patterns ...string) error {55return nil56}5758// MarkZshCompPositionalArgumentWords only worked for zsh. It has therefore59// been disabled.60// To achieve the same behavior across all shells, one can use61// ValidArgs (for the first argument only) or ValidArgsFunction for62// any argument (can include the first one also).63//64// Deprecated65func (c *Command) MarkZshCompPositionalArgumentWords(argPosition int, words ...string) error {66return nil67}6869func (c *Command) genZshCompletionFile(filename string, includeDesc bool) error {70outFile, err := os.Create(filename)71if err != nil {72return err73}74defer outFile.Close()7576return c.genZshCompletion(outFile, includeDesc)77}7879func (c *Command) genZshCompletion(w io.Writer, includeDesc bool) error {80buf := new(bytes.Buffer)81genZshComp(buf, c.Name(), includeDesc)82_, err := buf.WriteTo(w)83return err84}8586func genZshComp(buf io.StringWriter, name string, includeDesc bool) {87compCmd := ShellCompRequestCmd88if !includeDesc {89compCmd = ShellCompNoDescRequestCmd90}91WriteStringAndCheck(buf, fmt.Sprintf(`#compdef %[1]s92compdef _%[1]s %[1]s9394# zsh completion for %-36[1]s -*- shell-script -*-9596__%[1]s_debug()97{98local file="$BASH_COMP_DEBUG_FILE"99if [[ -n ${file} ]]; then100echo "$*" >> "${file}"101fi102}103104_%[1]s()105{106local shellCompDirectiveError=%[3]d107local shellCompDirectiveNoSpace=%[4]d108local shellCompDirectiveNoFileComp=%[5]d109local shellCompDirectiveFilterFileExt=%[6]d110local shellCompDirectiveFilterDirs=%[7]d111local shellCompDirectiveKeepOrder=%[8]d112113local lastParam lastChar flagPrefix requestComp out directive comp lastComp noSpace keepOrder114local -a completions115116__%[1]s_debug "\n========= starting completion logic =========="117__%[1]s_debug "CURRENT: ${CURRENT}, words[*]: ${words[*]}"118119# The user could have moved the cursor backwards on the command-line.120# We need to trigger completion from the $CURRENT location, so we need121# to truncate the command-line ($words) up to the $CURRENT location.122# (We cannot use $CURSOR as its value does not work when a command is an alias.)123words=("${=words[1,CURRENT]}")124__%[1]s_debug "Truncated words[*]: ${words[*]},"125126lastParam=${words[-1]}127lastChar=${lastParam[-1]}128__%[1]s_debug "lastParam: ${lastParam}, lastChar: ${lastChar}"129130# For zsh, when completing a flag with an = (e.g., %[1]s -n=<TAB>)131# completions must be prefixed with the flag132setopt local_options BASH_REMATCH133if [[ "${lastParam}" =~ '-.*=' ]]; then134# We are dealing with a flag with an =135flagPrefix="-P ${BASH_REMATCH}"136fi137138# Prepare the command to obtain completions139requestComp="${words[1]} %[2]s ${words[2,-1]}"140if [ "${lastChar}" = "" ]; then141# If the last parameter is complete (there is a space following it)142# We add an extra empty parameter so we can indicate this to the go completion code.143__%[1]s_debug "Adding extra empty parameter"144requestComp="${requestComp} \"\""145fi146147__%[1]s_debug "About to call: eval ${requestComp}"148149# Use eval to handle any environment variables and such150out=$(eval ${requestComp} 2>/dev/null)151__%[1]s_debug "completion output: ${out}"152153# Extract the directive integer following a : from the last line154local lastLine155while IFS='\n' read -r line; do156lastLine=${line}157done < <(printf "%%s\n" "${out[@]}")158__%[1]s_debug "last line: ${lastLine}"159160if [ "${lastLine[1]}" = : ]; then161directive=${lastLine[2,-1]}162# Remove the directive including the : and the newline163local suffix164(( suffix=${#lastLine}+2))165out=${out[1,-$suffix]}166else167# There is no directive specified. Leave $out as is.168__%[1]s_debug "No directive found. Setting do default"169directive=0170fi171172__%[1]s_debug "directive: ${directive}"173__%[1]s_debug "completions: ${out}"174__%[1]s_debug "flagPrefix: ${flagPrefix}"175176if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then177__%[1]s_debug "Completion received error. Ignoring completions."178return179fi180181local activeHelpMarker="%[9]s"182local endIndex=${#activeHelpMarker}183local startIndex=$((${#activeHelpMarker}+1))184local hasActiveHelp=0185while IFS='\n' read -r comp; do186# Check if this is an activeHelp statement (i.e., prefixed with $activeHelpMarker)187if [ "${comp[1,$endIndex]}" = "$activeHelpMarker" ];then188__%[1]s_debug "ActiveHelp found: $comp"189comp="${comp[$startIndex,-1]}"190if [ -n "$comp" ]; then191compadd -x "${comp}"192__%[1]s_debug "ActiveHelp will need delimiter"193hasActiveHelp=1194fi195196continue197fi198199if [ -n "$comp" ]; then200# If requested, completions are returned with a description.201# The description is preceded by a TAB character.202# For zsh's _describe, we need to use a : instead of a TAB.203# We first need to escape any : as part of the completion itself.204comp=${comp//:/\\:}205206local tab="$(printf '\t')"207comp=${comp//$tab/:}208209__%[1]s_debug "Adding completion: ${comp}"210completions+=${comp}211lastComp=$comp212fi213done < <(printf "%%s\n" "${out[@]}")214215# Add a delimiter after the activeHelp statements, but only if:216# - there are completions following the activeHelp statements, or217# - file completion will be performed (so there will be choices after the activeHelp)218if [ $hasActiveHelp -eq 1 ]; then219if [ ${#completions} -ne 0 ] || [ $((directive & shellCompDirectiveNoFileComp)) -eq 0 ]; then220__%[1]s_debug "Adding activeHelp delimiter"221compadd -x "--"222hasActiveHelp=0223fi224fi225226if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then227__%[1]s_debug "Activating nospace."228noSpace="-S ''"229fi230231if [ $((directive & shellCompDirectiveKeepOrder)) -ne 0 ]; then232__%[1]s_debug "Activating keep order."233keepOrder="-V"234fi235236if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then237# File extension filtering238local filteringCmd239filteringCmd='_files'240for filter in ${completions[@]}; do241if [ ${filter[1]} != '*' ]; then242# zsh requires a glob pattern to do file filtering243filter="\*.$filter"244fi245filteringCmd+=" -g $filter"246done247filteringCmd+=" ${flagPrefix}"248249__%[1]s_debug "File filtering command: $filteringCmd"250_arguments '*:filename:'"$filteringCmd"251elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then252# File completion for directories only253local subdir254subdir="${completions[1]}"255if [ -n "$subdir" ]; then256__%[1]s_debug "Listing directories in $subdir"257pushd "${subdir}" >/dev/null 2>&1258else259__%[1]s_debug "Listing directories in ."260fi261262local result263_arguments '*:dirname:_files -/'" ${flagPrefix}"264result=$?265if [ -n "$subdir" ]; then266popd >/dev/null 2>&1267fi268return $result269else270__%[1]s_debug "Calling _describe"271if eval _describe $keepOrder "completions" completions $flagPrefix $noSpace; then272__%[1]s_debug "_describe found some completions"273274# Return the success of having called _describe275return 0276else277__%[1]s_debug "_describe did not find completions."278__%[1]s_debug "Checking if we should do file completion."279if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then280__%[1]s_debug "deactivating file completion"281282# We must return an error code here to let zsh know that there were no283# completions found by _describe; this is what will trigger other284# matching algorithms to attempt to find completions.285# For example zsh can match letters in the middle of words.286return 1287else288# Perform file completion289__%[1]s_debug "Activating file completion"290291# We must return the result of this command, so it must be the292# last command, or else we must store its result to return it.293_arguments '*:filename:_files'" ${flagPrefix}"294fi295fi296fi297}298299# don't run the completion function when being source-ed or eval-ed300if [ "$funcstack[1]" = "_%[1]s" ]; then301_%[1]s302fi303`, name, compCmd,304ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,305ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder,306activeHelpMarker))307}308309310