composer and command line completion

Original author: Rob Allen
  • Transfer
  • Tutorial

As I add my scripts to files more and more composer.json, it would be useful to have autocomplete for the command composerin 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 composerin 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
    #  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
    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" ) )
        local scripts=$(composer --no-ansi 2> /dev/null |  awk '/^ +[a-z]+/ { print $1 }')
        COMPREPLY=( $(compgen -W "${scripts}" -- ${cur}) )
    __ltrim_colon_completions "$cur"
    return 0
complete -F _composer_scripts composer

(Note that it __ltrim_colon_completionsis 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 trand 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-autoloadand show, my own scripts are displayed, including apiary-fetchothers.

This is very useful when memory fails me!

Also popular now: