Skip to content
Myr

bash.go

This file

Path

completion/bash.go

668 lines · 21.4 KiB · Go

Last changed by

fix: lint issues (#909)Carlos Alexandro Beckerbefore adoption817c4bd

History of this file

Take it

1// Package completion provides a bash completion generator for Kong2// applications.3package completion45import (6	"bytes"7	"fmt"8	"io"9	"sort"10	"strings"1112	"github.com/alecthomas/kong"13)1415// Bash is a bash completion generator.16type Bash struct{}1718// Run generates bash completion script.19func (b Bash) Run(ctx *kong.Context) error {20	buf := new(bytes.Buffer)21	writePreamble(buf, ctx.Model.Name)22	b.gen(buf, ctx.Model.Node)23	writePostscript(buf, ctx.Model.Name)2425	_, err := fmt.Fprint(ctx.Stdout, buf.String())26	if err != nil {27		return fmt.Errorf("unable to generate bash completion: %v", err)28	}29	return nil30}3132// ShellCompDirective is a bit map representing the different behaviors the shell33// can be instructed to have once completions have been provided.34type ShellCompDirective int3536const (37	// ShellCompDirectiveError indicates an error occurred and completions should be ignored.38	ShellCompDirectiveError ShellCompDirective = 1 << iota3940	// ShellCompDirectiveNoSpace indicates that the shell should not add a space41	// after the completion even if there is a single completion provided.42	ShellCompDirectiveNoSpace4344	// ShellCompDirectiveNoFileComp indicates that the shell should not provide45	// file completion even when no completion is provided.46	ShellCompDirectiveNoFileComp4748	// ShellCompDirectiveFilterFileExt indicates that the provided completions49	// should be used as file extension filters.50	// For flags, using Command.MarkFlagFilename() and Command.MarkPersistentFlagFilename()51	// is a shortcut to using this directive explicitly.  The BashCompFilenameExt52	// annotation can also be used to obtain the same behavior for flags.53	ShellCompDirectiveFilterFileExt5455	// ShellCompDirectiveFilterDirs indicates that only directory names should56	// be provided in file completion.  To request directory names within another57	// directory, the returned completions should specify the directory within58	// which to search.  The BashCompSubdirsInDir annotation can be used to59	// obtain the same behavior but only for flags.60	ShellCompDirectiveFilterDirs6162	// ===========================================================================63	//64	// All directives using iota should be above this one.65	// For internal use.66	shellCompDirectiveMaxValue //nolint:deadcode,unused,varcheck6768	// ShellCompDirectiveDefault indicates to let the shell perform its default69	// behavior after completions have been provided.70	// This one must be last to avoid messing up the iota count.71	ShellCompDirectiveDefault ShellCompDirective = 072)7374// Annotations for Bash completion.75const (76	// ShellCompNoDescRequestCmd is the name of the hidden command that is used to request77	// completion results without their description.  It is used by the shell completion scripts.78	ShellCompNoDescRequestCmd = "completion completeNoDesc"79	BashCompFilenameExt       = "kong_annotation_bash_completion_filename_extensions"80	BashCompCustom            = "kong_annotation_bash_completion_custom"81	BashCompOneRequiredFlag   = "kong_annotation_bash_completion_one_required_flag"82	BashCompSubdirsInDir      = "kong_annotation_bash_completion_subdirs_in_dir"8384	activeHelpEnvVarSuffix = "_ACTIVE_HELP"85)8687// activeHelpEnvVar returns the name of the program-specific ActiveHelp environment88// variable.  It has the format <PROGRAM>_ACTIVE_HELP where <PROGRAM> is the name of the89// root command in upper case, with all - replaced by _.90func activeHelpEnvVar(name string) string {91	// This format should not be changed: users will be using it explicitly.92	activeHelpEnvVar := strings.ToUpper(fmt.Sprintf("%s%s", name, activeHelpEnvVarSuffix))93	return strings.ReplaceAll(activeHelpEnvVar, "-", "_")94}9596func writePreamble(buf io.StringWriter, name string) {97	writeString(buf, fmt.Sprintf("# bash completion for %-36s -*- shell-script -*-\n", name))98	writeString(buf, fmt.Sprintf(`99__%[1]s_debug()100{101    if [[ -n ${BASH_COMP_DEBUG_FILE:-} ]]; then102        echo "$*" >> "${BASH_COMP_DEBUG_FILE}"103    fi104}105106# Homebrew on Macs have version 1.3 of bash-completion which doesn't include107# _init_completion. This is a very minimal version of that function.108__%[1]s_init_completion()109{110    COMPREPLY=()111    _get_comp_words_by_ref "$@" cur prev words cword112}113114__%[1]s_index_of_word()115{116    local w word=$1117    shift118    index=0119    for w in "$@"; do120        [[ $w = "$word" ]] && return121        index=$((index+1))122    done123    index=-1124}125126__%[1]s_contains_word()127{128    local w word=$1; shift129    for w in "$@"; do130        [[ $w = "$word" ]] && return131    done132    return 1133}134135__%[1]s_handle_go_custom_completion()136{137    __%[1]s_debug "${FUNCNAME[0]}: cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}"138139    local shellCompDirectiveError=%[3]d140    local shellCompDirectiveNoSpace=%[4]d141    local shellCompDirectiveNoFileComp=%[5]d142    local shellCompDirectiveFilterFileExt=%[6]d143    local shellCompDirectiveFilterDirs=%[7]d144145    local out requestComp lastParam lastChar comp directive args146147    # Prepare the command to request completions for the program.148    # Calling ${words[0]} instead of directly %[1]s allows to handle aliases149    args=("${words[@]:1}")150    # Disable ActiveHelp which is not supported for bash completion v1151    requestComp="%[8]s=0 ${words[0]} %[2]s ${args[*]}"152153    lastParam=${words[$((${#words[@]}-1))]}154    lastChar=${lastParam:$((${#lastParam}-1)):1}155    __%[1]s_debug "${FUNCNAME[0]}: lastParam ${lastParam}, lastChar ${lastChar}"156157    if [ -z "${cur}" ] && [ "${lastChar}" != "=" ]; then158        # If the last parameter is complete (there is a space following it)159        # We add an extra empty parameter so we can indicate this to the go method.160        __%[1]s_debug "${FUNCNAME[0]}: Adding extra empty parameter"161        requestComp="${requestComp} \"\""162    fi163164    __%[1]s_debug "${FUNCNAME[0]}: calling ${requestComp}"165    # Use eval to handle any environment variables and such166    out=$(eval "${requestComp}" 2>/dev/null)167168    # Extract the directive integer at the very end of the output following a colon (:)169    directive=${out##*:}170    # Remove the directive171    out=${out%%:*}172    if [ "${directive}" = "${out}" ]; then173        # There is not directive specified174        directive=0175    fi176    __%[1]s_debug "${FUNCNAME[0]}: the completion directive is: ${directive}"177    __%[1]s_debug "${FUNCNAME[0]}: the completions are: ${out}"178179    if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then180        # Error code.  No completion.181        __%[1]s_debug "${FUNCNAME[0]}: received error from custom completion go code"182        return183    else184        if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then185            if [[ $(type -t compopt) = "builtin" ]]; then186                __%[1]s_debug "${FUNCNAME[0]}: activating no space"187                compopt -o nospace188            fi189        fi190        if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then191            if [[ $(type -t compopt) = "builtin" ]]; then192                __%[1]s_debug "${FUNCNAME[0]}: activating no file completion"193                compopt +o default194            fi195        fi196    fi197198    if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then199        # File extension filtering200        local fullFilter filter filteringCmd201        # Do not use quotes around the $out variable or else newline202        # characters will be kept.203        for filter in ${out}; do204            fullFilter+="$filter|"205        done206207        filteringCmd="_filedir $fullFilter"208        __%[1]s_debug "File filtering command: $filteringCmd"209        $filteringCmd210    elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then211        # File completion for directories only212        local subdir213        # Use printf to strip any trailing newline214        subdir=$(printf "%%s" "${out}")215        if [ -n "$subdir" ]; then216            __%[1]s_debug "Listing directories in $subdir"217            __%[1]s_handle_subdirs_in_dir_flag "$subdir"218        else219            __%[1]s_debug "Listing directories in ."220            _filedir -d221        fi222    else223        while IFS='' read -r comp; do224            COMPREPLY+=("$comp")225        done < <(compgen -W "${out}" -- "$cur")226    fi227}228229__%[1]s_handle_reply()230{231    __%[1]s_debug "${FUNCNAME[0]}"232    local comp233    case $cur in234        -*)235            if [[ $(type -t compopt) = "builtin" ]]; then236                compopt -o nospace237            fi238            local allflags239            if [ ${#must_have_one_flag[@]} -ne 0 ]; then240                allflags=("${must_have_one_flag[@]}")241            else242                allflags=("${flags[*]} ${two_word_flags[*]}")243            fi244            while IFS='' read -r comp; do245                COMPREPLY+=("$comp")246            done < <(compgen -W "${allflags[*]}" -- "$cur")247            if [[ $(type -t compopt) = "builtin" ]]; then248                [[ "${COMPREPLY[0]}" == *= ]] || compopt +o nospace249            fi250251            # complete after --flag=abc252            if [[ $cur == *=* ]]; then253                if [[ $(type -t compopt) = "builtin" ]]; then254                    compopt +o nospace255                fi256257                local index flag258                flag="${cur%%=*}"259                __%[1]s_index_of_word "${flag}" "${flags_with_completion[@]}"260                COMPREPLY=()261                if [[ ${index} -ge 0 ]]; then262                    PREFIX=""263                    cur="${cur#*=}"264                    ${flags_completion[${index}]}265                    if [ -n "${ZSH_VERSION:-}" ]; then266                        # zsh completion needs --flag= prefix267                        eval "COMPREPLY=( \"\${COMPREPLY[@]/#/${flag}=}\" )"268                    fi269                fi270            fi271272            if [[ -z "${flag_parsing_disabled}" ]]; then273                # If flag parsing is enabled, we have completed the flags and can return.274                # If flag parsing is disabled, we may not know all (or any) of the flags, so we fallthrough275                # to possibly call handle_go_custom_completion.276                return 0;277            fi278            ;;279    esac280281    # check if we are handling a flag with special work handling282    local index283    __%[1]s_index_of_word "${prev}" "${flags_with_completion[@]}"284    if [[ ${index} -ge 0 ]]; then285        ${flags_completion[${index}]}286        return287    fi288289    # we are parsing a flag and don't have a special handler, no completion290    if [[ ${cur} != "${words[cword]}" ]]; then291        return292    fi293294    local completions295    completions=("${commands[@]}")296    if [[ ${#must_have_one_noun[@]} -ne 0 ]]; then297        completions+=("${must_have_one_noun[@]}")298    elif [[ -n "${has_completion_function}" ]]; then299        # if a go completion function is provided, defer to that function300        __%[1]s_handle_go_custom_completion301    fi302    if [[ ${#must_have_one_flag[@]} -ne 0 ]]; then303        completions+=("${must_have_one_flag[@]}")304    fi305    while IFS='' read -r comp; do306        COMPREPLY+=("$comp")307    done < <(compgen -W "${completions[*]}" -- "$cur")308309    if [[ ${#COMPREPLY[@]} -eq 0 && ${#noun_aliases[@]} -gt 0 && ${#must_have_one_noun[@]} -ne 0 ]]; then310        while IFS='' read -r comp; do311            COMPREPLY+=("$comp")312        done < <(compgen -W "${noun_aliases[*]}" -- "$cur")313    fi314315    if [[ ${#COMPREPLY[@]} -eq 0 ]]; then316        if declare -F __%[1]s_custom_func >/dev/null; then317            # try command name qualified custom func318            __%[1]s_custom_func319        else320            # otherwise fall back to unqualified for compatibility321            declare -F __custom_func >/dev/null && __custom_func322        fi323    fi324325    # available in bash-completion >= 2, not always present on macOS326    if declare -F __ltrim_colon_completions >/dev/null; then327        __ltrim_colon_completions "$cur"328    fi329330    # If there is only 1 completion and it is a flag with an = it will be completed331    # but we don't want a space after the =332    if [[ "${#COMPREPLY[@]}" -eq "1" ]] && [[ $(type -t compopt) = "builtin" ]] && [[ "${COMPREPLY[0]}" == --*= ]]; then333       compopt -o nospace334    fi335}336337# The arguments should be in the form "ext1|ext2|extn"338__%[1]s_handle_filename_extension_flag()339{340    local ext="$1"341    _filedir "@(${ext})"342}343344__%[1]s_handle_subdirs_in_dir_flag()345{346    local dir="$1"347    pushd "${dir}" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return348}349350__%[1]s_handle_flag()351{352    __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"353354    # if a command required a flag, and we found it, unset must_have_one_flag()355    local flagname=${words[c]}356    local flagvalue=""357    # if the word contained an =358    if [[ ${words[c]} == *"="* ]]; then359        flagvalue=${flagname#*=} # take in as flagvalue after the =360        flagname=${flagname%%=*} # strip everything after the =361        flagname="${flagname}=" # but put the = back362    fi363    __%[1]s_debug "${FUNCNAME[0]}: looking for ${flagname}"364    if __%[1]s_contains_word "${flagname}" "${must_have_one_flag[@]}"; then365        must_have_one_flag=()366    fi367368    # if you set a flag which only applies to this command, don't show subcommands369    if __%[1]s_contains_word "${flagname}" "${local_nonpersistent_flags[@]}"; then370      commands=()371    fi372373    # keep flag value with flagname as flaghash374    # flaghash variable is an associative array which is only supported in bash > 3.375    if [[ -z "${BASH_VERSION:-}" || "${BASH_VERSINFO[0]:-}" -gt 3 ]]; then376        if [ -n "${flagvalue}" ] ; then377            flaghash[${flagname}]=${flagvalue}378        elif [ -n "${words[ $((c+1)) ]}" ] ; then379            flaghash[${flagname}]=${words[ $((c+1)) ]}380        else381            flaghash[${flagname}]="true" # pad "true" for bool flag382        fi383    fi384385    # skip the argument to a two word flag386    if [[ ${words[c]} != *"="* ]] && __%[1]s_contains_word "${words[c]}" "${two_word_flags[@]}"; then387        __%[1]s_debug "${FUNCNAME[0]}: found a flag ${words[c]}, skip the next argument"388        c=$((c+1))389        # if we are looking for a flags value, don't show commands390        if [[ $c -eq $cword ]]; then391            commands=()392        fi393    fi394395    c=$((c+1))396397}398399__%[1]s_handle_noun()400{401    __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"402403    if __%[1]s_contains_word "${words[c]}" "${must_have_one_noun[@]}"; then404        must_have_one_noun=()405    elif __%[1]s_contains_word "${words[c]}" "${noun_aliases[@]}"; then406        must_have_one_noun=()407    fi408409    nouns+=("${words[c]}")410    c=$((c+1))411}412413__%[1]s_handle_command()414{415    __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"416417    local next_command418    if [[ -n ${last_command} ]]; then419        next_command="_${last_command}_${words[c]//:/__}"420    else421        if [[ $c -eq 0 ]]; then422            next_command="_%[1]s_root_command"423        else424            next_command="_${words[c]//:/__}"425        fi426    fi427    c=$((c+1))428    __%[1]s_debug "${FUNCNAME[0]}: looking for ${next_command}"429    declare -F "$next_command" >/dev/null && $next_command430}431432__%[1]s_handle_word()433{434    if [[ $c -ge $cword ]]; then435        __%[1]s_handle_reply436        return437    fi438    __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"439    if [[ "${words[c]}" == -* ]]; then440        __%[1]s_handle_flag441    elif __%[1]s_contains_word "${words[c]}" "${commands[@]}"; then442        __%[1]s_handle_command443    elif [[ $c -eq 0 ]]; then444        __%[1]s_handle_command445    elif __%[1]s_contains_word "${words[c]}" "${command_aliases[@]}"; then446        # aliashash variable is an associative array which is only supported in bash > 3.447        if [[ -z "${BASH_VERSION:-}" || "${BASH_VERSINFO[0]:-}" -gt 3 ]]; then448            words[c]=${aliashash[${words[c]}]}449            __%[1]s_handle_command450        else451            __%[1]s_handle_noun452        fi453    else454        __%[1]s_handle_noun455    fi456    __%[1]s_handle_word457}458459`, name, ShellCompNoDescRequestCmd,460		ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,461		ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name)))462}463464func writePostscript(buf io.StringWriter, name string) {465	name = strings.ReplaceAll(name, ":", "__")466	writeString(buf, fmt.Sprintf("__start_%s()\n", name))467	writeString(buf, fmt.Sprintf(`{468    local cur prev words cword split469    declare -A flaghash 2>/dev/null || :470    declare -A aliashash 2>/dev/null || :471    if declare -F _init_completion >/dev/null 2>&1; then472        _init_completion -s || return473    else474        __%[1]s_init_completion -n "=" || return475    fi476477    local c=0478    local flag_parsing_disabled=479    local flags=()480    local two_word_flags=()481    local local_nonpersistent_flags=()482    local flags_with_completion=()483    local flags_completion=()484    local commands=("%[1]s")485    local command_aliases=()486    local must_have_one_flag=()487    local must_have_one_noun=()488    local has_completion_function=""489    local last_command=""490    local nouns=()491    local noun_aliases=()492493    __%[1]s_handle_word494}495496`, name))497	writeString(buf, fmt.Sprintf(`if [[ $(type -t compopt) = "builtin" ]]; then498    complete -o default -F __start_%s %s499else500    complete -o default -o nospace -F __start_%s %s501fi502503`, name, name, name, name))504	writeString(buf, "# ex: ts=4 sw=4 et filetype=sh\n")505}506507func writeCommands(buf io.StringWriter, cmd *kong.Node) {508	writeString(buf, "    commands=()\n")509	for _, c := range cmd.Children {510		if c == nil || c.Hidden {511			continue512		}513		writeString(buf, fmt.Sprintf("    commands+=(%q)\n", c.Name))514		writeCmdAliases(buf, c)515	}516	writeString(buf, "\n")517}518519func writeFlagHandler(buf io.StringWriter, name string, annotations map[string][]string, cmd *kong.Node) {520	for key, value := range annotations {521		switch key {522		case BashCompFilenameExt:523			writeString(buf, fmt.Sprintf("    flags_with_completion+=(%q)\n", name))524525			var ext string526			if len(value) > 0 {527				ext = fmt.Sprintf("__%s_handle_filename_extension_flag ", cmd.Parent.Name) + strings.Join(value, "|")528			} else {529				ext = "_filedir"530			}531			writeString(buf, fmt.Sprintf("    flags_completion+=(%q)\n", ext))532		case BashCompCustom:533			writeString(buf, fmt.Sprintf("    flags_with_completion+=(%q)\n", name))534535			if len(value) > 0 {536				handlers := strings.Join(value, "; ")537				writeString(buf, fmt.Sprintf("    flags_completion+=(%q)\n", handlers))538			} else {539				writeString(buf, "    flags_completion+=(:)\n")540			}541		case BashCompSubdirsInDir:542			writeString(buf, fmt.Sprintf("    flags_with_completion+=(%q)\n", name))543544			var ext string545			if len(value) == 1 {546				ext = fmt.Sprintf("__%s_handle_subdirs_in_dir_flag ", cmd.Parent.Name) + value[0]547			} else {548				ext = "_filedir -d"549			}550			writeString(buf, fmt.Sprintf("    flags_completion+=(%q)\n", ext))551		}552	}553}554555const cbn = "\")\n"556557func writeShortFlag(buf io.StringWriter, flag *kong.Flag, cmd *kong.Node) {558	name := fmt.Sprintf("%c", flag.Short)559	format := "    "560	if len(flag.DefaultValue.String()) == 0 {561		format += "two_word_"562	}563	format += "flags+=(\"-%s" + cbn564	writeString(buf, fmt.Sprintf(format, name))565	writeFlagHandler(buf, "-"+name, map[string][]string{}, cmd)566}567568func writeFlag(buf io.StringWriter, flag *kong.Flag, cmd *kong.Node) {569	name := flag.Name570	format := "    flags+=(\"--%s"571	if len(flag.DefaultValue.String()) == 0 {572		format += "="573	}574	format += cbn575	writeString(buf, fmt.Sprintf(format, name))576	if len(flag.DefaultValue.String()) == 0 {577		format = "    two_word_flags+=(\"--%s" + cbn578		writeString(buf, fmt.Sprintf(format, name))579	}580	writeFlagHandler(buf, "--"+name, map[string][]string{}, cmd)581}582583//nolint:deadcode,unused584func writeLocalNonPersistentFlag(buf io.StringWriter, flag *kong.Flag) {585	name := flag.Name586	format := "    local_nonpersistent_flags+=(\"--%[1]s" + cbn587	if len(flag.DefaultValue.String()) == 0 {588		format += "    local_nonpersistent_flags+=(\"--%[1]s=" + cbn589	}590	writeString(buf, fmt.Sprintf(format, name))591	if flag.Short > 0 {592		writeString(buf, fmt.Sprintf("    local_nonpersistent_flags+=(\"-%c\")\n", flag.Short))593	}594}595596func writeFlags(buf io.StringWriter, cmd *kong.Node) {597	writeString(buf, `    flags=()598    two_word_flags=()599    local_nonpersistent_flags=()600    flags_with_completion=()601    flags_completion=()602603`)604605	for _, flag := range cmd.Flags {606		if nonCompletableFlag(flag) {607			continue608		}609		writeFlag(buf, flag, cmd)610		if flag.Short != 0 {611			writeShortFlag(buf, flag, cmd)612		}613	}614615	writeString(buf, "\n")616}617618func writeCmdAliases(buf io.StringWriter, cmd *kong.Node) {619	if len(cmd.Aliases) == 0 {620		return621	}622623	sort.Strings(cmd.Aliases)624625	writeString(buf, fmt.Sprint(`    if [[ -z "${BASH_VERSION:-}" || "${BASH_VERSINFO[0]:-}" -gt 3 ]]; then`, "\n"))626	for _, value := range cmd.Aliases {627		writeString(buf, fmt.Sprintf("        command_aliases+=(%q)\n", value))628		writeString(buf, fmt.Sprintf("        aliashash[%q]=%q\n", value, cmd.Name))629	}630	writeString(buf, `    fi`)631	writeString(buf, "\n")632}633634func writeArgAliases(buf io.StringWriter, cmd *kong.Node) {635	writeString(buf, "    noun_aliases=()\n")636	sort.Strings(cmd.Aliases)637	for _, value := range cmd.Aliases {638		writeString(buf, fmt.Sprintf("    noun_aliases+=(%q)\n", value))639	}640}641642func (b Bash) gen(buf io.StringWriter, cmd *kong.Node) {643	for _, c := range cmd.Children {644		if c == nil || c.Hidden {645			continue646		}647		b.gen(buf, c)648	}649	commandName := cmd.FullPath()650	commandName = strings.ReplaceAll(commandName, " ", "_")651	commandName = strings.ReplaceAll(commandName, ":", "__")652653	if cmd.Parent == nil {654		writeString(buf, fmt.Sprintf("_%s_root_command()\n{\n", commandName))655	} else {656		writeString(buf, fmt.Sprintf("_%s()\n{\n", commandName))657	}658659	writeString(buf, fmt.Sprintf("    last_command=%q\n", commandName))660	writeString(buf, "\n")661	writeString(buf, "    command_aliases=()\n")662	writeString(buf, "\n")663664	writeCommands(buf, cmd)665	writeFlags(buf, cmd)666	writeArgAliases(buf, cmd)667	writeString(buf, "}\n\n")668}