如何使 bash 完成 git 别名的工作?

How to make bash completion work for git alias?

我创建 git 别名 ~/.gitconfig:

[alias]
xxx = !bash -c 'git rebase ...'

但是当我在 shell 中键入 git xxxTABTAB 时,我得到了当前目录中的文件列表而不是 git rebaseTABTAB

可用的分支列表

有没有办法使 git xxx 的 bash 自动完成? 就像通常的别名一样:

__git_complete grb _git_rebase

~/.bashrc

_git_xxx ()
{
  _git_rebase
}

~/.git配置

[alias]
xxx = !bash -c 'git rebase ...'

例如 _git_rebase 看起来像这样(在 git-completion.bash 中找到 - 此文件的路径取决于您的系统,使用 locate, find, 随便找吧):

_git_rebase ()
{
        __git_find_repo_path
        if [ -f "$__git_repo_path"/rebase-merge/interactive ]; then
                __gitcomp "--continue --skip --abort --quit --edit-todo"
                return
        elif [ -d "$__git_repo_path"/rebase-apply ] || \
            [ -d "$__git_repo_path"/rebase-merge ]; then
                __gitcomp "--continue --skip --abort --quit"
                return
        fi
        __git_complete_strategy && return
        case "$cur" in
        --whitespace=*)
                __gitcomp "$__git_whitespacelist" "" "${cur##--whitespace=}"
                return
                ;;
        --*)
                __gitcomp "
                        --onto --merge --strategy --interactive
                        --preserve-merges --stat --no-stat
                        --committer-date-is-author-date --ignore-date
                        --ignore-whitespace --whitespace=
                        --autosquash --no-autosquash
                        --fork-point --no-fork-point
                        --autostash --no-autostash
                        --verify --no-verify
                        --keep-empty --root --force-rebase --no-ff
                        --exec
                        "

                return
        esac
        __git_complete_refs
}

复制此函数,例如重命名为_git_whatever,随意更改并将其放入您的~/.bashrc,然后使用__git_complete gwhat _git_whatever为其创建别名。

完成将在 git whatever<TAB><TAB> 开箱即用,无需 __git_complete ... 步骤。

为防止代码重复,您可以将别名完成绑定到现有别名:

_git_xxx ()
{
  _git_rebase
}