2

I try to understand this bash completion function ? (for cloudfoundry cli)

I read https://debian-administration.org/article/317/An_introduction_to_bash_completion_part_2 and also the bash ref guide at https://www.gnu.org/software/bash/manual/bash.html#Programmable-Completion but can figure out how the code in the script for cloudfoundry works: (copy from /usr/local/etc/bash_completion.d/cf)

      _cf() {
          # All arguments except the first one
          args=("${COMP_WORDS[@]:1:$COMP_CWORD}")
          # Only split on newlines
          local IFS=$'
'
          # Call completion (note that the first element of COMP_WORDS is
          # the executable itself)
          COMPREPLY=($(GO_FLAGS_COMPLETION=1 ${COMP_WORDS[0]} "${args[@]}"))
          return 0
      }
      complete -F _cf cf

In have installed some plugins to cf and like to see them in completion. (e.g. github.com cf-targets-plugin)

Any hints for me ? How is the word list generated ? (I assume its in COMP_WORDS[])

This so different from the samples like

COMPREPLY=( $(compgen -W "$worldist -- "$cur_opt") )

Nuri Tasdemir
  • 9,720
  • 3
  • 42
  • 67
mhoff
  • 601
  • 8
  • 13
  • The literal newline after `$'` is kind of weird, the only purpose of the leading dollar sign is so you can use escape codes like `$'\n'` instead of a literal newline. – tripleee Apr 06 '17 at 12:42
  • Apparently this is the source: https://github.com/cloudfoundry/cli/blob/master/ci/installers/completion/cf – tripleee Apr 06 '17 at 12:49
  • @tripleee - thanks for to this git - yes the newline is a bit weird. Maybe the way homebrew installs this completion (some cat ....) I upgraded to the newest git version 6.26.0 but the local file "bash_completion.d/cf-cli" still looks like this – mhoff Apr 07 '17 at 15:57

1 Answers1

2

This is slightly speculative, because I have not actually installed this software.

Apparently the program itself will generate a list of available completions when it is invoked with the environment variable GO_FLAGS_COMPLETION set to 1. So the code simply sets that variable and calls the program with the current arguments, and expects to receive a list of completions back.

This is a fairly elegant solution to context-based completions -- the program itself knows what parameters it can accept with the current arguments, and Bash doesn't have to duplicate that information or parse the same arguments.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • cool that was a good guess: `GO_FLAGS_COMPLETION=1 cf spac` show a list start with spac.... – mhoff Apr 07 '17 at 15:59