Skip to content

Commit

Permalink
Add completion for fish shell
Browse files Browse the repository at this point in the history
Fix #2337
  • Loading branch information
nono committed Apr 16, 2020
1 parent 719e1b2 commit 98546d5
Show file tree
Hide file tree
Showing 5 changed files with 218 additions and 13 deletions.
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ cli:
@cozy-stack doc markdown docs/cli
@cozy-stack completion bash > scripts/completion/cozy-stack.bash
@cozy-stack completion zsh > scripts/completion/cozy-stack.zsh
@cozy-stack completion fish > scripts/completion/cozy-stack.fish
.PHONY: cli

## unit-tests: run the tests
Expand Down
16 changes: 9 additions & 7 deletions cmd/completion.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,12 @@ var completionCmd = &cobra.Command{
Use: "completion <shell>",
Short: "Output shell completion code for the specified shell",
Long: `
Output shell completion code for the specified shell (bash or zsh).
The shell code must be evalutated to provide interactive
completion of cozy-stack commands. This can be done by sourcing it from
the .bash_profile.
Output shell completion code for the specified shell (bash, zsh, or fish). The
shell code must be evalutated to provide interactive completion of cozy-stack
commands. This can be done by sourcing it from the .bash_profile.
Note: this requires the bash-completion framework, which is not installed
by default on Mac. This can be installed by using homebrew:
Note: this requires the bash-completion framework, which is not installed by
default on Mac. This can be installed by using homebrew:
$ brew install bash-completion
Expand All @@ -26,7 +25,7 @@ following line to the .bash_profile
$ source $(brew --prefix)/etc/bash_completion`,
Example: `# cozy-stack completion bash > /etc/bash_completion.d/cozy-stack`,
ValidArgs: []string{"bash", "zsh"},
ValidArgs: []string{"bash", "zsh", "fish"},
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return cmd.Usage()
Expand All @@ -38,6 +37,9 @@ following line to the .bash_profile
// Zsh completion support is still basic
// https://github.com/spf13/cobra/issues/107
return RootCmd.GenZshCompletion(os.Stdout)
case "fish":
includeDescription := true
return RootCmd.GenFishCompletion(os.Stdout, includeDescription)
}
return errors.New("Unsupported shell")
},
Expand Down
11 changes: 5 additions & 6 deletions docs/cli/cozy-stack_completion.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,12 @@ Output shell completion code for the specified shell
### Synopsis


Output shell completion code for the specified shell (bash or zsh).
The shell code must be evalutated to provide interactive
completion of cozy-stack commands. This can be done by sourcing it from
the .bash_profile.
Output shell completion code for the specified shell (bash, zsh, or fish). The
shell code must be evalutated to provide interactive completion of cozy-stack
commands. This can be done by sourcing it from the .bash_profile.

Note: this requires the bash-completion framework, which is not installed
by default on Mac. This can be installed by using homebrew:
Note: this requires the bash-completion framework, which is not installed by
default on Mac. This can be installed by using homebrew:

$ brew install bash-completion

Expand Down
66 changes: 66 additions & 0 deletions scripts/completion/cozy-stack.bash
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,67 @@ __cozy-stack_contains_word()
return 1
}

__cozy-stack_handle_go_custom_completion()
{
__cozy-stack_debug "${FUNCNAME[0]}: cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}"

local out requestComp lastParam lastChar comp directive args

# Prepare the command to request completions for the program.
# Calling ${words[0]} instead of directly cozy-stack allows to handle aliases
args=("${words[@]:1}")
requestComp="${words[0]} __completeNoDesc ${args[*]}"

lastParam=${words[$((${#words[@]}-1))]}
lastChar=${lastParam:$((${#lastParam}-1)):1}
__cozy-stack_debug "${FUNCNAME[0]}: lastParam ${lastParam}, lastChar ${lastChar}"

if [ -z "${cur}" ] && [ "${lastChar}" != "=" ]; then
# If the last parameter is complete (there is a space following it)
# We add an extra empty parameter so we can indicate this to the go method.
__cozy-stack_debug "${FUNCNAME[0]}: Adding extra empty parameter"
requestComp="${requestComp} \"\""
fi

__cozy-stack_debug "${FUNCNAME[0]}: calling ${requestComp}"
# Use eval to handle any environment variables and such
out=$(eval "${requestComp}" 2>/dev/null)

# Extract the directive integer at the very end of the output following a colon (:)
directive=${out##*:}
# Remove the directive
out=${out%:*}
if [ "${directive}" = "${out}" ]; then
# There is not directive specified
directive=0
fi
__cozy-stack_debug "${FUNCNAME[0]}: the completion directive is: ${directive}"
__cozy-stack_debug "${FUNCNAME[0]}: the completions are: ${out[*]}"

if [ $((directive & 1)) -ne 0 ]; then
# Error code. No completion.
__cozy-stack_debug "${FUNCNAME[0]}: received error from custom completion go code"
return
else
if [ $((directive & 2)) -ne 0 ]; then
if [[ $(type -t compopt) = "builtin" ]]; then
__cozy-stack_debug "${FUNCNAME[0]}: activating no space"
compopt -o nospace
fi
fi
if [ $((directive & 4)) -ne 0 ]; then
if [[ $(type -t compopt) = "builtin" ]]; then
__cozy-stack_debug "${FUNCNAME[0]}: activating no file completion"
compopt +o default
fi
fi

while IFS='' read -r comp; do
COMPREPLY+=("$comp")
done < <(compgen -W "${out[*]}" -- "$cur")
fi
}

__cozy-stack_handle_reply()
{
__cozy-stack_debug "${FUNCNAME[0]}"
Expand Down Expand Up @@ -99,6 +160,10 @@ __cozy-stack_handle_reply()
completions=("${commands[@]}")
if [[ ${#must_have_one_noun[@]} -ne 0 ]]; then
completions=("${must_have_one_noun[@]}")
elif [[ -n "${has_completion_function}" ]]; then
# if a go completion function is provided, defer to that function
completions=()
__cozy-stack_handle_go_custom_completion
fi
if [[ ${#must_have_one_flag[@]} -ne 0 ]]; then
completions+=("${must_have_one_flag[@]}")
Expand Down Expand Up @@ -3901,6 +3966,7 @@ __start_cozy-stack()
local commands=("cozy-stack")
local must_have_one_flag=()
local must_have_one_noun=()
local has_completion_function
local last_command
local nouns=()

Expand Down
137 changes: 137 additions & 0 deletions scripts/completion/cozy-stack.fish
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
# fish completion for cozy-stack -*- shell-script -*-

function __cozy-stack_debug
set file "$BASH_COMP_DEBUG_FILE"
if test -n "$file"
echo "$argv" >> $file
end
end

function __cozy-stack_perform_completion
__cozy-stack_debug "Starting __cozy-stack_perform_completion with: $argv"

set args (string split -- " " "$argv")
set lastArg "$args[-1]"

__cozy-stack_debug "args: $args"
__cozy-stack_debug "last arg: $lastArg"

set emptyArg ""
if test -z "$lastArg"
__cozy-stack_debug "Setting emptyArg"
set emptyArg \"\"
end
__cozy-stack_debug "emptyArg: $emptyArg"

set requestComp "$args[1] __complete $args[2..-1] $emptyArg"
__cozy-stack_debug "Calling $requestComp"

set results (eval $requestComp 2> /dev/null)
set comps $results[1..-2]
set directiveLine $results[-1]

# For Fish, when completing a flag with an = (e.g., <program> -n=<TAB>)
# completions must be prefixed with the flag
set flagPrefix (string match -r -- '-.*=' "$lastArg")

__cozy-stack_debug "Comps: $comps"
__cozy-stack_debug "DirectiveLine: $directiveLine"
__cozy-stack_debug "flagPrefix: $flagPrefix"

for comp in $comps
printf "%s%s\n" "$flagPrefix" "$comp"
end

printf "%s\n" "$directiveLine"
end

# This function does three things:
# 1- Obtain the completions and store them in the global __cozy-stack_comp_results
# 2- Set the __cozy-stack_comp_do_file_comp flag if file completion should be performed
# and unset it otherwise
# 3- Return true if the completion results are not empty
function __cozy-stack_prepare_completions
# Start fresh
set --erase __cozy-stack_comp_do_file_comp
set --erase __cozy-stack_comp_results

# Check if the command-line is already provided. This is useful for testing.
if not set --query __cozy-stack_comp_commandLine
set __cozy-stack_comp_commandLine (commandline)
end
__cozy-stack_debug "commandLine is: $__cozy-stack_comp_commandLine"

set results (__cozy-stack_perform_completion "$__cozy-stack_comp_commandLine")
set --erase __cozy-stack_comp_commandLine
__cozy-stack_debug "Completion results: $results"

if test -z "$results"
__cozy-stack_debug "No completion, probably due to a failure"
# Might as well do file completion, in case it helps
set --global __cozy-stack_comp_do_file_comp 1
return 0
end

set directive (string sub --start 2 $results[-1])
set --global __cozy-stack_comp_results $results[1..-2]

__cozy-stack_debug "Completions are: $__cozy-stack_comp_results"
__cozy-stack_debug "Directive is: $directive"

if test -z "$directive"
set directive 0
end

set compErr (math (math --scale 0 $directive / 1) % 2)
if test $compErr -eq 1
__cozy-stack_debug "Received error directive: aborting."
# Might as well do file completion, in case it helps
set --global __cozy-stack_comp_do_file_comp 1
return 0
end

set nospace (math (math --scale 0 $directive / 2) % 2)
set nofiles (math (math --scale 0 $directive / 4) % 2)

__cozy-stack_debug "nospace: $nospace, nofiles: $nofiles"

# Important not to quote the variable for count to work
set numComps (count $__cozy-stack_comp_results)
__cozy-stack_debug "numComps: $numComps"

if test $numComps -eq 1; and test $nospace -ne 0
# To support the "nospace" directive we trick the shell
# by outputting an extra, longer completion.
__cozy-stack_debug "Adding second completion to perform nospace directive"
set --append __cozy-stack_comp_results $__cozy-stack_comp_results[1].
end

if test $numComps -eq 0; and test $nofiles -eq 0
__cozy-stack_debug "Requesting file completion"
set --global __cozy-stack_comp_do_file_comp 1
end

# If we don't want file completion, we must return true even if there
# are no completions found. This is because fish will perform the last
# completion command, even if its condition is false, if no other
# completion command was triggered
return (not set --query __cozy-stack_comp_do_file_comp)
end

# Remove any pre-existing completions for the program since we will be handling all of them
# TODO this cleanup is not sufficient. Fish completions are only loaded once the user triggers
# them, so the below deletion will not work as it is run too early. What else can we do?
complete -c cozy-stack -e

# The order in which the below two lines are defined is very important so that __cozy-stack_prepare_completions
# is called first. It is __cozy-stack_prepare_completions that sets up the __cozy-stack_comp_do_file_comp variable.
#
# This completion will be run second as complete commands are added FILO.
# It triggers file completion choices when __cozy-stack_comp_do_file_comp is set.
complete -c cozy-stack -n 'set --query __cozy-stack_comp_do_file_comp'

# This completion will be run first as complete commands are added FILO.
# The call to __cozy-stack_prepare_completions will setup both __cozy-stack_comp_results abd __cozy-stack_comp_do_file_comp.
# It provides the program's completion choices.
complete -c cozy-stack -n '__cozy-stack_prepare_completions' -f -a '$__cozy-stack_comp_results'

0 comments on commit 98546d5

Please sign in to comment.