composer and command line completion
- Transfer
- Tutorial
As I add my scripts to files more and more composer.json
, it would be useful to have autocomplete for the command composer
in bash
. My question on Twitter did not give an immediate solution, and since I was already doing something similar for Phing
, I rolled up my sleeves and wrote my decision.
We start by creating a new bash completion file with a name composer
in the directory bash_completion.d
(the file needs execute rights). This directory is usually located at /etc/bash_completion.d/
, but on OS X using Homebrew , it is at /usr/local/etc/bash_completion.d/
(assuming you have already installed it brew install bash-complete
).
Here is the file:
# Store this file in /etc/bash_completion.d/composer
_composer_scripts() {
local cur prev
_get_comp_words_by_ref -n : cur
COMPREPLY=()
prev="${COMP_WORDS[COMP_CWORD-1]}"
#
# Complete the arguments to some of the commands.
#
if [ "$prev" != "composer" ] ; then
local opts=$(composer $prev -h --no-ansi | tr -cs '[=-=][:alpha:]_' '[\n*]' | grep '^-')
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
fi
if [[ "$cur" == -* ]]; then
COMPREPLY=( $( compgen -W '-h -q -v -V -n -d \
--help --quiet --verbose --version --ansi --no-ansi \
--no-interaction --profile --working-dir' -- "$cur" ) )
else
local scripts=$(composer --no-ansi 2> /dev/null | awk '/^ +[a-z]+/ { print $1 }')
COMPREPLY=( $(compgen -W "${scripts}" -- ${cur}) )
fi
__ltrim_colon_completions "$cur"
return 0
}
complete -F _composer_scripts composer
(Note that it __ltrim_colon_completions
is only supported in recent versions bash-complete
, so you may need to remove this line.)
To get a list of commands for composer, we create a list of words for the -W option for compgen
, by running composer --no-ansi
, and then using AWK we delete everything that is not a command. We also create a separate flag argument list when the user presses the Tab key after the hyphen is entered.
When launched composer {cmd} -h --no-ansi
, we automatically fill in the flags for any subcommand and, using tr
and grep
, limit the list to words starting with a hyphen.
Now by pressing Tab after composer, bash will automatically complete both the built-in composer commands and user scripts!
As you can see in this example, in addition to built-in commands, such as dump-autoload
and show
, my own scripts are displayed, including apiary-fetch
others.
This is very useful when memory fails me!