Laravel artisan 和 Composer 命令在 bash 下自动补全

看到 oh-my-zsh 上有 laravel 的 zsh 版的命令自动补全,就很想要个 bash 版;我也正好想学习下 auto-complete 是怎么做的,就自己写了一个简单的版本,欢迎指点!(不确定网上是否已经有更强大的版本)

效果图

我定了两个 alias

art => php artisan: art 可以在 laravel 项目的根目录或子目录下使用

c => composer: c 只能在有 composer.json 的文件夹下使用

file

Bash 代码


_find_up_for () {
  local dir=`pwd`
  until `test $dir == "/" -o -f "$dir/$1"` ; do
    dir=`dirname $dir`
  done
  echo $dir
}

_laravel5_get_command_list () {
  echo seed # 自定义的一个命令 => composer dump-autoload && php artisan db:seed
  php "$1/artisan" --no-ansi | sed "1,/Available commands/d" | awk '/^ +[a-z]+/ { print $1 }'
}

_composer_get_command_list () {
  composer --no-ansi | sed "1,/Available commands/d" | awk '/^ +[a-z]+/ { print $1 }'
}

_art_completion () {
  local dir=`_find_up_for artisan`

  if [[ -f "$dir/artisan" ]] ; then

    local all cur
    all=`_laravel5_get_command_list $dir`

    # Ref: http://stackoverflow.com/questions/2805412/bash-completion-for-maven-escapes-colon/12495727#12495727
    _get_comp_words_by_ref -n : cur
    COMPREPLY=( $(compgen -W "${all}" -- "${cur}") )
    __ltrim_colon_completions "$cur"

    return 0
  fi
}

art () {
  local dir=`_find_up_for artisan`

  if [[ -f "$dir/artisan" ]] ; then
    if [[ "$#" == "1" &&  "$1" == seed ]] ; then
      composer dump-autoload && php artisan db:seed
    else
      php "$dir/artisan" "$@"
    fi
  fi
}

_composer_completion () {
  if [[ -f "./composer.json" ]] ; then
    local all cur
    all=`_composer_get_command_list $dir`
    cur=${COMP_WORDS[COMP_CWORD]}
    COMPREPLY=( $(compgen -W "${all}" -- "${cur}") )
  fi
}

complete -F _art_completion art
complete -F _composer_completion c

alias c='composer'
本帖已被设为精华帖!
讨论数量: 3
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!