bliof
bliof

Reputation: 2987

Hook bash autocomplete based on argument

I have the following alias for git

[alias]
    review = !git stash && git fetch origin $1 && (git branch -m $1 tmp-review-$1-$(date +%Y-%m-%d-%H-%M-%S) || :) && git checkout -b $1 origin/$1 && :

You can use it like git review <branch-name>

How can I hook the already existing autocomplete for branches to the git review

I am searching for something like:

__git_complete gr _git_branch

but to be done based on the argument -> git review <tab>

In general is there a way to hook a bash autocompletion based on a regex or just the string match?


Solution

For git see the @Timir's response bellow.

# add completion handler for 'review' command
_git_review ()
{
    __git_complete_refs
}

An in general you can hook your own autocomplete and call the default one like:

_tralala ()
{
    cur=${COMP_WORDS[COMP_CWORD]}
    prev=${COMP_WORDS[COMP_CWORD-1]}

    if [ "$prev" = "test" ]; then
        COMPREPLY=( $( compgen -W 'ninja pizza' -- "$cur" ) )
    else
        _git
    fi
}

complete -F _tralala git

Upvotes: 1

Views: 178

Answers (1)

Timir
Timir

Reputation: 1425

Just define the following function in git-completion.bash or .bash_profile.

# add completion handler for 'review' command
_git_review ()
{
    __git_complete_refs
}

And that'll give you git review <tab> autocompletion. If you're also looking for git <tab> autocompletion to include your alias(es), you'll also need the following in git-completion.bash:

# add hook for further expansions
_git_known_expansions () 
{
    # list aliases
    echo $(git config --name-only --get-regexp alias | sed 's/alias\.//g')
}

# modify command list to include expansions
__git_commands () {
    if test -n "${GIT_TESTING_COMMAND_COMPLETION:-}"
    then
        printf "%s" "${GIT_TESTING_COMMAND_COMPLETION}"
    else
        echo "$(git help -a|egrep '^  [a-zA-Z0-9]') $(_git_known_expansions)"
    fi
}

Hope this helps.

Upvotes: 2

Related Questions